Generating Fancy Drop Caps for Drupal
As you can see on this page, we're generating Drop Caps for the first letter in every blog page on this site.
There are two steps within the process. Firstly, we need a way to identify the first letter in the paragraph so that we can style it with CSS. If we wanted to style the first letter of every paragraph, we could simply use a CSS identified of p:first-letter but unfortunately not every browser supports this yet, and more importantly we only want to style the first letter in the first paragraph.
To produce a solution that will work in just about every browser, we can handle this using the theming capabilities of Drupal. One of the files used to theme output within Drupal is node.tpl.php, which as the name suggests, is used to generate the output for each node (i.e. page, blog entry, story etc). Within node.tpl.php, the text that will be output is contained within a PHP variable $content - and we can modify this variable, altering the text displayed on each page.
As an example, the $content variable would hold something like
<h2>Generating Fancy Drop Caps for Drupal</h2> <p> As you can see on this page, we're generating <a href="http://en.wikipedia.org/wiki/Drop_cap">Drop Caps</a> for the first letter ...
Ideally, we'd like to alter this to something like:
<h2>Generating Fancy Drop Caps for Drupal</h2> <p> <span class="first-letter">A</span>s you can see on this page, we're generating <a href="http://en.wikipedia.org/wiki/Drop_cap">Drop Caps</a> for the first letter ...
To achieve this, we can use the preg_replace() function in php- this takes a regular expression and allows us to replace it's contents using the following code in node.tpl.php:
$content = preg_replace("/<p>(.)/", "<p><span class=\"first-letter\">$1</span>", $content, 1);
This searches for the first <p> & following letter in the $content variable and replaces it with the appropriate <span> code as required.
However, whilst this identifies the first letter of the paragraph within the HTML, we need to now put in place some CSS to style the text as required. This could be something as simple as the following:
p span.first-letter {
float: left;
font-weight: bold;
font-size: 200%;
}
To finish the job, we use the Drupal Flir module to replace the normal character with a version from an opentype font.
Note: If you want to restrict this to a particular content type such as a blog, either place the code in the node-blog.tpl.php file or do a check in the node.tpl.php file such as
if ($node->type == "blog") {
$content = preg_replace("/<p>(.)/", "<p><span class=\"first-letter\">$1</span>", $content, 1);
}
Comments
Thanks
Thanks man. This was exactly what I'm looking for!