Niklas9
Niklas9

Reputation: 9386

Underscore template not rendering in backbone

I'm trying out a simple example (see full code below) with the latest production versions of backbone.js, underscore.js and jquery. However I can't get anything displayed on the screen. I have tried logging this.$el to console log and it seems valid, also the html var contains the correct parsed HTML from the test-template. But nothing is shown in the browser window.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>testing Backbone.js</title>
  </head>
  <body>

      <script type="text/template" id="test-template">
      <div id="container">
          <%= test %>
      </div>
      </script>

      <script type="text/javascript" src="js/lib/jquery.js"></script>
      <script type="text/javascript" src="js/lib/underscore.js"></script>
      <script type="text/javascript" src="js/lib/backbone.js"></script>
      <script type="text/javascript">
        var testView = Backbone.View.extend({
            el: $("#container"),
            template: _.template($('#test-template').html()),
            render: function() {
                var html = this.template({test: 'hello World!'});
                this.$el.html(html);
                return this;
            }
        });

        $(document).ready(function() {
            var test = new testView();
            test.render();
        });
      </script>
  </body>
</html>

Upvotes: 4

Views: 2348

Answers (2)

coonooo
coonooo

Reputation: 205

There is no render code . Template's content not the visuable part of DOM; try this:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>testing Backbone.js</title>
  </head>
  <body>
      <div id="output"></div>
      <script type="text/template" id="test-template">
      <div id="container">
          <%= test %>
      </div>
      </script>

      <script type="text/javascript" src="js/lib/jquery.js"></script>
      <script type="text/javascript" src="js/lib/underscore.js"></script>
      <script type="text/javascript" src="js/lib/backbone.js"></script>
      <script type="text/javascript">
        var testView = Backbone.View.extend({
            el: $("#container"),
            template: _.template($('#test-template').html()),
            render: function() {
                var html = this.template({test: 'hello World!'});
                $("#output").html(html);
                return this;
            }
        });

    $(document).ready(function() {
        var test = new testView();
        test.render();
    });
  </script>

Upvotes: 1

Lee Avital
Lee Avital

Reputation: 542

There is no element with id="container" to append the template to. If you replace

el: $("#container")

with

el: $('body')

Something should show up

Upvotes: 5

Related Questions