【问题标题】:jsmart - Can't get template contents (in time?)jsmart - 无法获取模板内容(及时?)
【发布时间】:2012-07-31 12:20:13
【问题描述】:

我正在尝试使用jsmart 在客户端呈现Smarty3 模板。如果您对它们没有经验,请继续阅读,因为这可能只是我正在制作的一个简单的 JavaScript 错误。


它适用于简单的模板:

我根据文档创建模板(通过 AJAX 接收),然后渲染它(将数据传递给它):

var template = new jSmart(templateReceivedViaAJAX);
var content = template.fetch({"firstname":"adam", "secondname":"lynch"});

然后我只需将渲染输出粘贴到div

$('#dest').html(content);   

模板继承

尝试渲染包含includeextends 等的模板时会出现问题。

来自documentation

每当 jSmart 遇到任何一个模板包含标签时,它都会调用 jSmart.prototype.getTemplate() 方法并将标签文件参数的值传递给它。该方法必须返回模板的文本。

getTemplate() 的默认实现抛出异常。因此,由 jSmart 用户来覆盖此方法并提供模板的文本。


覆盖getTemplate()函数:

jSmart.prototype.getTemplate = function(name) {
    $.ajax({type: 'GET', url: name, async:false, success: function(data) {
        console.log('got template at '+name+'. The following is the contents:');
        console.debug(data);
                
        return data;
    }});
}

渲染包含include模板调用的模板时的控制台输出:

<div class="row">

    <label for="second" class="span4">Second Name:</label>  

    <input type="text" class="span4" placeholder="{$secondname}" id="second" /> 

</div>

<p>B;lsdsfasfsfds</p>
Uncaught Error: No template for /bundles/templatedemo/templates/form_include.html.smarty 

渲染包含extend模板调用的模板时的控制台输出:

got template at /bundles/templatedemo/templates/form.html.smarty. The following is the contents: templates:58
<form class="well">  

    <div class="row">

        <label for="first" class="span4">First Name:</label>  

        <input type="text" class="span4" placeholder="{$firstname}" id="first" /> 

    </div>

    {block name=form_include}{/block}

    <input type="submit" class="btn btn-inverse" />  

</form>
Uncaught Error: No template for /bundles/templatedemo/templates/form.html.smarty 
(expanded:)
S 
(anonymous function) 
jSmart.fetch 
(anonymous function) 
f.event.dispatch 
f.event.add.h.handle.i

编辑:

如果模板内容预先存在,则继承有效(例如,如果它们是硬编码的,而不是通过 AJAX 检索)。

【问题讨论】:

  • 我将在今晚(格林威治标准时间)稍后尝试针对 SmartyBundle 测试 jSmart,看看这是否与 SmartyBundle 相关。如果您想实时调试它,我也可以在#noiselabs freenode 频道上找到它。
  • @noisebleed 谢谢!我会整天在那儿 (GMT+1)

标签: javascript jquery ajax smarty templating


【解决方案1】:

使用函数指针而不是匿名函数:

function foo() 
  {
  $.ajax({type: 'GET', url: foo.url, async:false, success: bar});
  }

function bar(data) 
  {
  console.log(['got template at', foo.url, 'The following is the contents:']);
  console.debug(data);

  return data;
  }

foo.url = "http://www.stackoverflow.com";

jSmart.prototype.getTemplate = foo;

【讨论】:

    猜你喜欢
    • 2017-09-16
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 2014-01-24
    相关资源
    最近更新 更多