XSLT: تطبيق القوالب ذات المعلمات الشرطية؟
-
05-07-2019 - |
سؤال
أرغب في تطبيق قالب يحتوي على معلمات مختلفة بناءً على نتيجة شرطية. شيء من هذا القبيل:
<xsl:choose>
<xsl:when test="@attribute1">
<xsl:apply-templates select='.' mode='custom_template'>
<xsl:with-param name="attribute_name" tunnel="yes">Attribute no. 1</xsl:with-param>
<xsl:with-param name="attribute_value" tunnel="yes"><xsl:value-of select="@attribute1"/></xsl:with-param>
</xsl:apply-templates>
</xsl:when>
<xsl:when test="@attribute2">
<xsl:apply-templates select='.' mode='custom_template'>
<xsl:with-param name="attribute_name" tunnel="yes">Attribute no. 2</xsl:with-param>
<xsl:with-param name="attribute_value" tunnel="yes"><xsl:value-of select="@attribute1"/></xsl:with-param>
</xsl:apply-templates>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select='.' mode='custom_template'>
<xsl:with-param name="attribute_name" tunnel="yes">Error</xsl:with-param>
<xsl:with-param name="attribute_value" tunnel="yes">No matching attribute </xsl:with-param>
</xsl:apply-templates>
</xsl:otherwise>
</xsl:choose>
بادئ ذي بدء ، أظن أنه يمكن حل هذا بطريقة أفضل بكثير. (أنا جديد تمامًا على XSLT ، لذا يرجى اقتراح التحسينات ومسامحة الكود المتضخم.)
الآن للسؤال: كيف يمكنني تعيين المعلمات بناءً على هذا الشرط ، وما زلت أستخدمها في xsl:apply-templates
؟ لقد حاولت لفها بأكمله xsl:choose
مع xsl:apply-templates
البداية/نهاية العرض ، ولكن هذا ليس قانونيًا على ما يبدو. أي أدلة؟
المحلول
تتمثل الطريقة البديلة في وضع XSL: اختر عبارات داخل XSL: Param Elements
<xsl:apply-templates select="." mode="custom_template">
<xsl:with-param name="attribute_name" tunnel="yes">
<xsl:choose>
<xsl:when test="@attribute1">Attribute no. 1</xsl:when>
<xsl:when test="@attribute2">Attribute no. 2</xsl:when>
<xsl:otherwise>Error</xsl:otherwise>
</xsl:choose>
</xsl:with-param>
<xsl:with-param name="attribute_value" tunnel="yes">
<xsl:choose>
<xsl:when test="@attribute1"><xsl:value-of select="@attribute1"/></xsl:when>
<xsl:when test="@attribute2"><xsl:value-of select="@attribute1"/></xsl:when>
<xsl:otherwise>No matching attribute </xsl:otherwise>
</xsl:choose>
</xsl:with-param>
</xsl:apply-templates>
نصائح أخرى
لا حرج في طريقتك ، ولكن يمكنك أيضًا إلحاق مشروطك بـ xsl:template match
ينسب. هذا سيؤدي إلى واحد فقط xsl:apply-templates
, ، ولكن عدة xsl:template
عناصر
يمكنك التخلص من كل هذا المنطق والأوضاع عن طريق استخراج ظروفك إلى مسببات. أنت لا تقول ما هو اسم العنصر الذي تتعامل معه ، ولكن على افتراض أنه يسمى foo
ثم يجب أن يكون هناك شيء من هذا القبيل:
<xsl:template match="foo[@attribute1]">
<!--
do stuff for the case when attribute1 is present
(and does not evaluate to false)
-->
</xsl:template>
<xsl:template match="foo[@attribute2]">
<!--
do stuff for the case when attribute2 is present
(and does not evaluate to false)
-->
</xsl:template>
<xsl:template match="foo">
<!--
do stuff for the general case
(when neither attribute1 nor attribute 2 are present)
-->
</xsl:template>