Skip to content
This repository has been archived by the owner on Sep 6, 2022. It is now read-only.

Ternary operator in meteor jade #155

Open
movila opened this issue Jun 26, 2015 · 1 comment
Open

Ternary operator in meteor jade #155

movila opened this issue Jun 26, 2015 · 1 comment

Comments

@movila
Copy link

movila commented Jun 26, 2015

I'd like to use something like

li(class= isChecked ? 'checked' : '')
    input.text
    button.delete

But it seems the meteor-jade does not support ternary operator, so instead I must use

if isChecked
    li.checked
        input.text
        button.delete
else
    li
        input.text
        button.delete

See, a lot of code are redundant if ternary operator is not allowed.
Is there a better way to achieve the operation?

@dalgard
Copy link

dalgard commented Oct 14, 2015

I've modified a fork of this package that makes it possible to pass arguments to attribute helpers, besides some other useful features. The fork has been released as dalgard:jade.

I will keep the new package in sync with the original, should there be any updates, and generally continue maintenance until, hopefully, the two packages can be merged.

Regarding your case, I'm using some global logic helpers to do it in a reasonably elegant fashion:

li(class=$and(isChecked 'checked'))
  input.text
  button.delete

The trick works, because falsy values are not output in the template – if isChecked is falsy, nothing happens. The logic helpers that I use look like this:

// Return the last truthy argument
Template.registerHelper("$and", function (...args) {
  if (args[args.length - 1] instanceof Spacebars.kw)
    args.pop();

  return _.reduce(args, function (memo, item) {
    return memo && item;
  });
});

// Return the first truthy argument
Template.registerHelper("$or", function (...args) {
  if (args[args.length - 1] instanceof Spacebars.kw)
    args.pop();

  return _.reduce(args, function (memo, item) {
    return memo || item;
  });
});

// Return the first or second string depending on condition
Template.registerHelper("$tern", function (condition, first, second) {
  return condition ? first : second;
});


P.S. You can syntax highlight Jade like this:

```jade

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants