What may be confusing to experienced programmers at first is that LXP supports the familiar dollar sign notation to
substitute a named variable (e.g., $myvariable) with its associated value in a mixed
character string.
When using LXP, it is important to understand the contexts in which variables are substituted (and the context in
which they are not). Subsequently, it is also important to understand when to use variable substitution and when not
to.
The first rule is that variables will
never
be substituted outside of an LXP tag. Example 13-9 attempts incorrectly to place the value of a variable named
variable within an LXP document.
Example 13-9. Invalid variable substitution
<lxp>
Here is my variable: $variable <!-- Wrong -->
</lxp>
Instead, suppose that the URL
https://localhost/test.lxp?setbar=foo
is opened in a browser, and
that
test.lxp
contains the snippet of LXP mark-up shown in Example 13-10.
Example 13-10. Valid variable substitution
<lxp>
<setvar bar="$setbar" /> <!-- sets bar's value to setbar's value -->
<putvar name="bar" /> <!-- output the value of bar -->
<lxp>
The mark-up in Example 13-10 opens an LXP region and uses the
<setvar> tag to assign the
value
of the variable named
setbar to a new variable named bar. Variable substitution
is correctly used in this case, because it occurs within an LXP tag.
Since the previously mentioned URL assigned a value of foo to
setbar, this means that the new variable bar will be
assigned a value of foo.
The use of the <putvar> tag introduces the second rule to watch out for in
LXP. Some tags (such as the <putvar> tag) expect to receive a literal variable name
in order to perform their job. Remember that dollar signs and at signs are not actually part of variable names; they are
only used to substitute values in place of names.
You might be inclined to think that the syntax of the <putvar> tag in Example 13-10 should have read like this:
<putvar name="$bar" /> <!-- output the value of bar -->
This would actually result, however, in the value of the variable bar being
substituted into the value of the name attribute. Since the value of the
bar variable is foo, LXP would attempt to insert a
variable with the
name
of foo.
The simplest way to know whether or not to use substitution characters is to remain aware of what the purpose of the
tag is. If an attribute should be substituted with a variable's
value
, use the
$ symbol to substitute it. If an attribute is literally specifying a variable by name, as
with the <putvar> tag, do not substitute it.
A literal dollar sign ($) may be used within double quotes by placing two of them
immediately one after the other, sequentially (e.g., <setvar price="$$99.95" />).
Note: When using substitution, if a variable with the specified name is not found, LXP will check for a cookie with the
specified name. If one is found, its value will be substituted.