liquidjs icon indicating copy to clipboard operation
liquidjs copied to clipboard

Support for one liner conditional statement using ternary operator.

Open sanketdhoble opened this issue 2 years ago • 2 comments
trafficstars

Does liquid js support one-liner conditional msg using ternary operator? e.g: I want to do something like this but it doesn't work.

{{ data.age == 18 ? 'You are under 18' : 'You are over 18' }}
OR
{{ data.age == 18 ? data.newVar1 : data.newVar2 }}

sanketdhoble avatar Jul 13 '23 19:07 sanketdhoble

Unfortunately no. But I agree this would be a good feature, given all the discussions I see here: https://github.com/Shopify/liquid/issues/236

While the implementation would be changing the fundamental syntax, expect this feature won't come anytime soon. I'll leave this issue open for people to track.

harttle avatar Jul 16 '23 03:07 harttle

@sanketdhoble Not sure if it helps, but I've generally used a custom filter similar to this in the past:

import { Liquid } from "liquidjs";

const engine = new Liquid();

engine.registerFilter("ternary", (value, truthyValue, falsyValue) =>
  !!value ? truthyValue : falsyValue
);
engine
  .parseAndRender('{{ data.age < 18 | ternary: "You are under 18", "You are over 18" }}', { data: { age: 8 } })
  .then(console.log); // outputs 'You are under 18'

pdehaan avatar Jul 16 '23 06:07 pdehaan