What does capturing a liquid variable then assigni

2019-06-09 03:45发布

问题:

Jekyll bootstrap includes the file _includes/JB/setup:

{% capture jbcache %}
  <!--
  - Dynamically set liquid variables for working with URLs/paths
  -->
  {% if site.JB.setup.provider == "custom" %}
    {% include custom/setup %}
  {% else %}
    {% if site.safe and site.JB.BASE_PATH and site.JB.BASE_PATH != '' %}
      {% assign BASE_PATH = site.JB.BASE_PATH %}
      {% assign HOME_PATH = site.JB.BASE_PATH %}
    {% else %}
      {% assign BASE_PATH = nil %}
      {% assign HOME_PATH = "/" %}
    {% endif %}

    {% if site.JB.ASSET_PATH %}
      {% assign ASSET_PATH = site.JB.ASSET_PATH %}
    {% else %}
      {% capture ASSET_PATH %}{{ BASE_PATH }}/assets/themes/{{ page.theme.name }}{% endcapture %}
    {% endif %}  
  {% endif %}
{% endcapture %}{% assign jbcache = nil %}

I understand that this 1) captures the text as a variable then 2) assigns it to nil immediately, effectively throwing it away. So what does this do?

回答1:

Because you want the side-effects of rendering but don't want the rendered output. If you don't capture, the rendered content is output. But you don't actually want the output, so you throw it away when you're done. It's a slight hack.

So if you want to compute without outputting the result, capturing in a variable is a reasonable thing to do. The "then assign to nil" hack is a way of saying we are interested in the side-effects of the rendering computation, not the output. Those other assignments persist have effects that persist even when the variable is thrown out.

The {%include custom/setup %}'s output will similarly be thrown away, but its side-effects may be important.