Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Include js/css only for one page

Started by Muut Archive 11 years ago · 4 replies · 2242 views
11 years ago

Hi folks!
What's the best practice for loading styles or scripts only for one special page?

Is it a good idea to extend the javascript block from the base template inside the content block of a different template? It seems to work, but I was wondering if this is the right way to go…

Here's an example:

excerpt base.html.twig

TWIG
<head>
{% block head %}
    <meta charset="utf-8" />
    {% block javascripts %}
        {# {% do assets.addJs('jquery',101) %} #}
    {% endblock %}
    {{ assets.js() }}
{% endblock head%}
</head>

excerpt special.html.twig

TWIG
{% extends 'partials/base.html.twig' %} 

{% block content %}
    {{ page.content }}

    {% block javascripts %}
         <script src="special.js"></script>
    {% endblock %}
{% endblock %}

Any thoughts on this?

11 years ago

There are many ways to accomplish this, but for a single page, I would recommend two ways:

1) Use the Assets plugin to add the css/js right in the markdown - https://github.com/getgrav/grav-plugin-assets

2) Enable Twig processing in the page header (process: twig: true) and then use syntax like this:

TWIG
{% do assets.addJs('/mypage/special.js') %}
11 years ago

For performance I think you can duplicate or create another template and for this page use the new template. Into the template you add the twig function for add the js/css.

11 years ago

that's the 3rd way, but its more maintenance than the first two. really performance differences will be quite minimal between them all.

11 years ago

Thanks for your answers! The third way is quite similar to the one I tried to describe in my question.

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1336 9 years ago
Archive · by Muut Archive, 9 years ago
2 926 9 years ago
Archive · by Muut Archive, 9 years ago
2 4056 9 years ago
Archive · by Muut Archive, 9 years ago
1 2941 9 years ago
Archive · by Muut Archive, 9 years ago
3 1112 9 years ago