symfonytemplatestwiggrav

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


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


Solution

  • 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 %}
    

    To enable/disable bundling and minification of assets, use the settings in /user/config/system.yaml. See AssetManager/Configuration

    assets:
      css_pipeline: true
      css_minify: true
      js_pipeline: true
      js_minify: true