Home >Web Front-end >CSS Tutorial >Using Jade and Grunt to Speed Up HTML Production

Using Jade and Grunt to Speed Up HTML Production

Christopher Nolan
Christopher NolanOriginal
2025-02-24 08:24:19240browse

Using Jade and Grunt to Speed Up HTML Production

Which compiles into:

<span><span><!DOCTYPE html></span>
</span><span><span><span><html</span>></span>
</span>  <span><span><span><head</span>></span>
</span>    <span><span><span><title</span>></span> Jade Tutorial <span><span></title</span>></span>
</span>  <span><span><span></head</span>></span>
</span>  <span><span><span><body</span>></span>
</span>    <span><span><span><p</span> class<span>="className"</span> id<span>="idName"</span>></span> Hello SitePoint Readers! <span><span></p</span>></span>
</span>    <span><span><span><img</span> src<span>="images/image.png"</span>></span>
</span>  <span><span><span></body</span>></span>
</span><span><span><span></html</span>></span></span>

Using Jade, you don’t have to write closing tags, which helps avoid potential mistakes, such as forgetting to add closing tags or losing the correct order of them. Any text at the beginning of a line is interpreted as a tag. You need to use proper indentation for each tag.

Note: if the tag name is omitted, a div will be created as a default tag.

To add attributes to a tag, put them inside parentheses after the tag name and follow the name=value format. To separate multiple attributes, use a comma. In addition, classes and IDs can be written with . and # symbols respectively, as in the previous example.

Using the Pipe Character (|)

Sometimes we need to write the raw content of a tag on a new line but, as I mentioned earlier, any text at the beginning of a line is considered a tag. To avoid this, use the pipe or | character at the beginning of the line and write the inner text for the tag on the new line.

Note: in order to see the changes you made in the Jade file by compiling it you need to run grunt based on the Grunt task we created before.

Powerful Jade Features with Grunt

In the previous section, I gave you a quick overview of Jade’s syntax. In the following sections, we’ll go over some other common and powerful Jade features, along with a few more advanced ones. We’ll do this by going through a simple “job vacancies page” sample. You can find the full examples for each case in the source code files or from this GitHub repo. Let’s start!

Block and Extend (Jade Inheritance)

The file called layout.jade will be the basic structure for our page’s layout, and this is a kind of DRY concept, as you don’t need to write these tags for each page. Instead you need to extend the layout and start to write the block content specific code, as we will see.

Blocks are kind of separating or organizing the layout. It can then be overwritten in another file.

NOTE: The CSS and JavaScript code are removed for brevity and focus. You can find these in the repo. Also, I’ve used the copy Grunt task for transferring the js and style directories from the app directory to the build directory.

Here is the layout.jade file:

doctype html
html(lang="en" dir="ltr")
  block head
    include partials/head.jade

  body
    block content
    block footer
      include partials/footer.jade

You can create footer.jade and head.jade according to your needs. For our page, we will use Foundation and jQuery to help us establish some basic design and functionality.

Here is the partials/head.jade file:

head
  meta(name="viewport", content="width=device-width, initial-scale=1.0")
  meta(charset="UTF-8") 
  title Jobs
  link(rel = "stylesheet" href = "style/foundation.min.css")
  link(rel = "stylesheet" href = "style/app.css")

Here is the partials/footer.jade file:

<span><span><!DOCTYPE html></span>
</span><span><span><span><html</span>></span>
</span>  <span><span><span><head</span>></span>
</span>    <span><span><span><title</span>></span> Jade Tutorial <span><span></title</span>></span>
</span>  <span><span><span></head</span>></span>
</span>  <span><span><span><body</span>></span>
</span>    <span><span><span><p</span> class<span>="className"</span> id<span>="idName"</span>></span> Hello SitePoint Readers! <span><span></p</span>></span>
</span>    <span><span><span><img</span> src<span>="images/image.png"</span>></span>
</span>  <span><span><span></body</span>></span>
</span><span><span><span></html</span>></span></span>

In the next snippet of code, we will create jobs.jade, which uses all the other files by inheriting our layout using the extends keyword and then overwriting the blocks that we need. In this example, we overwrite the content block.

jobs.jade:

doctype html
html(lang="en" dir="ltr")
  block head
    include partials/head.jade

  body
    block content
    block footer
      include partials/footer.jade

But what if we don’t need to overwrite the entire block? What if we just need to add content instead? Let’s take block head as an example. We need to add a special script for this page in the header, so we will use the append or prepend keywords after block.

head
  meta(name="viewport", content="width=device-width, initial-scale=1.0")
  meta(charset="UTF-8") 
  title Jobs
  link(rel = "stylesheet" href = "style/foundation.min.css")
  link(rel = "stylesheet" href = "style/app.css")

Using Iterations and Mixins

In the previous section, we included job-container.jade. In this section, we will look at the benefit of loops and mixins and how we can use them it in Jade.

