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 %}
I am going to post this solution that I found on someone's blog. It is the only way that I have found so far so safely get the length of a passed in string and compare using anything other than straight equality. In order to make the comparison you must do subtractions and use the difference. The method is outlined in this blog post written by Ben Dunlap. It is still kind of a workaround, but it's clever and it seems like it will always work. Might not be as efficient if you wanted to do an if, elsif, else with multiple clauses, but you could still take multiple differences and make it work. Basically you would do this in my case:
{% capture difference %}{{ page.title | size | minus:20 }}{% endcapture %}
{% unless difference contains '-' %} // 20 characters or less
<h3>{{ page.title }}</h3> // show smaller header
{% else %} // More than 20 characters
<h2>{{ page.title }}</h2> // show larger header
{% endunless %}
Kind of clever, but also kind of a hack. If anyone comes up with a better way let me know.