The directory
Take a look again to the dictionary:
sample.js
import { zpt } from './zpt-esm.js';
var dictionary = {
msg: "hello world!"
};
zpt.run({
root: document.body,
dictionary: dictionary
});
In this example we define a variable called msg in the dictionary. The scope of all the variables in the dictionary is global: this means it will be accesible by any ZPT-JS attribute in the template.
Defining variables
Take a look again to this template:
sample.html
<html>
<body>
<p id="p1">
...
</p>
<p id="p2" data-define="var 1">
...
</p>
<p id="p3">
...
</p>
</body>
</html>
The msg variable is accesible in the entire document, but the var one is only inside p2: Inside p1 (not defined yet) or p3 (out of scope) it is not accesible.
Redefining variables
Now we are going to define the same variable twice. Take a look again to this template:
sample.html
<html>
<body>
<div data-define="var 1">
var = <span data-content="var">must be 1</span>
<div data-define="var 2">
var = <span data-content="var">must be 2</span>
</div>
var = <span data-content="var">must be 1</span>
</div>
</body>
</html>
Here the var variable is evaluated 3 times. What value will result?
- Must be 1. The variable is defined just in the parent node with the value 1.
- Must be 2. The variable is redefined just in the parent node with the value 2.
- Must be 1. The redefinition is out of scope and the value is 1 again.
Global variables
Sometimes is useful to define global variables in a template. How?
sample.html
<html>
<body>
<p id="p1">
...
</p>
<p id="p2" data-define="global var 1">
...
</p>
<p id="p3">
...
</p>
</body>
</html>
The var variable is accesible after its declaration in p2 (accesible inside p2 and p3): Inside p1 (not defined yet) it is not accesible.
Nocall variables
When ZPT-JS finds a data-define attribute it defines the variable and set its value with the evaluated value. After that, every time the variable appears ZPT-JS will evaluate it with that value, always the same value.
But sometimes we need the expression is reevaluated every time a variable appears. How?
sample.html
<html>
<body>
<p data-define="nocall run counter()">
<span data-content="run">must be 1</span>
<span data-content="run">must be 2</span>
<span data-content="run">must be 3</span>
</p>
</body>
</html>
Suppose counter() function returns an increased value starting with 1. Then every time run value is required counter() function will be executed.
Built-in variables
So a variable is either a in dictionary variable (built-in or defined by the user), or defined via a data-define attribute. The following variables are built-in:
context. An object with some utility methods. For internal use and for customization. See context reference page for details.window. The window object.
As ZPT-JS register the window object automatically, so global variables defined via javascript can be used easily:
<div data-content="window/globalVar">a string</div>