I am on beginner level on Backbonejs. I am trying to call simple template. But it's giving me below error:
*Uncaught TypeError: Cannot read property 'replace' of undefined*
See plnk which I have created for it: http://plnkr.co/edit/fTcL4m?p=info
You can also find code here:
<!DOCTYPE html>
<html>
<head>
<title>Loading a template</title>
</head>
<body>
<h1>Loading a template</h1>
<div id="search_container"></div>
<script data-require="[email protected]" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script data-require="[email protected]" data-semver="1.8.3" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script data-require="[email protected]" data-semver="1.1.2" src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script>
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
var template = _.template($("#search_template").html(), {});
this.el.html(template);
}
});
var search_view = new SearchView({ el: $("#search_container") });
</script>
<script type="text/template" id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
</body>
</html>
The major issue is the order of your script tags,
<script type="text/template" id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
does not exist when your script runs. You should make sure it does, By adding it before the one containing code, or wrapping your code in $(function(){})
etc.
Another issue is that you should use this.$el.html(template);
instead of this.el.html(template);