Here is the initial version of a new code snippet:

div#footer.row
  div.small-12.large-12.columns
    p Copyright (c) foobar
script(src="js/jquery.min.js")
script(src="js/foundation.min.js")
script(src="js/app.js")

As you see, we’re using multiple normal loop statements like the one on the first line - each job in jobs. The - character is used for unbuffered code that does not add any output directly.

In the previous snippet of code, there is redundant code that can become DRY-ier using mixins, as in the following code:

extends layout.jade
block content
  div#container.row
    div.small-12.large-12.columns
      include job-container.jade

Here we’re creating a reusable block of Jade using the mixin feature. Mixins are like methods (or functions) that have names and take arguments to evaluate in their inner code. In the above example, we created a mixin called skillsBlock().

To use this mixin, we just write its name and pass the proper parameter values, prefixing the mixin name with a sign to identify it as a mixin call.

NOTE: as in the above code, we can evaluate values either by =, != or #{}. But be careful when you use !=, which does not do any escaping, so is not safe for user input.

Passing JSON Data Through Grunt

After establishing our environment, let’s do some awesome stuff with the combination of Grunt and Jade by passing JSON data from a JSON file to Jade using a Grunt task.

At first, create the JSON file data.json, and fill it with your desired data.

Then open Gruntfile.js and add the data attribute to the options of the Jade task, as follows:

// append head can be used without block 'append head'
block append head 
  script.
    alert('Welcome to SitePoint')

The jobs data/locals (data passed to Jade templates are called locals) attribute will be passed to the Jade files identified in the files property and can be used in the Jade code. This manner gives you the ability to add text content to web pages easily.

Lastly, you can see how the page looks if you check out the demo. Of course, the source is compiled so the demo is of little importance in this case. A screenshot is shown below.

Using Jade and Grunt to Speed Up HTML Production

Wrapping Up

Reasons to use template engines may vary, but they can be categorized as more productivity, less repetition, and having a more pleasant syntax. Also, you might not want to write code in the native language because it is too repetitive, error-prone, or maybe you simply don’t like it. This is where a language like Jade, tuned to keeping your code concise and simple, comes into play.

Jade helps you write cleaner code, which makes it less tedious to do your job. We’ve covered some of the basics and tips and tricks using Grunt. There is more you can learn about Jade that we didn’t cover in this tutorial, so you can check out the official documentation for more.

Frequently Asked Questions (FAQs) about Using Jade and Grunt to Speed Up HTML Production

What is Jade and why should I use it for HTML production?

Jade, now known as Pug, is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js. It simplifies the process of writing HTML by allowing you to write clean, readable code that is easy to maintain. It also supports dynamic code, reusable blocks, and includes, which can significantly speed up HTML production.

How does Grunt complement Jade in speeding up HTML production?

Grunt is a JavaScript task runner that automates repetitive tasks like minification, compilation, unit testing, and linting. When used with Jade, Grunt can automate the process of compiling Jade templates into HTML, which can save a lot of time and effort in the long run.

How do I install Jade and Grunt?

Both Jade and Grunt can be installed via npm (Node Package Manager). You can install Jade by running ‘npm install jade -g’ and Grunt by running ‘npm install grunt-cli -g’ in your terminal or command prompt.

How do I convert HTML to Jade?

There are several online tools available that can convert HTML to Jade, such as html2jade.org and codebeautify.org. However, if you want to convert HTML to Jade programmatically, you can use the ‘html2jade’ npm package.

What are the benefits of using online tools for HTML to Jade conversion?

Online tools for HTML to Jade conversion are easy to use and do not require any installation. They can quickly convert your HTML code to Jade syntax, which can be very helpful if you are new to Jade or if you have a large amount of HTML code that needs to be converted.

How do I use the ‘html2jade’ npm package for HTML to Jade conversion?

After installing the ‘html2jade’ package via npm, you can use it to convert HTML to Jade by running ‘html2jade yourfile.html’ in your terminal or command prompt. This will output the Jade equivalent of your HTML code.

Can I use Jade with other task runners like Gulp?

Yes, Jade can be used with other task runners like Gulp. There are plugins available for Gulp that can compile Jade templates into HTML, similar to Grunt.

How do I include external files in my Jade templates?

You can include external files in your Jade templates using the ‘include’ keyword followed by the path to the file. This can be very useful for including common elements like headers and footers in multiple templates.

Can I use JavaScript in my Jade templates?

Yes, Jade supports inline JavaScript. You can use the ‘-‘ character to start a line of JavaScript code in your Jade templates.

How do I debug errors in my Jade templates?

Jade provides detailed error messages that can help you debug errors in your templates. If you are using Grunt, you can also use the ‘grunt-contrib-jade’ plugin which provides a ‘jade:debug’ task for debugging Jade templates.

The above is the detailed content of Using Jade and Grunt to Speed Up HTML Production. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn