Skip to content

How can I use javascript code in an external file with twig elements?

I have a lot of javascript code one my twig template home.html.twig, for example:

$(document).ready(function () {

  var table = $('.datatable').DataTable({
        "responsive": true,
        {% if output.json == true %}
          "serverSide": true,
          "ajax": {
          "url": '{{ path('json', { 'fileName': output.fileName, 'length':|default(10), 'start'|default(0)  }) }}',
          "data": { }
        {% else %}
          "data":{{|raw }},
        {% endif %}

Because the source code of my main page is now full of javascript I try to move it into an external file, to have a more clean appearance:

<script src="{{ absolute_url(asset('js/script.js')) }}"></script>

But it does not work because I have so much twig variables, and they are not recognized anymore.

For every twig variable I get an error message, like this for example:

SyntaxError: expected property name, got '{'



First of all (as the comments already said) it is not a good idea to mix JavaScript with Twig.

  • Makes your code hard to maintain, hard to read and hard to understand
  • Syntax errors and JavaScript errors might happen quite easily
  • Probably messes up syntax highlighting in IDEs
  • etc.

How to improve this situation? Obviously you have the variable output. You might do the following in your main file:

var output = {{ output|json_encode() }};

Within script.js you might do something like:

$(document).ready(function () {

 let options = { "repsonsive": true };

 if(output.json === true) {
   options.serverSide = true;
   options.ajax = { ... }
 } else { =
  var table = $('.datatable').DataTable(options);

Use this process of refactoring also to clean and restructure your code and especially keep JavaScript and CSS seperated from the Twig files as good as possible.

User contributions licensed under: CC BY-SA
1 People found this is helpful