0

I am using creating template parts (header, footer) but would like to know how I can add a variable, a body class to individual templates.

I see people are using stash but is there another way to set a variable on a per-page basis.

Thanks

3

The easier and faster way to do this is using Preload Text Replacements and snippets.

Snippets are parsed before Preload Text Replacements. So you can put them inside snippets.

Let me show you an example.

This is part of a snippet called doctype-and-styles-snip:

{preload_replace:pre-rootclass=""}<!doctype html>
<html class="no-js no-jquery {if segment_1 == ""}home{/if} {pre-rootclass}">
<head>
[...]

I put the CLASS on HTML instead of BODY, but the principle is the same. The {preload_replace:pre-rootclass=""} is intended to remove the unused CLASS.

On templates, you can use something like this:

{doctype-and-styles-snip}
{exp:channel:entries limit='1' require_entry='yes' disable='pagination' [...]}
<title>{title} - {site_name}</title>
{header-snip}
[...]

When you need a custom class, just add a preload_replace before the snippet. For example, this is a 404 page:

{preload_replace:pre-rootclass="404"}{doctype-and-styles-snip}
<title>Not found - {site_name}</title>
<meta name="robots" content="noindex,follow,noarchive" />
<meta name="description" content="not found" />
{header-snip}
[...]

This way, you can have custom classnames per page avoiding embeds and stash.

| improve this answer | |
0

Just wanted to add another way round this which might be helpful:

You could do something like this if you wanted to use the partial in lots of places but maybe change its styling a little depending on template (without use of conditionals).

In the template:

{preload_replace:pre_s_block_class='template_specific_class'}
{s_block}

In the snippet {s_block}:

<div class="{pre_s_block_class}">
... content ...
</div>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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