XSLT:如何通过连接字符串和另一个变量来获取变量的值?

时间:2016-10-06 11:09:43

标签: xslt-2.0

我试图通过连接字符串和另一个变量来获取变量的值。但结果是一个带有变量名称的字符串,而不是值。因此,以下代码因尝试根据数字计算字符串而失败。值也应该是,只有变量的名称。

目标是为300px到最大4200的图像制作一个scrset。但是在srcset达到maxWidth值之前停止它。因此,如果图像的maxWidth为2000,则输出1800后迭代将停止。

这是我到目前为止的代码:

<xsl:variable name="count" select="14"/>
<xsl:variable name="maxWidth" select="2200"/> <!-- this value will be dynamic depending on each image (taken from an attribute on the image) -->

<xsl:variable name="loopIndex1" select="300"/> 
<xsl:variable name="loopIndex2" select="600"/>
<xsl:variable name="loopIndex3" select="900"/>
<xsl:variable name="loopIndex4" select="1200"/>
<xsl:variable name="loopIndex5" select="1500"/>
<xsl:variable name="loopIndex6" select="1800"/>
<xsl:variable name="loopIndex7" select="2100"/>
<xsl:variable name="loopIndex8" select="2400"/>
<xsl:variable name="loopIndex9" select="2700"/>
<xsl:variable name="loopIndex10" select="3000"/>
<xsl:variable name="loopIndex11" select="3300"/>
<xsl:variable name="loopIndex12" select="3600"/>
<xsl:variable name="loopIndex13" select="3900"/>
<xsl:variable name="loopIndex14" select="4200"/>

<xsl:attribute name="srcset"> 
    <xsl:for-each select="1 to $count">
        <xsl:variable name="index" select="position()"/>

        <xsl:variable name="source">
            <xsl:value-of select="concat('loopIndex', $index)"/>
        </xsl:variable>

        <xsl:if test="$source &lt; $maxWidth">
            http://imagescalerserver.com/?url=http://test.com/1108932.jpg&amp;w=<xsl:value-of select="concat($source, ' ')" /> <xsl:value-of select="$source" />w,
        </xsl:if>

    </xsl:for-each>
</xsl:attribute>

如果我删除测试只是为了得到一些输出,输出将是:

srcset="
http://imagescalerserver.com/?url=http://test.com/1108932.jpg&w=loopIndex1 loopIndex1w,
http://imagescalerserver.com/?url=http://test.com/1108932.jpg&w=loopIndex2 loopIndex2w,
etc
"

想要的结果是:

srcset="
http://imagescalerserver.com/?url=http://test.com/1108932.jpg&w=300 300w,
http://imagescalerserver.com/?url=http://test.com/1108932.jpg&w=600 600w,
etc
"

我还需要在最后一项之后没有逗号。意思是如果http://imagescalerserver.com/?url=http://test.com/1108932.jpg&w=600 600w,是最后一个输出,则结尾处的逗号不会出现,如下所示:

http://imagescalerserver.com/?url=http://test.com/1108932.jpg&w=600 600w

理想情况下,我不想制作loopIndex变量,而只需将值增加300,总共14次迭代,但由于变量无法更改,因此这是我管理过的最好的。如果有更好的方法,我会很高兴听到它。

1 个答案:

答案 0 :(得分:1)

声明单个变量<xsl:variable name="loopIndex" select="300, 600, 900, ..., 4200"/>(您需要在代码中拼出...),然后您可以设置

<xsl:variable name="source" select="$loopIndex[current()]"/>

for-each内。

相关问题