Maksim Chemerisuk edited this page Apr 12, 2016 · 15 revisions

NOTE: information below is not relevant for better-dom version 3. DOM.emmet was moved from the library into a separate plugin https://github.com/chemerisuk/better-emmet-plugin

Html strings are annoyingly verbose. Let's fix that with Emmet. Compare the HTML string:

DOM.create("<ul><li class='list-item'></li><li class='list-item'></li><li class='list-item'></li></ul>");

to the equivalent micro template


Take a look at the Emmet cheat sheet for more examples, but be aware about the differences.

Where to use

  • DOM.create[All] could pass Emmet string to create a new element(s).
DOM.create("a.star-link>i.icon-star"), // => $Element wrapper for `<a>`
DOM.create("li*5"); // => $Elements wrapper for 5 `<li>` elements 
  • DOM.emmet converts Emmet abbreviation into a HTML string:
DOM.emmet("a+b"); // => "<a></a><b></b>"
// => "<select><option value="1"></option><option value="2"></option></select>"
DOM.mock("button.my-button"); // => mocked button

Abbreviation variables

It's a typical case when you need to create a parametrised element(s) in memory. DOM.create[All], DOM.emmet and DOM.mock[All] support optional second argument varMap that allows you to specify abbreviation variables.

DOM.create("input[name=`{name}` value=`{val}`]", {name: "my name", val: "my val"});
// => input[name="myname" value="myval"] with $Element wrapper

DOM.emmet("a[href={url}]>`{text}`", {url: "test", text: "hello"});
// => "<a href="test">hello</a>"

Note, that you need to wrap attribute values with back ticks when they contain spaces. Additionally to regular objects you can use array to make your code more compact:

DOM.create("input[name=`{0}` value=`{1}`]", ["my name", "my val"]);
// => input[name="myname" value="myval"] with $Element wrapper

DOM.emmet("a[href={0}]>`{1}`", ["test", "hello"]);
// => "<a href="test">hello</a>"

These variables internally used as macroses, so additionally to values you can parametrize any part of your abbreviation:

var options = "";

if (category === "red") {
  options = "option>`#F00`^option>`#A00`^option>`#500`";
} else if (category === "green") {
  options = "option>`#0F0`^option>`#0A0`^option>`#050`";

DOM.create("option[name=color]>{0}", [options]);
// => $Element wrapper for `<select>` that has different options depending on `category`

Do not be crazy with microtemplates!

Several recommendations from the emmet docs:

Abbreviations are not a template language, they don’t have to be “readable”, they have to be “quickly expandable and removable”.

You don’t really need to write complex abbreviations. Stop thinking that “typing” is the slowest process in web-development. You’ll quickly find out that constructing a single complex abbreviation is much slower and error-prone than constructing and typing a few short ones.

See also

Abbreviation parser differences from the emmet.io project