dongmi8980 2015-11-02 09:53
浏览 12

获取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条回答 默认 最新

  • dongzi4030 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 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法