lquasar
lquasar

Reputation: 55

Create variable in XSLT based on value of another variable

What I need to do is to create different variables (variable name) based on value of defined variable. As I am beginner with XSLT I am not quite sure how to that. Basic idea is to have something like

foo is defined and can have value 1 or 2 or 4

if (foo == 1):
    a = 1
elif (foo == 2):
    b = 1
elif (foo == 4):
    c = 1

Reason why I need to create different variables is that those variables will be used as conditions for pystache to generate file from mustache template.

All resources I found for xsl is how to assign different values with choose syntax but not how to conditionally create different variables. XML version is 1.0.

Thanks in advance for any help

Upvotes: 0

Views: 544

Answers (1)

zx485
zx485

Reputation: 29052

You can use a simple compare to true or false which will be converted to 1 or 0 by the number() function:

<xsl:variable name="foo" select="2"/>
<xsl:variable name="a" select="number($foo = 1)"/>
<xsl:variable name="b" select="number($foo = 2)"/>
<xsl:variable name="c" select="number($foo = 4)"/>
<xsl:value-of select="concat('a=',$a,'; b=',$b,' c=',$c)"/>

The output of this sample is

a=0; b=1 c=0

It is not exactly an IF-THEN-ELSE construct, but you did not specify default values in your example. If you need a more sophisticated approach, you can go back to the xsl:choose approach you mentioned for each variable a,b and c.

Upvotes: 1

Related Questions