0

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 %}
Brad Bell
  • 67,440
  • 6
  • 73
  • 143
William Spark
  • 381
  • 3
  • 9

3 Answers3

2

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>
<html>
<head></head>
<body>

{# This outputs the JavaScript from mypage.twig #}
{{ getFootHtml() }}
</body>
</html>
Stephen Lewis
  • 2,429
  • 11
  • 17
2

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

{% if craft.request.lastSegment == "" %}
  {# do something #}
{% endif %}
Phil H
  • 21
  • 1
2

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

andrew.welch
  • 11,551
  • 22
  • 31