1

I'm new to XSLT and I'm not sure I am using the right wording for a node that I am creating in my template rather than one that is being processed. By 'current template node' I mean the a in this block:

<xsl:template match="item">
     <li>
         <a href="{location}">
             <xsl:value-of select="title" />
         </a>
     </li>
 </xsl:template>

I have another template match that I want to apply to the a:

<xsl:template match="a" mode="html">
    <a href="{@href}" title="this{@title}">
        <xsl:if test="number(substring(@href,1,4)='http')">
            <xsl:attribute name="class">external</xsl:attribute>
            <xsl:attribute name="target">_blank</xsl:attribute>
        </xsl:if>
        <xsl:value-of select="." />
    </a>
</xsl:template>

My question is: is it possible to apply this a template to the a I am creating in the item template or is matching like this only for context nodes? (also, for future searching, what do you call this kind of node?)

Thanks for reading.

Edit: in response to @Jim Garrison asking for my use-case, the example above is not far off. The only extra information I have to include is the node set I am working with, which looks like:

<related-links>
    <title>Link text</title>
    <location>http://link-address.whatever</location>
</related-links>

The a template I have is used to apply and 'external' class to every link placed in any node I am processing as HTML. I want to reuse it for this special related-links template. The only thing I can think to do currently is something like:

<xsl:template match="item">
     <li>
        <a href="{location}">
        <xsl:if test="number(substring(location,1,4)='http')">
            <xsl:attribute name="class">external</xsl:attribute>
            <xsl:attribute name="target">_blank</xsl:attribute>
        </xsl:if>
            <xsl:value-of select="title" />
        </a>
     </li>
 </xsl:template>

Which seems unnecessarily repetitious, especially considering this is the very beginning and I'm sure it will get more complicated. This can't be an uncommon thing to want to do... is there some other approach I should be using?

P.S. - I am using Symphony CMS which depends on libxslt so no XSLT 2.0

4

1 回答 1

3

是否可以将此模板应用于a我在item模板中创建的...?

在没有扩展的 XSLT 1.0 中,没有;匹配是并且只能在输入节点上执行。

在具有(相当常见的)node-set() 扩展的 XSLT 1.0 中,是的:将a元素或其父li元素分配给一个变量,从该变量构造一个节点集,并将模板应用于该节点集中的节点。

在 XSLT 2.0 中,是的:将a元素或其父li元素分配给变量,将模板应用于该变量值中的节点。

请注意,说“这是可能的”与说“这是个好主意”不同。可能还有其他更简单、更直接的方法可以实现您想要的。特别是,如果您的直接目标是避免在生成链接的多个位置中的每一个中重复链接相关代码,则可以使用命名模板(或在 XSLT 2.0 中也是用户定义的函数)来保存该代码,并调用它模板(或函数)从需要的地方。任何关于 XSLT 的好书(大多数认真的 XSLT 程序员都对 Michael Kay 的书发誓,但我相信还有其他好书可用)应该有助于了解如何使用命名模板和 xsl:call-template 指令,或者 user-定义的功能。

于 2013-08-30T00:02:21.097 回答