TransWikia.com

How to create different template for specific page?

Craft CMS Asked on September 30, 2020

I have added a "newsletter" page under Admin > Entries > Page [New Entry]
And the page is opening fine on the url xyz.com/newsletter

But I want to assign a different template to this url, how can I do that?
I tried creating a folder at /templates/newsletter/index.twig but that is not working at all.

One Answer

Entry templates are assigned on a per-section basis, and each section can only have a single entry template per site.

The workaround is to create a "proxy" template and use that as your section's entry template. The only responsibility for the proxy template is to {% include %} another template (the actual entry template), based on some conditions.

Here's how that proxy template could look in your case:

{% if entry.slug == 'newsletter' %}

    {# Use a special template for the "Newsletter" entry #}
    {% include 'newsletter/index' %}

{% else %}

    {# All other entries use a default "page" template #}
    {% include 'pages/page' %}

{% endif %}

Note: Using entry.slug (or entry.id, entry.title etc) for something like this is a bit fragile, because your content editor can easily change the slug and at that point the conditional will fail and the wrong template would be loaded.

A better approach is to add multiple entry types to your section (e.g. a "Newsletter" entry type and a "Page" entry type), and change the conditional to use that:

{% if entry.type.handle == 'newsletter' %}

    {% include 'newsletter/index' %}

{% else %}

    ...

Using different entry types also enables you to have different fields for different kinds of entries within the same section (which you'd typically want, when you're loading completely different templates for those entries).

Correct answer by Mats Mikkel Rummelhoff on September 30, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP