douchen4534 2015-11-02 09:53
浏览 110

获取Smarty模板(传递数据)为字符串

I'm working with a legacy code that uses Smarty. For one of the Ajax requests I need to return HTML code of a sub-template. Hence, I would like to pass a variable to the sub-template and store the processed template as string, so it can be passed back to Ajax callback.

I have no idea how to do that. Smarty fetch() seems to do something like that, but I'm unable to pass $myData into the sub-template.

What I want is this:

$content = $smarty->get_template_as_string('results.tpl', $myData);
return $content;

The get_template_as_string() method does not exist in Smarty, just serves as an example of what I need.

  • 写回答

1条回答 默认 最新

  • douping5226 2015-11-02 10:07
    关注

    Smarty doesn't take its data as an array, you need to assign each variable individually; luckily, all you need to do this is a simple foreach loop:

        foreach ($variables as $key => $value) {
            $this->assign($key, $value);
        }
    

    Then, as you say, fetch will render the actual template for you:

        $html = $this->fetch($template_file_name);
    

    Obviously you can wrap all of this up in whatever kind of utility function makes sense for you.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