{% js %} Tags

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

{% js %}
    _gaq.push([
        "_trackEvent",
        "Search",
        "{{ searchTerm|e('js') }}"
    ]);
{% endjs %}

TIP

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) %}

Parameters

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

Position

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

KeywordDescription
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.

WARNING

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.