1
votes

I'm trying to get Jekyll to generate a link dynamically. The link is for a CSS file, but depends on the page that is being rendered.

i.e. If the page was contact, it should render mywebsite.com/lib/css/contact.css

The problem I have is that When I try to nest liquid tags, it can't resolve the name properly. It seems to treat the entire string as literal string instead of resolving the name.

I've tried the following:

Note: layout.cssFile is a page variable that contains the name of the CSS file I wish to render.

Attempt 1:

<link href="{{ lib/css/" | append:  layout.cssFile }} | relative_url }}" rel="stylesheet">

Attempt 2:

<link href="{{ "lib/css/{{ layout.cssFile }} | relative_url }}" rel="stylesheet"> 

Attempt 3:

{% assign cssPath="lib/css/{{layout.cssFile}}" %}
  <link href="{{ cssPath | relative_url }}" rel="stylesheet"> 

None of these things work. How can I write this in a clean way that is easy to read and does what I want?

2

2 Answers

3
votes

You don't have to use double-quotes in Liquid. Single-quotes are just as fine.

<link href="{{ layout.cssFile | prepend: 'lib/css/' | append: '.css' | relative_url }}" />
0
votes

I've found a solution. However, I'm not sure if it is the best solution. If you have a better solution, please do post below.

The problem is that I wanted the double quotes to be rendered into the actual generate file since it is an href. In addition, I also want to be able to put variables resolved by liquid as part of the URL.

The solution is to use "append" filter to add liquid resolved variables and then add the relative_url filter at the very end.

<link href="{{ "lib/css/" | append: layout.cssFile | append: ".css" | relative_url }}" 

The first double quote after the equals sign marks the double quote that will be rendered into the source file that is generated. Matching that is the double quotes at the very end.

The {{ symbol you see that it follows, is the beginning of the liquid tag. The double quotes after allows the path lib/css/ to be rendered as a string.

Notice I used the pipe symbol and begin using the append filter to add the variable layout.cssFile, concatenating it with the string. I then used another append filter to tack on the css extension to the file path.

Finally, I added the relative_url filter to ensure that the link will be rendered correctly regardless of its environment. I test this on my local computer and I also want this to work online without having to make manual changes.