23 June 2012

Add Blogger Labels to Post as CSS Classes

Developing custom templates for Blogger is not the easiest of tasks, with the strict XML requirements, proprietary blogger tag names, and the few pages of documentation that are available from Google. However, it's better than static HTML / CSS / JavaScript, with the availability of variables, basic conditional if statements, loops, and the widget structures. For instance, within the loop used to display posts on the blog homepage, there are all the usual post variables available, such as the title, the body, url, and labels, all available for use within the XML structure.

The structure can be a bit prohibiting at times though, since the XML needs to be valid. In order to output a variable, either a <data: tag or an expr: attribute needs to be used, neither of which allows for much flexibility if you want to output something more than just a simple variable. Setting variables also is not allowed in the posts sections, which further restricts options. Take for example the puzzle of trying to set your post labels as classes on your post container element. Given the current situation, it seems a near impossible task. But there is one workaround that allows for the full use of the available Blogger functions without compromising the XML structure: predefined entities.

Continuing with the example of looping through the post labels within a tag attribute, here is the code with entities. Just convert the html output surrounding the Blogger tags to entities such as &lt;&quot; and &gt; and the Blogger tags can then be moved anywhere within.


Blogger XML Markup
&lt;div class=&quot;post<b:if cond="data:post.labels"><b:loop values="data:post.labels" var="label"> -<data:label.name></data:label.name></b:loop></b:if>&quot;&gt;
  <data:post.body>
&lt;/div&gt;
Final HTML Markup
<div class="post -travel -sport">
  Post body
</div>