【问题标题】:How to access smarty's foreach iteration from php function? (Smarty 2.6)如何从 php 函数访问 smarty 的 foreach 迭代? (智能 2.6)
【发布时间】:2014-12-15 18:04:06
【问题描述】:

问题

说我有

{php}
    function hello(){
{/php}
    <div class="hello">{$smarty.foreach.panellist.iteration}</div>
{php}
    }
{/php}

然后我在下面调用:

{foreach from=$channelObj->get_panellist_primary('','','pan_ptyid,pan_label1,pan_label2') item=panelObj name=panellist}
        {php}hello(){/php}
{/foreach}

我收到此错误:

PHP Fatal error: Using $this when not in object context in /var/www.app1/theURL/otherthings/channel.tpl.php on line 197

为什么这不起作用?如何从函数内部访问此 foreach 的迭代,最好不传递参数?

更多详情

因为我知道你会告诉我{php} 已被弃用...我使用它的原因是因为我被要求制作一个非常复杂的模板,所以我需要复杂的函数来构建它而不让它变成一团糟,我以前从未使用过smarty。我在最后期限,我已经迟到了,所以我无法学习 smarty 的正确方法。我知道如何管理此代码的唯一方法是使用常规 PHP,但我的老板坚持我用 smarty 完成整个事情......不允许使用 PHP 或 Javascript。

谢谢!

【问题讨论】:

  • 如果“不允许 PHP ...”,那么呃...{php} 是不允许的,对吧? :) 说真的,你能are you allowed a plugin 吗?如果没有,你的生活可能会更难成为 SOL...
  • 这看起来像是经典的X/Y problem 对我来说:你偶然发现了一些你不知道如何在 Smarty 中做的事情(与编写可重用的代码块有关),开始了一条路线你认为这很容易,结果却得到了一件你不知道如何在 Smarty 中做的不同的事情(以非标准方式混合 PHP 和 Smarty)。你可能会发现回到最初的问题比在错误的方法上苦苦挣扎更好地利用你的时间。
  • @bishop...naw 我可以在 .tpl 文件中使用我必须工作的任何内容...我无权访问该课程
  • @IMSoP 我已经走了很多路,我只需要有关如何执行此操作的帮助。我可以用一堆意大利面条聪明的代码来做到这一点,但我想避免这种情况。我希望 smarty 代码看起来像,例如,{wrapperIfNecessary()}{content}{closeWrapperIfNecessary()}
  • 替代方案是{if \\thing || \\thing and \\thing eq thing}&lt;div&gt;divdivdivdivdivdivdivdiv....etc{/if&gt;{content}{if really long if statement that makes it not even worth using smarty etc}&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;{/if}

标签: php smarty smarty2


【解决方案1】:

这是一种可怕的编码风格,它不是使用这种代码的解决方案,因为你很着急。如果你对某些技术一无所知,你就不应该为此花钱。

您可以在 Smarty 中使用:

{foreach from=$x item=panelObj name=panellist}
    {assign var="iteration" value=$smarty.foreach.panellist.iteration}
    {php}hello(){/php}
{/foreach}

在 PHP 函数中:

function hello()
{
    global $smarty;
    ?>
    <div class="hello"><?php echo $smarty->get_template_vars('iteration'); ?>
    </div>
<?php
}

它会工作(我已经测试过),但我什至不会尝试将此类代码用于任何项目

【讨论】:

  • 有没有办法直接从 $smarty 访问迭代而不分配它?
  • @NickManning 我不知道其他方式
【解决方案2】:

范围=全球 从 foreach 访问变量是必需的!

{assign var=SenderID value=$Nachricht.sender_id scope=global} 
{php} echo $smarty->getTemplateVars('SenderID'); {/php} 

{assign var="edit_ticket_id" value=$ticket.ticketRaw['edit_old_ticket_id'] 范围=全局}

{php} 全球 $smarty; var_dump($smarty->get_template_vars('edit_ticket_id')); {/php}

【讨论】:

    猜你喜欢
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2015-12-14
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多