2015-02-05 75 views
0

我對XSLT很陌生。我有以下的代碼,我相信可以作出更多的清潔/幹:使用xsl:屬性時在哪裏放置子元素?

<xsl:choose> 
    <xsl:when test="custom-link"> 
     <!-- Custom link --> 
     <a class="no-ajax" href="{custom-link/item/@handle}"> 
      <img src="//images.mysite.com/2/1120/630/5{lead-image/@path}/{lead-image/filename}" alt="" /> 
     </a> 
    </xsl:when> 
    <xsl:otherwise> 
     <!-- Organic link --> 
     <a class="no-ajax" href="/film/{primary-category/item/@handle}/{film-title/@handle}/"> 
      <img src="//images.mysite.com/2/1120/630/5{lead-image/@path}/{lead-image/filename}" alt="" /> 
     </a> 
    </xsl:otherwise> 
</xsl:choose> 

理想我只想在錨改變href。我讀過你可以這樣做:

<xsl:element name="a"> 
    <xsl:attribute name="href"> 
     <xsl:choose> 
      <xsl:when test="custom-link"> 
       <!-- Custom link --> 
       <xsl:value-of select="custom-link"/></xsl:text> 
      </xsl:when> 
      <xsl:otherwise> 
       <!-- Organic link --> 
       <xsl:value-of select="organic-link"/></xsl:text> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:attribute> 
</xsl:element> 

但我不太明白如何把鏈接值

回答

1

脫離上下文來評估代碼是非常困難的。我相信以下內容:

<a class="no-ajax"> 
    <xsl:attribute name="href"> 
     <xsl:choose> 
      <xsl:when test="custom-link"> 
       <xsl:value-of select="custom-link/item/@handle"/> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:value-of select="concat('/film/', primary-category/item/@handle, '/', film-title/@handle, '/')"/> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:attribute> 
    <img src="//images.mysite.com/2/1120/630/5{lead-image/@path}/{lead-image/filename}" alt="" /> 
</a> 

簡化了您現在所擁有的功能 - 所以如果工作正常,應該這樣做。但我無法測試它。

1

另一種方法是使用xsl-attribute

<a class="no-ajax> 
    <xsl:attribute name="href"> 
     <xsl:choose> 
      <xsl:when test="custom-link"> 
       <xsl:value-of select="custom-link/item/@handle"/> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:value-of select="concat('/film/', primary-category/item/@handle, '/', film-title/@handle, '/')"/> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:attribute> 
    <img src="//images.mysite.com/2/1120/630/5{lead-image/@path}/{lead-image/filename}" alt="" /> 
</a> 
+0

這不起作用:您不能使用*屬性值模板*和''的'select'屬性。 – 2015-02-05 16:09:43

+0

你仍然在模仿他的道路,你剛剛拿出了{},就好像他們沒有任何意義。他們是這樣。 – 2015-02-05 16:37:50

+0

您的代碼將查找源XML文檔中(單個)節點的值。該節點的路徑從根元素「/ film」開始。無論在該節點上發現什麼(如果它存在*)都將是「href」屬性的內容。我的代碼查找**兩個**節點的內容,然後將其與**文本文本**結合起來 - 所以最後,「href」屬性的內容(即生成的HTML文檔中的實際鏈接)將會是一個以'/ film'目錄開頭的URL。所以這是兩個非常不同的結果。 - (*)我可以告訴你確定節點不存在,因爲... – 2015-02-05 16:59:02

相關問題