im trying to use templates for my backbone views. I tried it with underscore.template to get it running. The problem is that since the manifest_version 2 of chrome extensions there are some security restrictions. I think the reason is because inline blocks are not allowed anymore. In this little example i load a template and try to render it. I then get the error:
Uncaught Error: Code generation from strings disallowed for this context.
I tried it also with Handlebars.js and a template right into my html-file. It works in a normal browser-window. But it does not as a chrome extension.
So how can i use templates with backbone.js in a chrome extension with manifest_version 2?
With underscore (does not work):
define [
'jquery'
'backbone'
'lib/facade'
'text!templates/loginTemplate.js'
],
($, Backbone, facade, LoginTemplate) ->
'use strict'
class LoginView extends Backbone.View
tagName: 'div'
events: {
}
initialize: (options) ->
@el = options.el
render: ->
console.log 'LoginView: render()'
$(@el).html(_.template(LoginTemplate, {}))
with handlebars (does not work):
template in index.html:
<!-- templates -->
<script id="loginTemplate" type="text/x-handlebars-template">
<form class="form-horizontal">
<fieldset>
<legend>Login</legend>
<div class="control-group">
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input type="text" class="input-xlarge" id="email" name="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Passwort:</label>
<div class="controls">
<input type="password" class="input-xlarge" id="password" name="password">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</fieldset>
</form>
</script>
and in my view:
define [
'jquery'
'backbone'
'lib/facade'
],
($, Backbone, facade) ->
'use strict'
class LoginView extends Backbone.View
tagName: 'div'
events: {
}
initialize: (options) ->
@el = options.el
render: ->
console.log 'LoginView: render()', $("#loginTemplate")
$(@el).html(Handlebars.compile($("#loginTemplate").html()))
Both Underscore and Handlebars templates convert strings to JavaScript functions; for example, Underscore does it like this:
so it builds some JavaScript and uses
new Functionto build a function; Handlebars probably does something similar. Apparently Chrome doesn’t want you doing things like that in an extension.You could precompile the template and then embed the function in your extension as a simple bit of JavaScript. For Underscore templates, you could look at the
sourceproperty:So you can
t = _.template(your_template)while packaging your extension and put thet.sourcetext in your extension as a JavaScript function.You can do similar things with Handlebars (see handlebars_assets for example).
Both of them complicate your build and packaging process but if Chrome doesn’t want you building functions in an extension then there’s not much you can do about it.