Article-specific CSS & JavaScript in Textpattern


Methods for loading stylesheets and scripts on a per-article basis

The problem: some JavaScript and any linked CSS files need to be included in the “ <head> of an HTML page, but in Textpattern there’s no straightforward way to do this on a per-article basis. There are any number of solutions; here is how mine has evolved.

I started with the quick-and-dirty method of hard-coded conditional statements such as this:

<txp:if_individual_article><txp:if_article_id id="24,26">
<link rel="stylesheet" type="text/css" href="<txp:site_url />css/special.css" />

Passably OK for one or two articles with identical requirements, but gets ridiculous quickly with anything more complex.

Much better to control this in the Write tab. The obvious starting point is a custom field containing a list of required items. I was already using the sed_packed_custom_fields plugin elsewhere, so I used it to iterate over the contents of the new custom field (which I named “Requires”). This markup:

<txp:sed_pcf_for_each_value name="requires" wraptag="" break="">
<txp:output_form form="require_{value}" />

calls up a form for each item listed in the field. I used the “require_” prefix simply to keep my forms organized. Each “require_” form contains the appropriate <script> and/or <link> elements to load the required files.

This works fine, giving simple custom field entries such as jQuery, Shadowbox . However, it means a lot of forms, many of them so simple as to hardly justify a separate form (each form adding a database query to the page load, and of course taking space in the Forms tab).

So I wrote a plugin, soo_required_files. You can use it as above, calling up a form, but you can also list the actual JavaScript or CSS file names in the custom field and load them directly. (The plugin has default directories for .js and .css files.) The <head> markup becomes very simple, just the one plugin tag:

<txp:soo_required_files />

Posted 2009-05-14 (last modified 2017-02-18)