Can you do something similar to using "with" in twig's include tag (http://twig.sensiolabs.org/doc/tags/include.html), but instead with includeJsFile?

I am using a plugin to filter my entries by their tags. The js initiation for this plugin requires me to list all the tags I'm using as a variable. I'd love to assign a variable to the tag group I'm using and pass it to the javascript file, rather than hard code the tag names. Is this possible?


You can't pass a JS variable into a JS file (that doesn't quite make sense). What you can do is to create a JS variable, and make it accessible to the script you are including.

So you'd include your JS file as you are already doing:

{% includeJsFile 'path/to/file' %}

And then you would create your variable, and in JavaScript pass that variable back into the script which you called.

{% includejs %}
    var myData = 'whatever your data needs to be';
{% endincludejs %}

The snag you're going to run into here is, the order matters. When you use Craft's include methods, they will always include any files before any raw scripts. So using this method, your variable will be defined after the file has already been included.

It's important to note, the "files before raw scripts" will happen regardless of which order you defined them in Twig.

Similarly, be aware that your file include and raw script include will both happen at the bottom of the page, just before the closing </body> tag.

Now I'm going to make an assumption... You're about to say "But I need my variable declared before the file is included!"

Fair enough, and the solution is pretty simple. Just declare your JS variable in the middle of the page, while you're rendering the main Twig code:

    var myData = 'whatever your data needs to be';

So your variable declaration gets rendered along with the rest of your HTML, and your includeJsFile still happens at the bottom of the page. By the time that file is included, your JS variable is sitting around waiting for it.

  • Thanks for your answer! I can't get anything in a <script> tag to work, though - even just a console.log. Also, am I able to use twig outputs in the <script> tag like {{ craft.tags }}? Aug 11 '15 at 19:16
  • Sounds like a separate question... Would you mind posting a new question with some code examples of what you've tried so far?
    – Lindsey D
    Aug 11 '15 at 19:55
  • Also, if this solution answered your original question, feel free to mark it as "accepted" :)
    – Lindsey D
    Aug 11 '15 at 19:58
  • Sure, I'll post a new question about the script tags. I think your explanation will work, but since I can't declare the variable in the script tag, I can't verify yet. Aug 12 '15 at 20:18
  • I've posted my new question here. I was able to print to the console after a little more debugging, but I still can't get it to accept a twig output. Aug 12 '15 at 20:52

Your Answer

