Search code examples
jekyllliquid

How to inject a variable with Liquid?


How does one inject a variable into a html file with Liquid?

Here's the original code.

<!-- post list -->
{% for post in paginator.posts %}
  <li>
    <!-- Post Summary -->
    <!-- <a href="{{post.url | prepend: site.baseurl}}">
      <h3>{{post.title}}</h3>
    </a> -->

    {%- include post-summary.html -%}

  </li>
{% endfor %}

Here's how i'd like to refactor it...sorta

<!-- post list -->
{% for post in paginator.posts %}
  <li>
    {%- include post-summary.html -%}
  </li>
{% endfor %}
<!-- Need Mechanism to Inject 'post' -->
<!-- Post Summary -->
<a href="{{post.url | prepend: site.baseurl}}">
  <h3>{{post.title}}</h3>
</a>

Solution

  • This is described in the documentation, you can pass, in Jekyll, variables to an included file.

    So in your case:

    <!-- post list -->
    {% for post in paginator.posts %}
      <li>
        {%- include post-summary.html post=post -%}
      </li>
    {% endfor %}
    
    <!-- post summary -->
    <a href="{{ post.url | prepend: site.baseurl }}">
      <h3>{{ post.title }}</h3>
    </a>