Limit number of characters in View (Backbone.js)

backbone.js, css, javascript, jquery

Solution

Rather than try to modify the title after rendering it, modify it as it's rendered.

Pass a `maxlength` variable to your template as well, then:

<script type="text/template" id="tpl_PhotoListItemView">
    <div class="photo_stats_title"><%= title.substr(0,maxLength) %></div>
</script>

If `title.length` is less than maxlength, the entire string will display. If it's greater, only the first `maxlength` characters will display.

Alternatively, simply hardcode the maximum length of the `title` into the call to `.substr()`

If you need to perform more advanced truncating (e.g. adding '...' to truncated titles), you're better off modifying the title before rendering the template, passing the truncated version of the title into the template

Another option would be to override `Model.parse(response)`, creating a `shortTitle` attribute on the model; this way it's always available whenever you're working with the model

Problem

I have a backbone.js View that reads a template from the HTML file and inserts values from its model into the template. One of this value is in the variable `title`, which can be long enough to disrupt the flow of elements on the page. I want to use Javascript to limit the max. number of characters `title` can have, instead of doing it on the backend because eventually the full `title` has to be displayed. I tried selecting the div that contains `title` after the template was been rendered, but cannot seem to select it. How can I do this otherwise? Template ``` <script type="text/template" id="tpl_PhotoListItemView"> <div class="photo_stats_title"><%= title %></div> </script> ``` View ``` PhotoListItemView = Backbone.View.extend({ tagNAme: 'div', className: 'photo_box', template: _.template( $('#tpl_PhotoListItemView').html() ), render: function() { $(this.el).html( this.template( this.model.toJSON() ) ); console.log($(this.el).children('.photo_stats_title')); <!-- returns nothing --> this.limitChars(); return this; }, limitChars: function() { var shortTitle = $(this.el).children('.photo_stats_title').html().substring(0, 10); $(this.el .photo_stats_title).html(shortTitle); } }); ```

Original source