ZPT-JS tutorial - Replacing content and attributes

Replacing content

Let's see how we can replace the content of any tag by a value. Take a look at this template:

sample.html
<html>
  <body>
    <p>
      This is <span data-content="title">the title</span>.
    </p>
  </body>
</html>
                

Now we declare the dictionary and invoke ZPT:

sample.js
"use strict";

var zpt = require( 'zpt' );

var dictionary = { 
    title: "hello world!"
};

zpt.run({
    root: document.body,
    dictionary: dictionary
});
                

The resulting HTML will be:

<html>
  <body>
    <p>
      This is <span data-content="title">hello world!</span>
    </p>
  </body>
</html>
                

ZPT-JS has replaced the content of the span element by the value of the title in the dictionary (the value of dictionary.title).

Replacing attributes

Now let's see how to replace the value of the attributes. Take a look at this template:

sample.html
<html>
  <body>
    <p>
      This is <a data-attributes="href url">a link</a>
    </p>
  </body>
</html>
                

Now we declare the dictionary and invoke ZPT:

sample.js
"use strict";

var zpt = require( 'zpt' );

var dictionary = { 
    url: "https://www.gnu.org/"
};

zpt.run({
    root: document.body,
    dictionary: dictionary
});
                

The resulting HTML will be:

<html>
  <body>
    <p>
      This is <a href="https://www.gnu.org/" data-attributes="href url">a link</a>.
    </p>
  </body>
</html>
                

data-attributes supports more than one attribute (separated by ;):

sample.html
<html>
  <body>
    <p>
      This is <a data-attributes="href url; title theTitle">a link</a>.
    </p>
  </body>
</html>
                

Now we declare the dictionary and invoke ZPT:

sample.js
"use strict";

var zpt = require( 'zpt' );

var dictionary = { 
    url: "https://www.gnu.org/",
    theTitle: "GNU"
};

zpt.run({
    root: document.body,
    dictionary: dictionary
});
                

The resulting HTML will be:

<html>
  <body>
    <p>
      This is <a href="https://www.gnu.org/" title="GNU" data-attributes="href url; title theTitle">a link</a>.
    </p>
  </body>
</html>