Search code examples
javascriptswig-template

Overriding default Swig template filter for a single tag


I need to inject a JavaScript object into an HTML script tag within a Swig template.

<script>
  var myObj = {{myObj|json_encode}};
</script>

The json_encode part works fine, but then the default HTML filter kicks in and I get this in my output:

<script>
  var myObj = {&quot;socketIOServerAddress&quot;:&quot;http://localhost:8989/&quot;}
</script>

How can I disable the default filter for this one tag?


Solution

  • Well, that was easier than expected. For some reason, I am able to chain another filter, raw, which disables the built-in filtering. A little counter-intuitive, but it works.

    <script>
      var myObj = {{myObj|json_encode|raw}};
    </script>