Load section-specific CSS

I always find it a little odd (because of the way I organize/link stylesheets) the way TXP associates a section to a particular stylesheet.

I usually use the default CSS as a commmon stylesheet across all sections, and then each section (or a group of them) has its own stylesheet assigned on Presentation -> Sections.

In other words, sections should not have the default CSS asigned to them. Instead, sections are assigned a particular stylesheet that usually expands/overrides/complements the default CSS.

So, default CSS is loaded in all (or almost all) sections, and then, if also needed, each section loads its own stylesheet (the one assigned on Presentation -> Sections).

The code I used to load stylesheets was this:

<!-- load default CSS in every section -->
<link rel="stylesheet" href="<txp:rvm_css n="default" />" type="text/css" media="all" />
<!-- load section - specific CSS -->
<link rel="stylesheet" href="<txp:rvm_css />" type="text/css" media="all" />

The only problem I had with this approach was if the section didn’t have its own stylesheet assigned, the default CSS was assigned instead. This usually led to the default CSS being loaded twice in the code. That may not be a problem, but it isn’t very elegant either. Of course, a few txp:if_section conditionals could do the job, but I don’t like to clutter the <head> using too many of them.

But now, with Txp 4.0.7, I can solve this problem! This is how I configure this system:

<!-- load default CSS in every section -->
<link rel="stylesheet" href="<txp:rvm_css n="default" />" type="text/css" media="all" />
<!-- assign the CSS URL to a variable -->
<txp:variable name="css" value='<txp:rvm_css n="default" />' />
<!-- check if assigned value is equal to the value of the CSS URL for that section -->
<txp:if_variable name="css" value='<txp:rvm_css />'>
<!-- do nothing: no specific CSS. This section uses just the default CSS -->
<txp:else />
<!-- This section has an specific CSS assigned to it -->
<link rel="stylesheet" href="<txp:rvm_css />" type="text/css" media="all" />
</txp:if_variable>

As you can seen, nothing fancy. And it’s not overkill either. BTW, you can replace txp:rvm_css with standard built-in txp:css.

You may find it useful if you manage section-specific stylesheets as I do.

Note: Originally posted on the forum here. This TXP Tip uses the rvm_css plugin.

comments powered by Disqus