Using pipelines in templates

One of the most important feature for a web developer is how much flexibility and ease the templating engines in a language provide.

Go’s templates are as good as they get. In particular the pipelines are very useful.

Very often, we pass in a list of objects to our template and iterate over it using a range function. Consider a case, where if there is no object in the list we display a message that says “No objects found.”

Clearly, we need an if condition here, before we could use the range. We need to evaluate an expression for the if condition, which gives us a boolean value. It could get complicated, had there been no pipelines.

With pipelines, all we need to do is

{{if .posts|len |eq 0}}
        ... some HTML stuff that says "No objects found"..
        {{else}}
            {{range $index, $post := .posts}}
            .. some HTML stuff ....
            {{end}}
        </div>
        {{end}}

Here, we have a list of objects (posts), In the if condition we call len function (to find length) on posts and then pass the result (length of posts) to eq and compare it with 0. The pipelines here behave like they would in unix.

Let me know, if you think it can be further improved!

~~ Whizdumb ~~
Email : sachin.xpert@gmail.com

4 responses

  1. {{if not .posts}}
    … some HTML stuff that says “No objects found”..
    {{else}}
    {{range $index, $post := .posts}}
    .. some HTML stuff ….
    {{end}}

    {{end}}

Comments are closed.