Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare a string's size / length in Jekyll's Liquid templates?

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 %} 
like image 312
Cory Gross Avatar asked May 26 '13 19:05

Cory Gross


People also ask

How do you count liquids?

Pour the liquid into the container and record the weight of the container plus the liquid. Subtract the weight of the container to get the weight of the liquid. Look up or calculate the density of the liquid, then determine the volume of the liquid by dividing the mass of the liquid by the density.

What is liquid Jekyll?

Liquid is a templating language used in Jekyll to process your site's pages. In other words, it helps you make your HTML pages a bit more dynamic, for example adding logic or using content from elsewhere. This doesn't require any setup - we can just start using it.


1 Answers

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.

like image 165
Connor Spencer Harries Avatar answered Oct 01 '22 03:10

Connor Spencer Harries