XSLT:使用apply-templates时将变量传递给模板

时间:2014-07-30 13:14:28

标签: xslt symphony-cms

我不确定这是否过多地要求XSLT,但是我之后的问题类似于mode的工作方式,理想情况是在一个模板中,而不是像我现在:

<!-- Start -->
<xsl:apply-templates select="airports/airport" mode="start" />

<!-- End -->
<xsl:apply-templates select="airports/airport" mode="end" />

<!-- Template -->
<xsl:template match="airports/airport" mode="start">
    <option value="{@iata}" data-alternative-spellings="{.},{@iata}">
        <xsl:if test="@iata = 'LGW'">
            <xsl:attribute name="selected">selected</xsl:attribute>
        </xsl:if>
        <xsl:value-of select="@iata"/> - <xsl:value-of select="."/>
    </option>
</xsl:template>
<xsl:template match="airports/airport" mode="end">
    <option value="{@iata}" data-alternative-spellings="{.},{@iata}">
        <xsl:if test="@iata = 'LAX'">
            <xsl:attribute name="selected">selected</xsl:attribute>
        </xsl:if>
        <xsl:value-of select="@iata"/> - <xsl:value-of select="."/>
    </option>
</xsl:template>

如果值是特定的值,则模板应用selected属性。该值需要根据调用模板的内容而有所不同。有两种情况,startend都有不同的标准。

解释我尝试做的最简单的方法是让我用另一种语言写一下:)

<!-- Start -->
getAirports(start);

<!-- End -->
getAirports(end);

<!-- Template -->
var getAirports = function(position)
{
    var selected = '';
    switch(position)
    {
        case 'start':
            if(iata == 'LGW')
            {
                var selected = 'selected="selected"';
            }
        break;
        case 'end':
            if(iata == 'LAX')
            {
                var selected = 'selected="selected"';
            }
        break;
        default:
        break;
    }
    return '<option value="'+iata+'" data-alternative-spellings="'+iata+','+name+'" '+selected+'>'+iata+' - '+name+'</option>';
}

这在xslt中是否可行,或者我是否必须坚持复制模板并使用mode

谢谢!

1 个答案:

答案 0 :(得分:3)

一位Twitter用户给了我解决方案,可在此Gist中找到。

我需要的是with-param,这是我之前从未使用过的东西:

<!-- Start -->
<xsl:apply-templates select="airports/airport">
    <xsl:with-param name="position" select="'start'" />
</xsl:apply-templates>

<!-- End -->
<xsl:apply-templates select="airports/airport">
    <xsl:with-param name="position" select="'end'" />
</xsl:apply-templates>

<xsl:template match="airports/airport">
    <xsl:param name="position" />
    <option value="{@iata}" data-alternative-spellings="{.},{@iata}">
        <xsl:if test="(@iata = 'LGW' and $position = 'start') or (@iata = 'LAX' and $position = 'end')">
            <xsl:attribute name="selected">selected</xsl:attribute>
        </xsl:if>
        <xsl:value-of select="@iata"/> - <xsl:value-of select="." />
    </option>
</xsl:template>
相关问题