Question

In my posts, I sometimes include the same HTML pattern. To do it so, I created pattern.html in _includes/ and include it in my posts with :

{% include pattern.html %}

I would like to add a CSS file (or any other code) in my header if, and only if, pattern.html as been used in my post. To put it in pseudo-code, I would like to get the following layouts/default.html:

<!doctype html>
<html>
   <head>
      {% if pattern.html is included in the post %} code here {% endif %}
   </head>
   <body>
      {{ content }}
   </body>
</html>

I already tried to assign a variable in pattern.html and to test it in my layout, but this assignement occurs too late: the layout is already processed. I know I can pass a variable through YALM, but my objective is to get rid of it. I would prefer not to use plugins to do this.

Was it helpful?

Solution

It seems asking the question helped me to answer it! You can use the Liquid contains in order to look for a pattern in your post.

For example, if the included pattern.html contains a particular piece of code (<!--pattern--> for instance, or any particular HTML), you can use in your head:

<!doctype html>
<html>
   <head>
      {% if content contains "<!--pattern-->" %} code here {% endif %}
   </head>
   <body>
  {{ content }}
  </body>
</html>

This can be used for any HTML pattern. For example, if you want to call the CSS file producing syntaxic coloration only if there is code in the page, use:

<!doctype html>
<html>
   <head>
      {% if content contains "<code>" %}
          <link rel="stylesheet" href="code.css">
      {% endif %}
   </head>
   <body>
  {{ content }}
  </body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top