I want to load a .css file only in a certain page.
What's the magic code I need?
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityYou can register your file with Twig at the place you need it
{% do craft.app.getView().registerCssFile(alias('@assetUrl') ~ '/path/to/css') %}
{% 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
Jul 20, 2018 at 18:08
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.
entry
does not exist.
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 %}