Home > Enterprise >  How to define class selector in a Jekyll liquid tag?
How to define class selector in a Jekyll liquid tag?

Time:10-13

I have some html code in my Jekyll website, in which there is some Jekyll generated content, with liquid tags. When I style the content, CSS does not get applied to the said content.

To be specific, I have this html code:


<p class="post-excerpt">
    {{post.excerpt | truncatewords : 40 }}
</p>

Which I try to style in my CSS with the relevant class selector:

.post-excerpt{
   font-size: 1.2vw;
   // and so on and so forth
}

However, the CSS styling is being ignored. Upon inspecting the Jekyll-generated .html, I saw that it is generated like this:

<p class="post-excerpt">
    <p> This is the content of the post's excerpt blah blah </p>
</p>

And the paragraph element inside is left unstyled. If I then manually add styling in the generated .html to the inner <p> element, then it works.

How can I solve this issue so that the styling properly gets applied to the actual content and not just the wrapper paragraph?

Thanks :)

CodePudding user response:

I would try in markdown

{: .post-excerpt }
{{post.excerpt | truncatewords: 40 }}

So you will create a <p> with the class post-excerpt

UPDATE:

with HTML

{% capture my_post_excerpt %}{{post.excerpt | truncatewords: 40 }}{% endcapture %}

{: .post-excerpt }
{{ my_post_excerpt }}

Or with this

{% capture my_post_excerpt %}{{post.excerpt | truncatewords: 40 }}{% endcapture %}

<p class="post-excerpt">
    {{ my_post_excerpt }}
</p>

A dirty workaround could also be change the css, add the inner and outer p to the css.

p.post-excerpt p {
   font-size: 1.2vw;
   // and so on and so forth
}

CodePudding user response:

With the help of @kargware, I found a semi-hacky way to make it work. You can capture the content and then replace the <p> with <p class='class-selector-name'> like so:

<p>
{% capture my_post_excerpt %}{{post.excerpt | truncatewords: 40 }}{% endcapture %}
{% assign my_post_excerpt = my_post_excerpt | replace: "<p>", "<p class='post-excerpt'>" %}
{{ my_post_excerpt }}
</p>

This produces the following HTML in the generated files:

<p>
<p class='post-card-excerpt'>This is the content of the post's excerpt blah blah</p>
</p>

and the CSS styling gets applied normally :)

If there is a more correct way to do this, I'd love to know it!

  • Related