Eleventy: Liquid Custom Tag, Need Help

Created on 22 Jun 2018  路  7Comments  路  Source: 11ty/eleventy

Hi.

I just created a Universal filter and it works

 // Universal filters (Adds to Liquid, Nunjucks, and Handlebars)
  eleventyConfig.addFilter("cacheBuster", function(value) {
    let milliseconds = Date.now();
    return value + "?Rev=" + milliseconds;
  });

It's being used as follows

<script src="{{ '/dist/vendor.js' | url | cacheBuster}}"></script>

And it returns <script src="/dist/vendor.js?Rev=1529687538285"></script>



How can I make this into a liquid tag? The intent is to use it as follows

{% cacheBuster %}

It should return ?Rev=1529686251216

My failed attempt was the following:

  eleventyConfig.addLiquidTag("cacheBuster", function(scope, hash) {
    let milliseconds = Date.now();
    return Promise.resolve("?Rev=" + milliseconds); // ?Rev=1529686251216
  });

The issue is that there is no output from the tag.

Thanks for the help in advanced.

education

All 7 comments

Yeah, sorry鈥攃ustom tags are kind of hairy. This is getting simplified as we speak in #13.

You鈥檙e close, but your addLiquidTag isn鈥檛 quite right. You basically want to match this example from the Liquid documentation:

https://github.com/harttle/liquidjs#register-tags

Here鈥檚 closer to what you want:

eleventyConfig.addLiquidTag('cacheBuster',
    function cacheBusterParse() { /* you don鈥檛 actually need to parse anything for this example */ },
    function cacheBusterRender(scope, hash) {
      let milliseconds = Date.now();
      return Promise.resolve("?Rev=" + milliseconds);
    });

Lemme know if that works for you.

If you鈥檙e reading this on email, I edited the code!

I will give it a try tomorrow. Thanks again.

Hmm @navarrorc after looking at this again, I think what I sent you was wrong鈥攕o sorry. In fact, I think the example I had on the docs was wrong too.

I鈥檝e added a better documented (and correct) example to the docs:
https://www.11ty.io/docs/custom-tags/

This is what you want

eleventyConfig.addLiquidTag("cacheBuster", function(liquidEngine) {
  return {
    parse: function(tagToken, remainingTokens) {},
    render: function(scope, hash) {
      let milliseconds = Date.now();
      return Promise.resolve("?Rev=" + milliseconds);
    }
  };
});

Please reopen if you have more questions!

Hi @zachleat the code you provide works great. Thank you.

You do have a problem in the documentation, however; shouldn't the Liquid.evalValue(...) call be liquidEngine.evalValue(...) instead? I get an error, Liquid is not defined when trying to use uppercase tag.

You鈥檒l notice a require that includes the Liquid lib on the docs example but you鈥檙e right鈥攖his can be simplified! I鈥檝e updated the docs鈥攖hanks!

Was this page helpful?
0 / 5 - 0 ratings