我有一个多语言网站,其 url 结构如下:www.mysite/en/home.htm
或www.mysite/es/home.htm
(适用于英语和西类牙语版本)。
在此 home.htm 中,我有一个来自 xml 文件的表数据。
该表的标题 <th>
,都放入 xsl 文件中。
我想根据我检测到的语言动态更改这些值 /es/
在网址中。
- 如果 URL = www.mysite/en/home.htm 则
- 描述
- 游戏类型
....
如果 URL = www.mysite/es/home.htm 则
- 描述
- 游戏技巧
- ...
有人可以帮我吗? 谢谢!
最佳答案
这种转变:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my" exclude-result-prefixes="my">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pUrl" select="'www.mysite/es/home.htm '"/>
<my:headings>
<h lang="en">
<description>Description</description>
<gameType>Game Type</gameType>
</h>
<h lang="es">
<description>Descripción</description>
<gameType>Tipo De Juego</gameType>
</h>
</my:headings>
<xsl:variable name="vHeadings" select="document('')/*/my:headings/*"/>
<xsl:template match="/">
<xsl:variable name="vLang" select=
"substring-before(substring-after($pUrl, '/'), '/')"/>
<table>
<thead>
<td><xsl:value-of select="$vHeadings[@lang=$vLang]/description"/></td>
<td><xsl:value-of select="$vHeadings[@lang=$vLang]/gameType"/></td>
</thead>
</table>
</xsl:template>
</xsl:stylesheet>
当应用于任何 XML 文档(未使用)时,会生成所需的标题:
<table>
<thead>
<td>Descripción</td>
<td>Tipo De Juego</td>
</thead>
</table>
注意:在实际应用中,您可能希望将特定于语言的数据放入单独的 XML 文件中(甚至放在文件中——每种语言一个)——在这种情况下您只需稍微更改此代码中对 document()
函数的调用即可。
更新:
OP 在评论中指出,在他的环境中禁止使用 document()
。
这里是相同的解决方案,稍加修改即可在不使用 document()
的情况下工作:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pUrl" select="'www.mysite/es/home.htm '"/>
<xsl:variable name="vrtfHeadings">
<h lang="en">
<description>Description</description>
<gameType>Game Type</gameType>
</h>
<h lang="es">
<description>Descripción</description>
<gameType>Tipo De Juego</gameType>
</h>
</xsl:variable>
<xsl:variable name="vHeadings" select="ext:node-set($vrtfHeadings)/*"/>
<xsl:template match="/">
<xsl:variable name="vLang" select=
"substring-before(substring-after($pUrl, '/'), '/')"/>
<table>
<thead>
<td><xsl:value-of select="$vHeadings[@lang=$vLang]/description"/></td>
<td><xsl:value-of select="$vHeadings[@lang=$vLang]/gameType"/></td>
</thead>
</table>
</xsl:template>
</xsl:stylesheet>
关于xml - 检测 URL 中字符串的 XSL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10497283/