You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.tpl文件中If Else逻辑不生效问题排查求助

问题原因与解决方案:Smarty模板逻辑未被解析直接显示

核心问题

通过路由http://127.0.0.1:8080/tikiTwoFactor访问时,Smarty的{if}逻辑直接以原始代码显示,根本原因是路由直接指向了.tpl模板文件,没有经过Smarty引擎的解析流程:

  • 访问tiki-two_factor_validator.php时,是通过PHP代码初始化Smarty实例,调用display()方法触发模板解析,所以逻辑能正常执行;
  • 而路由配置直接把请求导向templates/tiki_two_factor_auth.tpl,此时服务器只是直接输出文件内容,没有启动PHP和Smarty处理模板标签。

另外模板中直接使用$_GET.error也不符合Smarty最佳实践,存在兼容性和安全隐患。

修复步骤

1. 修改路由指向PHP处理脚本

创建专门的tikiTwoFactor.php文件,负责初始化Smarty并传递变量:

require_once('vendor_bundled/vendor/smarty/smarty/libs/Smarty.class.php');
$smarty = new Smarty();
// 将GET参数赋值给Smarty模板变量
$smarty->assign('error', $_GET['error'] ?? null);
$smarty->display('/templates/tiki_two_factor_auth.tpl');

更新路由配置,指向这个PHP文件:

tiki_route_attempt(
        '|^tikiTwoFactor$|',
        'tikiTwoFactor.php'
);

2. 修正模板中的变量调用

将模板里直接访问超全局变量的代码,改为使用Smarty赋值的变量:

<form 
     action="../tiki-two_factor_validator.php" 
     method="POST">
     <div class="form-group">
            <label for="twoFactor">
                   {if $error}
                       <div class="alert alert-danger">
                            {$error}
                        </div>
                    {else}
                        We send to your email two-factor authentication code
                    {/if}
            </label>
            <input type="text" class="form-control" id="twoFactor" name="twoFactor" placeholder="Two-Factor Code" required>
      </div>
      <button type="submit" class="btn btn-primary btn-block">Login</button>
</form>

原理说明

Smarty是PHP模板引擎,必须通过PHP代码驱动才能完成模板编译、变量替换和逻辑解析。直接访问.tpl文件时,服务器只会把它当作普通文本文件输出,不会触发任何PHP或Smarty的处理流程,因此模板标签会原封不动显示在页面上。通过PHP脚本作为中间层,才能让Smarty完成模板的解析渲染工作。

内容的提问来源于stack exchange,提问作者Arsen Mkrtumian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:47:30