I’m using one template for multiple pages. On these pages there is a colour background styled with css. How can i make this colour different for every page? I’ll need some way to add a unique class to the pages to target them. Could/should i use page id?
If i were to use the same example as the modx docs page on templates, the template is the house. I want to make a row of houses using the same template. But i want the interior walls to be decorated differently!
You could certainly base it off the resource id, though a more user friendly way (especially if you have editors who need to set the colour when they create a new article/page) would be to use a Template Variable (TV).
You could create a drop-down list of colours as shown in the docs here:
To expand on digitalpenguin’s excellent answer, there are two fairly easy ways to do it with a TV called
- Show the editor the color name in the list, but store the color code (e.g,
#0c0c0c) in the TV’s value. Put a tag for the TV in the template like so:
(if you’re using a background image, put the URL of the image file in the TV).
- Same as #1, but with a class name in the TV, and do something like this in the Template:
<body class="existing class [[*color_tv]]">
The second method would allow you to change other features of the page as well if you decide to down the road.
Excellent suggestions so far, but as an additional bonus I’ve also seen people use something like this:
That gives you automatic page-specific class names you can use in your CSS in the form of
Thanks for all the suggestions. I am going to explore all of them for future reference but for the website i’m building, i figured out that i can just add the resource ID to the body tag:
<body class="fade-in page-[[*id]]">
This gives each page a unique id which worked for what i needed.
Cheers for the help
+1 for using one template. The fewer, the better in my opinion.
Just my thoughts…
These are all very good suggestions. My first impulse would be to use a Template Variable.
I’m not a big fan of using MODX resource ids for something like this, although I know that resource ids are often used in plugins like Wayfinder. But I would consider using the suggestion by @markh to get right to the point without creating a template variable.
However, since you are using CSS classes for this, would you ever need to reuse the rules from the classes you are building?
If so, I would definitely check out Template Variables. Template Variables are quite easy once you start using them and you might find a lot of use for them later with your website considering that you are using only one template. Template Variables are really powerful with websites that use very few templates.