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
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:
and then load the assets elsewhere in Twig:
To enable/disable bundling and minification of assets, use the settings in /user/config/system.yaml. See AssetManager/Configuration