【问题标题】:Has anyone went from PHP templating to XSLT templating and not regretted it?有没有人从 PHP 模板转到 XSLT 模板并且不后悔?
【发布时间】:2012-04-19 10:24:31
【问题描述】:

我正在使用某个框架,主要开发人员正在考虑从基于原生 PHP 的模板彻底更改为 XSLT 模板。

我担心这不可行,因为在我们的网站上,我们通常有非常复杂的模板逻辑。

对于这么简单的事情:

    if ( $something ) { ?>
        <p><?php if ( $another ) { ?>Lorem Ipsum<?php } else { ?>Dolor amet<?php } ?>.</p>
    <?php } else { ?>
        <p><?php if ( $another ) { ?>Lorem Ipsum<?php } else { ?>Dolor amet<?php } ?>.</p>
    <?php } ?>

等效的 XSLT 是:

    <xsl:choose>
        <xsl:when test="blah">
            <xsl:choose>
                <xsl:when test="another">
                    <p>Lorem Ipsum.</p>
                </xsl:when>
                <xsl:otherwise>
                    <p>Dolor amet.</p>
                </xsl:otherwise>
        </xsl:when>
        <xsl:otherwise>
                <xsl:when test="another">
                    <p>Lorem Ipsum.</p>
                </xsl:when>
                <xsl:otherwise>
                    <p>Dolor amet.</p>
                </xsl:otherwise>
        </xsl:otherwise>
    </xsl:choose>

这么简单的代码sn-p,一想到高级场景就吓到我了。

我想知道是否有人经历过类似的模板转换,如果是,您是如何应对的?你回去了吗?

【问题讨论】:

  • 不理解 XSLT 不必担心团队选择使用它。一个合理的行动项目是扩大自己的视野。停止害怕的一个好方法是开始学习——通过阅读和练习。有很好的学习资源,包括SO的“xslt”标签中的很多问题和答案。
  • 这对我来说不是问题,我只是担心这会导致我的大多数团队的生产水平下降(接口开发,从现在开始将处理 XSLT 和模板逻辑,而不是后端开发人员),而且我们已经在紧迫的期限内运行。
  • 根据我的经验,使用 XSLT 处理 XML 比使用传统命令式语言快几个数量级。质量要高得多,错误少了几个数量级。您甚至可以用更少的开发人员完成同样的工作。

标签: php xslt templating


【解决方案1】:

在 XSLT 1.0 中,您建议的代码可以简化为:

<p>
   <xsl:choose>
        <xsl:when test="blah">
                <xsl:when test="another">Lorem Ipsum.</xsl:when>
                <xsl:otherwise>Dolor amet.</xsl:otherwise>
        </xsl:when>
        <xsl:otherwise>
                <xsl:when test="another">Lorem Ipsum.</xsl:when>
                <xsl:otherwise>Dolor amet.</xsl:otherwise>
        </xsl:otherwise>
    </xsl:choose>
</p>

在 XSLT 2.0 中,它可以进一步简化为:

<p>
  <xsl:value-of select="if (test=blah) 
                        then if (test=another) then 'Lorem ipsum' else 'Dolor amet'
                        then if (test=another) then 'Lorem ipsum' else 'Dolor amet'"/>
</p>

这让我觉得比你的 PHP 原版好很多。

对于更一般的问题,XSLT 确实有一个陡峭的学习曲线。那些坚持使用并掌握概念的人通常对这种语言非常满意。但也有不少人在到达那一点之前就冷落了,放弃了,因为这与他们以前遇到的任何事情都大不相同。

【讨论】:

    【解决方案2】:

    根据我的经验,最终,我总是回到简单的 .phtml 文件 - 并不是说​​这是正确的事情或理想的事情,而是解决了当时的问题。

    XSLT 从来没有为我做正确的事情,即使对于更简单的逻辑模板也是如此。

    如果有什么模板系统让我很开心,那就是Twig

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2012-07-23
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多