Preprocessors are only a good thing if they make your life easier.
I’ve been using CSS preprocessors for a while, but I had never found an easy workflow with HTML preprocessors. I’ve used HAML shortcuts in SublimeText, but for me, they almost create more issues than they solve. At the advice of some of the other people on my team, I gave Jade a shot.
In plain HTML, here’s an example:
<h1>Jade - node template engine</h1> <div id="container" class="col"> <p>This is Jade.</p> <p>Jade is a terse and simple templating language with a strong focus on performance and powerful features.</p> </div>
Writing this in Jade would look like this:
h1 Jade - node template engine #container.col p This is Jade. p. Jade is a terse and simple templating language with a strong focus on performance and powerful features.
Notice that it’s indentation based - you won’t have to close your HTML tags anymore, which will free you of the headache of figuring out which tag isn’t getting closed when your templates get complicated.
This keeps your HTML tidy and easy to follow.
Making This Work with WordPress
WordPress requires PHP inline with the HTML to render the template loops and put all of the pieces together. This complicates things but not too much. What it does require is a different version of Jade.
What Jaded PHP Looks Like
So what does a page template look like when we get it running? Not too different:
- get_header(); - if (have_posts()): - while (have_posts()): - the_post(); main article.container - get_template_part('title'); - get_template_part('meta'); section.main - if (get_field('post_intro')): p.intro - the_field('post_intro'); - endif; - the_content(); - get_template_part('comments'); - get_sidebar(); - endwhile; - endif; - get_footer();
Notice that it’s basically regular PHP without the opening and closing
<?php ?> tags - which is a timesaver and may prevent some typos and errors. It also makes it easier to read.
This helps with block level PHP but not so much with inline PHP. That’s still not so nice. You write it like this:
script(src!='<?php echo get_template_directory_uri(); ?>/build/js/modernizr.min.js')
Notice that the
src is written
src!=. This is to parse the PHP in the string. The PHP inside of attributes is still written normally. This isn’t ideal but it’s the only solution I’ve found.
One other thing to note is the opening and closing of tags that span across template parts, in particular your
body tags that may open in your
header.php and close in your
footer.php. If you write them in Jade format, they’ll close at the end of that template, which is not what you want. They need to be written the normal way.
Room for Improvement
I feel this approach has room for improvement. If you have a suggestion or have discovered something yourself, make a comment. I’ll be sharing more workflow improvements in future posts.