如何在XSL中统一设置边框样式并全局引用?
这种复用边框样式的方式完全可行!
你想通过变量统一管理边框样式的思路非常棒,能避免后期修改时要逐个找地方改的麻烦,是XSLT里复用样式的常用技巧。不过你的写法有两处小问题,调整后就能正常工作了:
1. 正确的变量定义语法
你之前的变量定义里,select的值没有用单引号包裹,XSLT会把1pt solid black当成节点路径去查找,自然找不到正确的值。正确的写法是把字符串用单引号括起来:
<xsl:variable name="border" select="'1pt solid black'" />
或者也可以用内容体来定义变量(这种写法对新手更直观):
<xsl:variable name="border">1pt solid black</xsl:variable>
2. 正确的变量引用方式
在XSL-FO的属性里引用变量时,必须使用属性值模板(Attribute Value Templates),也就是把变量放在{}中。如果直接写$border,FO处理器会把它当成普通字符串,不会解析成变量的值。所以你的FO标签应该改成这样:
<fo:table border="{$border}" table-layout="fixed" width="100%" display-align="center"> <fo:table-column column-width="10%" border-right="{$border}"/> <fo:table-column column-width="10%" border-right="{$border}"/> <!-- 其他列的写法以此类推 --> <fo:table-header> <!-- 你的表头内容 --> </fo:table-header> </fo:table>
额外推荐:用属性集管理样式(进阶技巧)
如果你的样式不止一个属性,或者想统一管理一组相关样式,还可以用<xsl:attribute-set>来定义,灵活性更强:
<!-- 定义表格的边框属性集 --> <xsl:attribute-set name="table-base-style"> <xsl:attribute name="border">1pt solid black</xsl:attribute> <xsl:attribute name="table-layout">fixed</xsl:attribute> <xsl:attribute name="width">100%</xsl:attribute> <xsl:attribute name="display-align">center</xsl:attribute> </xsl:attribute-set> <!-- 定义列的右边框属性集 --> <xsl:attribute-set name="column-right-border"> <xsl:attribute name="border-right">1pt solid black</xsl:attribute> </xsl:attribute-set>
引用的时候直接用xsl:use-attribute-sets:
<fo:table xsl:use-attribute-sets="table-base-style"> <fo:table-column column-width="10%" xsl:use-attribute-sets="column-right-border"/> <!-- 其他列 --> <fo:table-header> <!-- 内容 --> </fo:table-header> </fo:table>
这种方式适合更复杂的样式复用场景,后期修改时只需要修改属性集的内容即可。
内容的提问来源于stack exchange,提问作者Dan Schertz
相关产品推荐
相关产品推荐

