Return array of objects from Handlebars Helper - arrays

I'm trying to write a helper that will return an array of objects that can then be looped through. Here's what I have now:
Handlebars.registerHelper('testHelper', () => {
return [
{ slug: 'Test', title: 'This is it!' },
{ slug: 'Test 2', title: 'This is the second it!' },
];
});
Using it like:
{{#entries this}}
{{title}}
{{/entries}}
And I'm receiving [object, Object] for each object in the array instead of the individual values. Please help :)
Thanks!

The way helpers in Handlebars work is a bit tricky. Instead of passing data from the helper to the main template body, you pass the portion of the template body related to the helper to the helper.
So, for example, when you do this:
{{#entries this}}
{{title}}
{{/entries}}
You are providing two things to the entries helper:
1) the current context (this)
2) some template logic to apply
Here's how the helper gets these items:
Handlebars.registerHelper('entries', (data, options) => {
// data is whatever was provided as a parameter from caller
// options is an object provided by handlebars that includes a function 'fn'
// that we can invoke to apply the template enclosed between
// #entries and /entries from the main template
:
:
});
So, to do what you want to do:
Handlebars.registerHelper('testHelper', (ignore, opt) => {
var data = [
{ slug: 'Test', title: 'This is it!' },
{ slug: 'Test 2', title: 'This is the second it!' },
];
var results = '';
data.forEach( (item) => {
results += opt.fn(item);
});
return results;
});
The opt.fn(item) applies this portion of template:
{{title}}
and the idea is to create a string (a portion of your html) that is then returned and placed into the string being formulated by your main template.
Here's a sample to show this working.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
</head>
<body>
<script id="t" type="text/x-handlebars">
{{#testHelper this}}
{{title}}
{{/testHelper}}
</script>
<script>
Handlebars.registerHelper('testHelper', (ignore, opt) => {
var data = [
{ slug: 'Test', title: 'This is it!' },
{ slug: 'Test 2', title: 'This is the second it!' },
];
var results = '';
data.forEach((item) => {
results += opt.fn(item);
});
return results;
});
var t = Handlebars.compile($('#t').html());
$('body').append(t({}));
</script>
</body>
</html>
Let me also echo what others have been trying to tell you. It doesn't make a lot of sense to try to populate data within your templates. This should be passed as context for your templates to act on. Otherwise, you are mixing your business logic with your template logic (view) and this complicates things needlessly.
Here's a simple change you can make in the same snippet, passing the data to your templates:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
</head>
<body>
<script id="t" type="text/x-handlebars">
{{#testHelper this}}
{{title}}
{{/testHelper}}
</script>
<script>
Handlebars.registerHelper('testHelper', (ignore, opt) => {
var results = '';
data.forEach((item) => {
results += opt.fn(item);
});
return results;
});
var data = [
{ slug: 'Test', title: 'This is it!' },
{ slug: 'Test 2', title: 'This is the second it!' },
];
var t = Handlebars.compile($('#t').html());
$('body').append(t(data));
</script>
</body>
</html>
This way you can retrieve your data in your javascript and keep the templates for what they were intended - formulating html.

Related

Angular UI grid - Translate grid on fly

I am using angular ui-grid. I want to translate the grid on fly. For example my current language is English. The grid gets rendered in English. Now I switch to french. I want all my menu options to be translated to french. How can I achieve this? This is my link to plunkr.
http://plnkr.co/edit/tpdNYirUEIF3RL0kf2d7?p=preview
Here is my sample code
HTML
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
<script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
<script src="https://rawgithub.com/PascalPrecht/bower-angular-translate/master/angular-translate.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<select ng-model="lang" ng-options="l for l in langs"></select><br>
<div ui-i18n="{{lang}}">
<p>Using attribute:</p>
<p ui-t="groupPanel.description"></p>
<br/>
<p>Using Filter:</p>
<p>{{"groupPanel.description" | t}}</p>
<p>Click the header menu to see language. NOTE: TODO: header text does not change after grid is rendered. </p>
<div ui-grid="gridOptions" class="grid"></div>
</div>
</div>
</body>
</html>
My JS
var app = angular.module('app', ['ngTouch', 'ui.grid', 'pascalprecht.translate']);
app.controller('MainCtrl', ['$scope', 'i18nService', '$http', '$translate','$rootScope', function ($scope, i18nService, $http, $translate,$rootScope) {
$scope.langs = i18nService.getAllLangs();
$scope.lang = 'en'
$scope.gridOptions = {
columnDefs: [
{ displayName: 'NAME', field: 'name', headerCellFilter: 'translate' },
{ displayName: 'GENDER', field: 'gender', headerCellFilter: 'translate' },
{ displayName: 'COMPANY', field: 'company', headerCellFilter: 'translate', enableFiltering: false }
]
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function(data) {
$scope.gridOptions.data = data;
});
}]);
app.config(function ($translateProvider) {
$translateProvider.translations('en', {
GENDER: 'Gender',
NAME: 'Name',
COMPANY: 'Company'
});
$translateProvider.translations('de', {
GENDER: 'Geschlecht',
NAME: 'Name',
COMPANY: 'Unternehmen'
});
$translateProvider.preferredLanguage('en');
});
The first screenshot refers to default language English. When I change my language to 'de' the grid menu options don't get translated. How can I make this happen?
To translate the Grid on the fly if you are using "Angular Translate", you should only refresh the Grid language when the angular-translate's event "$translateChangeSuccess" get fired like below:
// Get Fired when you change language using angular-translate
$rootScope.$on('$translateChangeSuccess', function (event, a) {
$scope.language = $translate.proposedLanguage() || $translate.use();
i18nService.setCurrentLang($scope.language); // Refresh the grid language
});
Do not forget to inject $rootScope and i18nService.
I needed to translate on the fly (without page refresh) those custom menu items too as well as "items per page" and such in the pager.
I also wrote an hack/workaround directly in the ui-grid source code so sharing if it might help someone else, at least until there will be an official patch.
first at grid definition a new event to handle language changed on
the fly (for example via angular dynamic locale):
onRegisterApi: function(gridApi) {
gridApi.registerEvent('language', 'changed');
gridApi.language.on.changed($scope, function(language) {
$rootScope.$gridLanguage = language;
});
then in a controller after language changed raise that event (in my
case on $localeChangeSuccess from angular dynamic locale) :
$scope.$on('$localeChangeSuccess', function (e, locale) {
$scope.$View.GridApi.language.raise.changed(locale);
});
and here the hacks, where the texts need a refresh, for example
adding in uiGridColumnMenu directive link function:
$scope.$watch('$parent.$root.$gridLanguage', function () {
if ($scope.$parent.$root.$gridLanguage !== undefined) {
$scope.menuItems = uiGridColumnMenuService.getDefaultMenuItems($scope);
}
});
or the same for uiGridPager:
$scope.$watch('$parent.$root.$gridLanguage', function () {
if ($scope.$parent.$root.$gridLanguage !== undefined) {
$scope.sizesLabel = i18nService.getSafeText('pagination.sizes');
$scope.totalItemsLabel = i18nService.getSafeText('pagination.totalItems');
$scope.paginationOf = i18nService.getSafeText('pagination.of');
$scope.paginationThrough = i18nService.getSafeText('pagination.through');
}
});
Working Plnkr
Add following method in controller:
$scope.changeLanguage = function (key) {
$translate.use(key);
};
Call this method with ng-change:
<select ng-model="lang" ng-options="l for l in langs" ng-change="changeLanguage(lang)"></select>

Unable to reduce the number of watchers in ng-repeat

In a performance purpose, i wanted to remove the double data-binding (so, the associated watchers) from my ng-repeat.
It loads 30 items, and those data are static once loaded, so no need for double data binding.
The thing is that the watcher amount remains the same on that page, no matter how i do it.
Let say :
<div ng-repeat='stuff in stuffs'>
// nothing in here
</div>
Watchers amount is 211 (there is other binding on that page, not only ng-repeat)
<div ng-repeat='stuff in ::stuffs'>
// nothing in here
</div>
Watchers amount is still 211 ( it should be 210 if i understand it right), but wait :
<div ng-repeat='stuff in ::stuffs'>
{{stuff.id}}
</div>
Watchers amount is now 241 (well ok, 211 watchers + 30 stuffs * 1 watcher = 241 watchers)
<div ng-repeat='stuff in ::stuffs'>
{{::stuff.id}}
</div>
Watchers amount is still 241 !!! Is :: not supposed to remove associated watcher ??
<div ng-repeat='stuff in ::stuffs'>
{{stuff.id}} {{stuff.name}} {{stuff.desc}}
</div>
Still 241...
Those exemples has really been made in my app, so those numbers are real too.
The real ng-repeat is far more complex than the exemple one here, and i reach ~1500 watchers on my page. If i delete its content ( like in the exemple), i fall down to ~200 watchers. So how can i optimize it ? Why :: does't seem to work ?
Thank you to enlighten me...
It's hard to figure out what's the exact problem in your specific case, maybe it makes sense to provide an isolated example, so that other guys can help.
The result might depend on how you count the watchers. I took solution from here.
Here is a Plunker example working as expected (add or remove :: in ng-repeat):
HTML
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<div>{{name}}</div>
<ul>
<li ng-repeat="item in ::items">{{::item.id}} - {{::item.name}}</li>
</ul>
<button id="watchersCountBtn">Show watchers count</button>
<div id="watchersCountLog"></div>
</body>
</html>
JavaScript
angular
.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.name = 'Hello World';
$scope.items = [
{ id: 1, name: 'product 1' },
{ id: 2, name: 'product 2' },
{ id: 3, name: 'product 3' },
{ id: 4, name: 'product 4' },
{ id: 5, name: 'product 5' },
{ id: 6, name: 'product 6' },
{ id: 7, name: 'product 7' },
{ id: 8, name: 'product 8' },
{ id: 9, name: 'product 9' },
{ id: 10, name: 'product 10' }
];
});
function getWatchers(root) {
root = angular.element(root || document.documentElement);
var watcherCount = 0;
function getElemWatchers(element) {
var isolateWatchers = getWatchersFromScope(element.data().$isolateScope);
var scopeWatchers = getWatchersFromScope(element.data().$scope);
var watchers = scopeWatchers.concat(isolateWatchers);
angular.forEach(element.children(), function (childElement) {
watchers = watchers.concat(getElemWatchers(angular.element(childElement)));
});
return watchers;
}
function getWatchersFromScope(scope) {
if (scope) {
return scope.$$watchers || [];
} else {
return [];
}
}
return getElemWatchers(root);
}
window.onload = function() {
var btn = document.getElementById('watchersCountBtn');
var log = document.getElementById('watchersCountLog');
window.addEventListener('click', function() {
log.innerText = getWatchers().length;
});
};
Hope this helps.

Backbone Marionettejs view does not change when model changed

I follow the example from this book https://leanpub.com/marionette-gentle-introduction. My problem is that the view does not rerender when i change the model by clicking on the button. As the answer from this question , i don't need to do anything because Backbone/MarionetteJS smart enough to change the view.
Here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Demo marionettejs</title>
<script src="./vendors/jquery/dist/jquery.js" type="text/javascript"></script>
<script src="./vendors/underscore/underscore.js" type="text/javascript"></script>
<script src="./vendors/backbone/backbone.js" type="text/javascript"></script>
<script src="./vendors/backbone.marionette/lib/backbone.marionette.js" type="text/javascript"></script>
</head>
<body>
<div id="main-region" class="container">
<p>Here is static content in the web page. You'll notice that it gets
replaced by our app as soon as we start it.</p>
</div>
<script type="text/template" id="contact-template">
<p><%- firstName %> <%- lastName %> : <%- time %> </p> <br />
<button>Change model</button>
</script>
<script type="text/javascript">
var ContactManager = new Marionette.Application();
ContactManager.Contact = Backbone.Model.extend({});
ContactManager.ContactView = Marionette.ItemView.extend({
template: "#contact-template",
initialize: function () {
this.currentMeterId = null;
},
events: {
"click button": "changeModel"
},
modelEvents: {
"change": "modelChanged"
},
changeModel: function() {
this.model.set("time", (new Date()).toString());
},
modelChanged: function() {
console.log("Model changed : " + this.model.get('time'));
},
//EDIT
onRender: function() {
//Create jsTree here.
}
});
ContactManager.on("before:start", function () {
var RegionContainer = Marionette.LayoutView.extend({
el: "#app-container",
regions: {
main: "#main-region"
}
});
ContactManager.regions = new RegionContainer();
});
ContactManager.on("start", function () {
var alice = new ContactManager.Contact({
firstName: "Alice",
lastName: "Arten",
time: "#"
});
var aliceView = new ContactManager.ContactView({
model: alice
});
ContactManager.regions.main.show(aliceView);
});
ContactManager.start();
</script>
</body>
</html>
#Edit
This code is just sample. In my real app, I have an ajax task that changes DOMs in the view. This ajax task creates a tree (jsTree) in onRender event. If i use modelEvents: {"change": "render"}, my jsTree will be reload and lost its state. So I want only update the model values in the view, others DOMs is retain.
The accepted answer to the question you pointed points to another question which has the following:
modelEvents: {
'change': "modelChanged"
},
modelChanged: function() {
console.log(this.model);
this.render();
}
And the most upvoted answer suggests the same:
modelEvents: {
'change': 'fieldsChanged'
},
fieldsChanged: function() {
this.render();
}
a comment to the most upvoted answer suggests
just {'change': 'render'} does the trick too
Which means you can do
modelEvents: {
'change': 'render'
}
So somehow you need to tell marionette invoke render on model changes.
I don't think backbone and marionette couple is smart enough to know whether you need to render view on model changes or you don't want to unless you tell them ;)

Polymer 1.0: How can I add paper-card heading content dynamically

Is there a way I can create paper-card heading dynamically using some property inside custom element? Following is what I tried but didn't work. Probably this is not the way to achieve what I want:( I googled for a couple of hours but ended up with nothing!
Custom Element
<script>
(function () {
'use strict';
Polymer({
is: 'nearest-customers',
properties: {
customers: {
type: Array,
value: [],
notify: true
},
cardViewMaxRecords: {
type: Number,
notify: true
},
showFullCustomerList: {
type: Boolean,
value: false,
notify: true
},
headingContent: {
type: String,
value: 'Custom card heading'
}
},
ready: function () {
this.heading.textContent = this.headingContent
},
});
})();
</script>
HTML
<nearest-customers id="nearestCustomers" card-view-max-records="3"></nearest-customers>
...
...
...
<script type="text/javascript">
window.addEventListener('WebComponentsReady', function (e) {
var nearestCustomers = document.querySelector("#nearestCustomers");
nearestCustomers.headingContent= "<a href='someurl'><iron-icon icon='fa:arrow-left'></iron-icon></a> This is a new content";
}
</script>
My objective is to put an iron-icon before the heading text and the icon can be used as a link to somewhere.
Thanks in advance
I'm sure there's a better way, but I just added the styles and structure:
<div class="header paper-card">
<div class="title-text paper-card">
<iron-icon icon="book"></iron-icon> Reading List
</div>
</div>

Why doesn't this.$el.append() work?

I'm trying to follow along http://addyosmani.github.io/backbone-fundamentals. I'm not getting how $el is supposed to work in a view.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Dashboard</title>
</head>
<body>
<h1>Dashboard</h1>
<ol class="foo" id="recent-station">
</ol>
<!-- Templates -->
<script type="text/template" id="station-template">
<li><%= station %></li>
</script>
<!-- Javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
<script src="static/js/script.js"></script>
</body>
</html>
And script.js is:
var RecentStation = Backbone.Model.extend( {
defaults: {
station: "",
},
initialize: function() {
console.log('initialized: ' + JSON.stringify(this));
this.on('change', function() {
console.log('changed: ' + JSON.stringify(this));
})
}
});
var RecentStationView = Backbone.View.extend( {
tagName: 'ol',
id: 'recent-station',
initialize: function() {
this.model.bind('change', _.bind(this.render, this));
},
render: function() {
console.log('render');
this.$el.append('<li>foo</li>');
$('ol#recent-station').append('<li>bar</li>');
return this;
},
});
var recent = new RecentStation();
var recentView = new RecentStationView({model: recent});
recent.set('station', 'My Station');
The interesting stuff is happening in the render function. I can see "render" logged to the console, and the "bar" text gets appended to the node, but not the "foo" text. I thought this.$el and $('ol#recent-station') were the same thing, but obviously not. What am I missing?
If you don't specify a dom element using el attribute, one will be created using tagName,id,className, and attributes from the view.
In your case you don't specify an el attribute in your view so you create an element that looks like:
<ol id='recent-station'></ol>
You then append <li>foo</li> into it, but your view element is still not in the DOM.
$('ol#recent-station') returns the dom element included in your html which is different than your view element, but has the same attributes.
So, in your example you would need to specify an existing element by supplying an el attribute.
var RecentStationView = Backbone.View.extend( {
// remove tagName and id
el:'#recent-station',
/* rest of your code below */
A fiddle with the changes, http://jsfiddle.net/DsRJH/.

Resources