Github – How to compare a string’s size / length in Jekyll’s Liquid templates

githubjekyllliquidtemplate-engine

I am using Jekyll on GitHub Pages in order to build a blog and am wanting to get the length of the page.title string passed to the Liquid Template in the YAML front matter in each post. I have not been able to figure out an easy way to do this. Looking at the Liquid For Designers Guide I was able to see that it supports two types of markup:

  • Output Markup – Delimited by double curly braces {{ }}, you can output variables that are passed to your template, either in the YAML front matter such as page.title in Jekyll, or the global site level variables in _config.yml. In order to output the title of the post or page you would use {{ page.title }}.

  • Tag Markup – Delimited by curly braces and percents {% %}, these are used for logic in your templates. If statements, loops, that type of thing.

Apparently there are lots of filters you can use with the Output Markup and you can output the length of a string passed to the template by using {{ page.title | size }}.

However, what I would like to do in my template is render the title of the page using either an <h1>,<h2>, or <h3> header depending on the length of the title.

I can not figure out anyway to mix the tag markup and the output markup.

I can output the size of page.title onto the page with {{ page.title | size }}, I cannot, however, figure out how to use the length in an if statement. This also returns a string representation and not a number.

Does anyone with more experience with Liquid know how to do this?

Ideally, what I would like to do is something along the lines of this:

{% if page.title | size > 5 %} 

Best Answer

I've been looking into this for doing links in my footers using the liquid syntax and it's dead simple.

{% assign thesize = variable.size %}
{% if thesize > 5 %}
    Do stuff here.
{% endif %}

Works for what I'm doing at least, just thought I'd throw it out there. I had issues using capture because of the fact it's automatically stored as a string.

Then again,

{% if variable.size > 5 %}
      Do stuff here.
{% endif %}

should work equally as well.

Related Topic