问题
I'm trying to use jsmart to render Smarty3 templates on the client-side. If you've no experience with them, keep reading because it could just be a simple JavaScript error that I'm making.
It works for simple templates:
I create the template (which I receive via AJAX), then render it (passing it the data), as per the documentation:
var template = new jSmart(templateReceivedViaAJAX);
var content = template.fetch({"firstname":"adam", "secondname":"lynch"});
Then I simply stick the rendered output in a div
:
$('#dest').html(content);
Template inheritance
Problems happen when trying to render templates which contain include
, extends
, etc.
From the documentation:
Whenever jSmart come across either of template inclusion tags it calls jSmart.prototype.getTemplate() method and passes it a value of tag's file parameter. The method must return the template's text.
The default implementation of getTemplate() throws an exception. So, it is up to a jSmart user to override this method and provide template's text.
Overridding the getTemplate()
function:
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;
}});
}
The console output when rendering a parent template containing an include
call to a child template:
<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
The console output when rendering a child template containing an extend
call to a parent template:
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
Edit:
Inheritance works if the template contents are there in advance (if they're hard-coded in, instead of being retrieved via AJAX, for example).
回答1:
Use a function pointer rather than an anonymous function:
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;
来源:https://stackoverflow.com/questions/11739922/jsmart-cant-get-template-contents-in-time