Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in handlebars template of emberjs

I am using http://ivaynberg.github.io/select2/ to provide autocomplete functionality in an rails-emberjs application. I do have the some_dynamic_id value. My handlebars code is as below:

{{
  view App.TokenAutoCompleteView                                                                                               
  searchUrl="/users/" + some_dynamic_id + "/books/search"
  optionValuePath="content.id"
  optionLabelPath="content.name"
  multiple="false"
}}

I want to assign a dynamically created url to the searchUrl attribute. I tried using bind-attr from Ember Interpolation in a href tag in handlebars template but couldn't get it working.

like image 621
prasad.surase Avatar asked Feb 12 '23 11:02

prasad.surase


1 Answers

Remember that Handlebars templates are logic-less, so there is no concept of string interpolation. You should instead do that in a computed property inside of your controller (or component).

In your controller:

dynamicSearchUrl: function() {
    return '/users/' + this.get('someDynamicId') + '/books/search';
}.property('someDynamicId')

In your template:

{{view App.TokenAutoCompleteView searchUrl=dynamicSearchUrl ... }}

Update: It's been a long time since I've answered this so I thought I would update. Ember.js now uses a newer version of Handlebars that support subexpressions. This means that string concatenation in templates is now possible. You just need to write a concatenation helper.

// helpers/concat.js
export default Ember.Helper.helper(function(first, second, three) {
    // You could make this apply to more than three strings...
    return first + '' + second + '' + three;
});

Once you have that, just use a subexpression in your template:

{{
  view App.TokenAutoCompleteView
  searchUrl=(concat "/users/" some_dynamic_id "/books/search")
  optionValuePath="content.id"
  optionLabelPath="content.name"
  multiple="false"
}}

I still strongly prefer the my first answer in this situation, but the second is now possible.

like image 135
GJK Avatar answered Feb 13 '23 23:02

GJK