{% js %} Tags

The {% js %} tag can be used to register a <script> tag on the page.

{% js %}
        "{{ searchTerm|e('js') }}"
{% endjs %}


The tag calls yii\web\View::registerJs() under the hood, which can also be accessed via the global view variable.

{% set script = '_gaq.push(["_trackEvent", "Search", "'~searchTerm|e('js')~'"' %}
{% do view.registerJs(script) %}


The {% js %} tag supports the following parameters:


You can specify where the <script> tag should be added to the page using one of these position keywords:

at headIn the page’s <head>
at beginBodyAt the beginning of the page’s <body>
at endBodyAt the end of the page’s <body>
on loadAt the end of the page’s <body>, within jQuery(window).load()
on readyAt the end of the page’s <body>, within jQuery(document).ready()
{% js at head %}

By default, at endBody will be used.


Setting the position to on load or on ready will cause Craft to load its internal copy of jQuery onto the page (even if the template is already including its own copy), so you should probably avoid using them in front-end templates.