Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Or operator equivalent using mustache.js

Ok, so I know that mustache templates don't have logic, but how do I implement this:

<?php
  if ($a || $b) {
    echo $c, $d, $e;
  }
?>

... using mustache template syntax? The best I can come up with is this:

{{#a}}
  {{c}}{{d}}{{e}}
{{/a}}
{{^#a}}
  {{#b}}
    {{c}}{{d}}{{e}}
  {{/b}}
{{/a}}

... which is obviously hideous and requires me to duplicate anything inside the 'if'.

Any ideas?

like image 574
Stephen Sorensen Avatar asked Mar 16 '12 12:03

Stephen Sorensen


2 Answers

Mustache expressly forbids things like this. That's logic, and you're trying to put it in your template :)

The appropriate way would be to move the logic to your ViewModel or View object:

<?php
class MyView {
    public $a;
    public $b;
    public function aOrB() {
        return $this->a || $this->b;
    }
}

But if it were me, I'd name that function something like hasFoo or showBar, so it has a bit of semantic meaning.

Because you're handling the "should I show this block?" logic in your View or ViewModel, you're back to a normal section in your template:

{{#aOrB}}
  {{c}}{{d}}{{e}}
{{/aOrB}}
like image 70
bobthecow Avatar answered Oct 24 '22 11:10

bobthecow


For the record, that is the only way to do it with mustache. As for now (mustache 5, I believe) there is no better solution.

like image 29
ambe5960 Avatar answered Oct 24 '22 10:10

ambe5960