Home > Enterprise >  Is it possible to load JS code from .js file in Twig template as inline?
Is it possible to load JS code from .js file in Twig template as inline?

Time:07-24

I'd like to load JS code from JS file in Twig template and render it inline. As we can do it in PHP with file_get_contents('.../js/main.js').

I know I can load main.js.twig, but I need to load JS code from a file with .js extenstion

For example, main.js contains:

console.log('Works!');

And in my Twig template I try:

<script>
{% include "#{theme_dir}/js/main.js" %}
</script>

to render inline JS code like

<script>
console.log('Works!');
</script>

but I receive the error

Template ".../js/main.js" is not defined in ...

In my case Twig is used by CMS Grav

CodePudding user response:

Grav has its Asset Manager with which js/css assets can be added to Twig. Assets can be added as bundle and minified or can be inlined.

In Twig you first define the assets to add in the <head> of the page:

{% block javascripts %}
    {% do assets.addJs('jquery', 101) %}
    {% do assets.addJs('theme://js/jquery.treemenu.js', { group: 'bottom' }) %}
    {% do assets.addJs('theme://js/site.js', { group: 'bottom' }) %}
    {% do assets.addJsModule('plugin://my_plugin/app/main.js', { group: 'bottom' }) %}
{% endblock %}

and then load the assets elsewhere in Twig:

{% block bottom %}
    {{ assets.js('bottom')|raw }}
{% endblock %}

CodePudding user response:

Oh, sorry - the problem was in the path: JS file should be in /templates/ directory of Grav theme. Now it works.

Also we can use Grav read_file() function to load file content from any directory as variable and change it before rendering if we need:

<script>
{% set js = read_file("#{theme_dir}/js/main.js") %}
{{ js|raw }}
</script>
  • Related