Cleaning Liquid generated whitespace

Updated on 20-October-2016 at 10:16 AM

Business Catalyst End of life announcement - find out more details.

This articles tackles a known aspect of Liquid, where generated output will include whitespaces. This can be removed by using a dash before the end of the liquid end tag:

-%}

Example

Let's say you're building a drop-down containing the tags on your site. Normally you'd use seomthing like this:

{module_data version="v3" resource="tags" collection="tags"}
    
    <select>
{%for item in tags.items %}
	{% if item.tagName contains 'tag' %}
		<option {% if item.tagName contains '1' %}selected{%endif%}>{{item.tagName}}</option>
    {%endif%}
{%endfor%}
    </select>

The above code would generate the following markup:

    <select>

	
		<option selected>tag#1</option>
    

	
		<option >tag#2</option>
    

	
		<option >tag#3</option>
    

	
		<option >tag#4</option>
    

	
		<option >tag#5</option>
    

	
		<option >tagone</option>
    

    </select>

Now that's bad markup, for reasons such as performance, SEO, and even debugging. Placing - at the end of the liquid tag solves this problem:

{module_data version="v3" resource="tags" collection="tags"}
    
    <select>
{%for item in tags.items -%}
	{% if item.tagName contains 'tag' -%}
		<option {% if item.tagName contains '1' -%}selected{%endif%}>{{item.tagName}}</option>
    {%endif%}
{%endfor%}
    </select>

Now the rendered markup turns into this:

    <select>
		<option selected>tag#1</option>
		<option >tag#2</option>
		<option >tag#3</option>
		<option >tag#4</option>
		<option >tag#5</option>
		<option >tagone</option>
    </select>

Next, let's put in place the actual instance of module_data that will render the blog posts, filtered with these variables:

{module_data resource="blogposts" version="v3" fields="id,postTitle,releaseDate,postBody,author,postUrl" where="\{'blog.id':'13506','author.id:'{{author}}','tags.tagId':'{{mytag}}'\}" collection="postcollect" template="blogcustom.tpl"} 

Finally, we wrap up with a script that passes the variables selected from the form to the url, and updates the values on these drop-downs, based on our selection, after the page is refreshed:


<script>
            {% if globals.get.auth %} 
			$('#author').val('{module_url,auth}');
            {% endif %} 
 $("#values").submit(function(event) {
                event.preventDefault();
                // window.location = window.location.protocol + "//" + window.location.host + window.location+hre"?mytag=" + $('#tag').val() + "&auth=" + $('#author').val()
                window.location.search = "mytag=" + $('#tag option:selected').val() + "&auth=" + $('#author option:selected').val()
            });
</script>

Conclusion

With Liquid, it's best practice to use the -%} ending tag so no white lines are generated in your markup.