What is the best method to render Javascript on specific page using name instead of id. This is what I found but not sure how to use name instead.

{% if entry.id == 2 %}
{% endif %}

{% if entry.section == homepage %}
    //Content goes here
{% endif %}

3 Answers 3


You'd typically use the {% includeJs %} or {% includeJsFile %} tags within your page template, to specify your page-specific JavaScript, and then output everything in your layout template by calling {{ getFootHtml() }}.

Here's how your (very basic) page template might look in practice:

{# mypage.twig #}
{% extends '_layout' %}
{% includeJsFile "/assets/js/mypage.js" %}

And here's how your (equally basic) layout template might look:

{# _layout.twig #}
<!doctype html>

{# This outputs the JavaScript from mypage.twig #}
{{ getFootHtml() }}

If you want something to only appear on the homepage you could use this:

{% if craft.request.lastSegment == "" %}
  {# do something #}
{% endif %}

So the most reliable way to check to see if you're on the Craft-designated homepage (which can be either a Single, or a Structure, or what have you) would be:

{% if entry.slug == '__home__' %}
    //Content goes here
{% endif %}

As per: Add home page to a structure?

Rather than using {% includeJs %} or {% includeJsFile %} I would recommend that you use some kind of a JavaScript loader with dependency management:

Using SystemJS as a JavaScript Loader

LoadJS as a Lightweight JavaScript Loader

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.