lazd / DOMly

The fast template system that creates and clones DOM nodes
MIT License
53 stars 9 forks source link

Allow full expressions in statements #3

Open lazd opened 10 years ago

lazd commented 10 years ago

Expressions should be allowed in statements:

  1. {{variable+1}}
  2. {{variable+method()}}
  3. {{method(variable+otherVariable)}}
  4. <if variable||otherVariable>
cespare commented 9 years ago

Yeah, <if var == "foo"> was something I just wanted today.

lazd commented 9 years ago

@cespare you can accomplish the equality comparison with a quick helper:

Helper:

function eq(a, b) {
  return a === b;
}

Template:

<if eq(data.foo,"bar")>
  <div>Yay!</div>
</if>

Output:

(function anonymous(data_0) {
  var frag = document.createDocumentFragment();
  var data = data_0;
  if (eq(data_0["foo"],"bar")) {
    var el2 = document.createElement("div");
    el2.textContent = "Yay!";
    frag.appendChild(el2);
  }
  return frag;
})

This is what we've had to do in Handlebars for years, so I'd definitely like to see this possible in DOMly. However, the whole statement needs to be a valid attribute name according to Cheerrio's HTML parser, so its impossible to throw an equals sign in there. This won't parse the way you expect it:

<div if-data.bar==='baz'='class="bazified"'>Yay!</div>

However, using the helper approach, you can easily test equality in a conditional attribute:

<if eq(data.foo,'bar')>
  <div if-eq(data.bar,'baz')='class="bazified"'>Yay!</div>
</if>

Output:

(function anonymous(data_0) {
  var frag = document.createDocumentFragment();
  var data = data_0;
  if (eq(data_0["foo"],'bar')) {
    var el2 = document.createElement("div");
    if (eq(data_0["bar"],'baz')) {
      el2.className = "bazified";
    }
    el2.textContent = "Yay!";
    frag.appendChild(el2);
  }
  return frag;
})