3

I want to load a .css file only in a certain page.

What's the magic code I need?

3 Answers 3

3

You can register your file with Twig at the place you need it

{% do craft.app.getView().registerCssFile(alias('@assetUrl') ~ '/path/to/css') %}
3
  • yo there isn't something like {if this page} and then print the tag? I believe that's easier.
    – dawn
    Commented Jul 20, 2018 at 17:16
  • @dawn Robin's answer is perfectly valid, and is exactly the right answer for many scenarios. If you'd like other options, please expand on your original question.
    – Lindsey D
    Commented Jul 20, 2018 at 18:05
  • You can wrap it around an {% if %} condition if you want, but usually you want to register the file where you need it. So when you include a template that requires your css file you'll register it. You can execute the line as many times as you want, Craft won't mess around and only insert the style tag once in your header Commented Jul 20, 2018 at 18:08
3

You can check a specific URL segment. For example if you need to load some CSS on the About page and that URL is yoursite.com/about you can do this:

{% if craft.app.request.segments|first == 'about' %}
    {# Load CSS #}
{% endif %}

You could also check by entry.id

{% if entry is defined and entry.id == '123' %}
    {# Load CSS #}
{% endif %}

Replace "123" with the id of the entry you'd like to load the CSS for.

2
  • 1
    Good answer. But the second one will throw an error if you're on a page where entry does not exist.
    – Lindsey D
    Commented Jul 20, 2018 at 21:30
  • Good point. I added a check for the entry being defined. Commented Jul 20, 2018 at 21:32
1

The best way to do that is to use the Parent function of Twig.

For this u have to define a block in your base template:

{% block stylesheets %}
    <link rel="stylesheet" href="{{ rev('/assets/dist/css/main.css') }}">
    <link rel="stylesheet" href="https://use.typekit.net/lrj4mhv.css">
{% endblock %}

then in your page template (wich extends the base template) u just use it like this:

{% extends "_private/layout" %}

{% block stylesheets %}
    {{ parent() }}

    {#here u can inject any css file u want to#}
{% endblock %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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