0
votes

Is there a possibility to selectively render specific tags in a liquid template and leave the rest for a second render?

I have pages containing snippets(includes) and variables. The snippets are stored in the database and expensive to render. The variables are available only at runtime (via the URL request in the scenario of a landing page). I want to cache the page content with the snippets rendered but with all the rest of the liquid markup untouched.

So, If I have

{% snippet header %}

{% if vars.first_name %}
Welcome, {{ vars.first_name }}
{% endif %}

{% snippet footer %}

I would want the cached page content to be:

The header content

{% if vars.first_name %}
Welcome, {{ vars.first_name }}
{% endif %}

The footer content

At runtime this would be picked up from the memcached store and rendered:

The header content

Welcome, John

The footer content

Any idea on how to achieve this?

Update: Here's what I have in place already: (It works, but I am looking for a cleaner, ideally liquid-only-based solution.)

A "vars" tag which produces a variable with the given name:

{% vars first_name %} #=> {{ vars.first_name }}

And, I use modified liquid markup for everything I don't want rendered the first time:

{* if vars.first_name *}

So, currently the initial page looks like this:

{% snippet header %}

{* if vars.first_name *}
Welcome, {% vars first_name %}
{* endif *}

{% snippet footer %}

Which gets rendered once and cached as:

The header content

{* if vars.first_name *}
Welcome, {{ vars.first_name }}
{* endif *}

The footer content

Then at runtime I retrieve the cached version and replace {* with {% etc. to get

The header content

{% if vars.first_name %}
Welcome, {{ vars.first_name }}
{% endif %}

The footer content

Which I render with liquid again to get to the desired outcome.

This does the job but is not pure liquid and I was wondering if there is a cleaner solution.

Is there?

1
I don't know Liquid, but I would think you could craft the body as a snippet that gets rendered, but produces more Liquid markup. As long as you can run it back through the rendering phase, it would then render the Liquid tags that were produced in the first pass of rendering. I would assume Liquid has some way to escape the characters it uses as tags and markup. Or you could use another tempting engine like ERB to produce the first render with the snippets written in ERB.Beartech
Bear tech, I agree. I already tried this by defining a tag called vars which renders into a variable markup at first pass. {% vars first_name %} -> {{ vars.first_name}}. It works. I am mainly looking for a workaround for the conditionals.aaandre

1 Answers

1
votes
{% snippet header %}

{% raw %}{% if vars.first_name %}
Welcome, {{ vars.first_name }}
{% endif %}{% endraw %}

{% snippet footer %}

This should get you the rendering that you want to cache, and then if you re-render it through Liquid I would think it would process the runtime variable.