11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
17.13k stars 493 forks source link

Using Liquid filters in Nunjucks templates #989

Open pdehaan opened 4 years ago

pdehaan commented 4 years ago

"Not really a question, more of a comment(tm)…"

liquidjs@9.9.0 was released today and they now expose their filter implementations, so it looks like you can now use eleventyConfig.addNunjucksFilter() to add liquidjs filter implementations.

Probably Almost certainly not a good idea, and probably not worth documenting, but a neat little hack if you're a Nunjucks user who is envious of some of them sweet, sweet filters.

// Where liquidjs is v9.9.0+, per https://github.com/harttle/liquidjs/issues/188
const { Liquid } = require("liquidjs");

// console.log(require("liquidjs/package.json").version); // 9.9.0

const liquidOptions = {
  extname: ".liquid",
  strictFilters: true,
  root: ["_includes"]
};
const liquidEngine = new Liquid(liquidOptions);
const liquidFilters = liquidEngine.filters.impls;

module.exports = function(eleventyConfig) {
  // eleventyConfig.setLibrary("liquid", liquidEngine);

  eleventyConfig.addNunjucksFilter("uniq", liquidFilters.uniq);

  return {
    dir: {
      input: "src",
      output: "www"
    }
  };
};

And now, in your Nunjucks templates, behold!

---
# src/test.njk
title: Liquid filters in Nunjucks templates
---

{{ [1, 2, 4, 4, 4, 3, 2, 1, 7, 3] | uniq | sort }}
{# Output: 1,2,3,4,7 #}

Next I'll have to see if Nunjucks exposes filters in a way that they could be consumed by Liquid templates.

It's still a pretty fragile workflow, and not sure it'd be any better if somebody could repackage this into an Eleventy plugin where liquidjs filters get shimmed into nunjucks without all this hassle, but... I still figure this is a hacky solution and probably not worth the hassle of building something that would need to be maintained for more than 1 user.

pdehaan commented 4 years ago

And for completeness, apparently you can access Nunjucks filters via require("nunjucks/src/filters") and then use .addLiquidFilter() as per usual:

const nunjucksFilters = require("nunjucks/src/filters");

module.exports = function(eleventyConfig) {
  eleventyConfig.addLiquidFilter("random", nunjucksFilters.random);

  return {
    dir: {
      input: "src",
      output: "www"
    }
  };
};
# src/test.liquid
title: Nunjucks filters in Liquid templates

Your random number is {{ (0..20) | random }}.
zachleat commented 1 year ago

I think the Render plugin solves this use case in a safer/less brittle way—what do you think about resolving this old one?

https://www.11ty.dev/docs/plugins/render/