代码之家  ›  专栏  ›  技术社区  ›  user967451

如何将此PHP语法转换为Smarty语法?

  •  1
  • user967451  · 技术社区  · 12 年前

    我刚开始在项目中使用智能模板。我很难让这个工作起来。这段代码在我的“.php”文件中工作:

    echo $categories[$topics[9]['category_id']]['category_id'];
    

    但这两个(以及其他变体)在我的“.tpl”文件中都失败了:

    {$categories[$topics[9].category_id]['category_id']}
    {$categories[$topics[9].category_id].category_id}
    

    我犯了什么语法错误,如何使其生效?

    2 回复  |  直到 12 年前
        1
  •  1
  •   Marcin Nabiałek    12 年前

    Smarty使用与PHP不同的语法。看见 this page on Smarty variable syntax .

    然而,正如您所看到的,Smarty也允许PHP风格的语法。因此,您的PHP代码应该按原样工作,只需删除 echo 结尾处的分号用大括号替换。

    当我有多维和嵌套数组时,有时我喜欢为每个元素分配一个变量,以便于阅读。所以我可以重写变量:

    {$categories[$topics[9]['category_id']]['category_id']}
    

    成为:

    {assign var="topic" value=$topics[9].category_id}
    {$categories.$topic.category_id}
    

    这将帮助您减少重复并提高可读性。随后,调试将更容易。

        2
  •  0
  •   Marcin Nabiałek    12 年前

    聪明,因为几乎所有模板引擎都有自己的语法。

    据我所知(如果我错了,有人可以纠正我),在Smarty 2中使用某些语法是不可能的,而且从PHP中编写一些显而易见的代码也比较困难。但现在我们有了Smarty 3.1

    在您的问题中,您可能没有将类别和主题都分配给Smarty,因此它无法工作。简单的规则是,您需要使用 $smarty->assign 建筑

    在您的情况下,您可以在PHP中简单地执行以下操作:

    $topics = [];
    $topics[9]['category_id'] = 'something';
    $categories = [];
    $categories['something']['category_id'] = 798897;
    
    
    $smarty->assign('topics', $topics);
    $smarty->assign('categories', $categories);
    

    要将PHP和Smarty中的两个数组分配给Smarty,可以简单地执行以下操作:

    {$categories[$topics[9]['category_id']]['category_id']}
    

    正如您所看到的,您显示的这个值与PHP中的值几乎相同(而不是简单地使用echo { 在开始和 } 在结尾)蚂蚁就这样。

    不过,您也可以在Smarty中使用更简单的语法:

    {$categories[$topics.9.category_id].category_id}
    

    而不是使用 [..] 你可以使用 . 但当使用上述其他变量作为索引时,仍需要使用 [..] 语法