Ember: how to use i18n translations in controller code? - ember.js

I am using Ember i18n in my app. I also want to use the translation strings in the controllers (in most cases in an alert or confirm message). How can this be done ?
See http://jsfiddle.net/cyclomarc/36VS3/2/
Clicking on the button should alert "info" and not "T1005" ...
<script type="text/x-handlebars">
{{t T1005}}<br>
<button {{action 'clickMe' content}}>{{t T1005}} - Click me</button>
</script>
CLDR.defaultLanguage = 'en';
App.ApplicationController = Ember.Controller.extend({
clickMe: function(){
alert('T1005');
}
})
I know that a possible workaround is to no longer use alert and confirm and replace them by for example the bootstrap alternatives. However, I could imagine that in certain cases you will want to do something with the strings in Javascript (e.g. update a certain label via jQuery or so).
Any ideas on how to use the i18n strings in the controllers is helpful. Using an i18n library is only usefull if all aspects of the application can be translated ...

Just found the solution. Just access the string via Ember.I18n.t("T1005");
JSFiddle updated: http://jsfiddle.net/cyclomarc/36VS3/7/

Might be late here, but what about using the Em.I18n.TranslateableProperties mixin as documented here ?
You could do something like :
App.ApplicationController = Ember.Controller.extend(Em.I18n.translateableProperties, {
messageTranslation: 'T1005',
clickMe: function(){
alert(this.get('message'));
}
});
In the template, {{message}} will also hold the translation.

The solution that works to me is the following (using Ember I18n):
App.ApplicationController = Ember.Controller.extend(Em.I18n.translateableProperties, {
messageTranslation: 'T001',
showMessage: function(){
alert(this.get('message'));
}
});

The answer from cyclomarc didn't work for me (it's from 2013, which might be related), but it pointed me in the right direction:
this.container.lookup('service:i18n').t('my.translation.id')

Related

How to append Ember.View Properly

I have recently decided to do a major upgrade with my javascript libraries and have ran into a perplexing issue with appending Ember.Views. I have been researching this issue for several hours now and have tried many things but nothing has worked.
What I want to do is quite simple: Extend Ember.View, manually create a new instance of this extended view and then append it to a div. In a much earlier version (ember.js 1.5) this was extremely straightforward. Now (ember.js 1.9) attempting the same thing results in an error.
Container was not found when looking up a views template. This is most
likely due to manually instantiating an Ember.View. See:
http://git.io/EKPpnA
Here is a very simple example that demonstrates this: http://jsfiddle.net/81dhm3ta/
html
<body>
<script data-template-name="main" type="text/x-handlebars">
Main
</script>
<div id="main" style="text-align: center;"></div>
</body>
javascript
$(document).ready(function () {
App = Ember.Application.create();
App.MainView = Ember.View.extend({
templateName: 'main',
});
App.view = App.MainView.create();
App.view.appendTo("#main");
});
Can someone show me the simplest way to do this properly?
App.view is neither a D0M element or jQuery object that you can simply append to a div. It is an Ember object of type View.
In the link given by the error, you are clearly told that you can't create views like you did in your snippet. Dynamic views must be instantiated within a parent view or directly through the container (not recommended).
Your life will be much easier if you add views within a template by just using the view helper:
<script type="text/x-handlebars" data-template-name="index">
{{view 'main'}}
</script>

Not rendering/removing sidebar based on route

Something I've been experimenting around with Ember for a couple of hours and can't work out. Hopefully it's just a terminology issue that I'm getting stumped on as I read through the Ember docs.
I have an application, that, for the most part, consists of a sidebar/top bar (called wrapper), and a footer.
My basic application.hbs looks like this (I'm using Ember App Kit to provide structure):
{{partial "wrapper"}}
{{outlet}}
{{partial "footer"}}
If this was the state of my application, it would work pretty well. Page content loads in the {{outlet}} fine.
My main issue is how to break out of this template structure in an "Ember" way (and preferably without going all jQuery and removing DOM elements willy-nilly).
I have a few routes that I don't want the wrapper and the footer to show on (they're full page login/forgot password routes, and a couple of minimal interface/no distractions modes).
I experimented with trying to remove the sidebar and footer by making the default template (application.hbs):
{{#if showWrappers}}
{{partial "wrapper"}}
{{/if}}
{{outlet}}
{{#if showWrappers}}
{{partial "footer"}}
{{/if}}
Where showWrappers is in the ApplicationController:
export default Ember.Controller.extend({
showWrappers: function() {
var routes = ['login'],
currentPath = this.get('currentPath'),
show = true;
routes.forEach(function(item) {
var path = new RegExp('^' + item + '*');
if (!Ember.isEmpty(currentPath.match(path))) {
show = false;
}
});
return show;
}.property('currentPath'),
});
Attemping to transition to /login from / using {{link-to}} returns in an error: Uncaught Error: Cannot perform operations on a Metamorph that is not in the DOM presumably because I'm removing things Ember wanted to keep (I am using {{link-to}} and {{bind-attr}} in the sidebar, so there are bindings there).
Aware that I could use actions and jQuery to hide elements of the page and bring them back for the "distraction free" mode, but I'd prefer to learn how to structure templates and use Routes with the renderTemplate hook potentially using this.render (?) to blow away the current DOM and rebuild from a different base (rather than application.hbs).
Thoughts? More than happy to clarify.
I have discovered disconnectOutlet, and have converted my partials into outlets:
{{outlet wrapper}}
{{outlet}}
{{outlet footer}}
Made my ApplicationRoute render to them by default:
export default Ember.Route.extend({
renderTemplate: function() {
this.render();
this.render('wrapper', {
outlet: 'wrapper',
into: 'application'
});
this.render('footer', {
outlet: 'footer',
into: 'application'
});
}
});
and then on the LoginRoute, I just run this.disconnectOutlet for both wrapper and footer, and seems to work pretty well.

Access Controller in a View in a Render

I have a view like this:
App.AbilityFilter = Ember.TextField.extend({
classNames: ['span3'],
keyUp: function(evt) {
this.get('controller').send('filterAbilities','text');
},
placeholder:'Search abilities'
});
It's part of a render like this:
<script type="text/x-handlebars" data-template-name="abilities">
{{view App.AbilityFilter}}
<div class="accordion" id="abilities">
{{#each ability in model}}
<div class="accordion-group">
{{ability.name}}
</div>
{{/each}}
</div>
</script>
Which is being rendered in my application like this:
{{render 'abilities'}}
The problem I'm having is with the event or, rather, the action. The keyUp event fires perfectly well, but for some reason it won't go to a controller.
I've tried adding the filterAbilities to the actions hash on both the App.AbilitiesController and the App.IndexRoute according to this. According to this, the view should be part of the abilities controller since that's the context of it's parent, but it's not working.
I've done some testing and it almost seems like this.get('controller') isn't fetching a controller at all. I'm a bit lost as to what's causing the problem. This code worked a few RCs ago, but as soon as I upgraded to 1.0 it broke.
What I'm trying to do here is filter the list of abilities. If this isn't the way to this anymore, please let me know! Any help would be appreciated. Thanks!!
Ember.TextField and Ember.TextArea are no longer simple views but rather subclasses of Ember.Component which means that this.get('controller') does not refer anymore to the views controller.
But there is a different variable which indeed holds a reference to the surrounding controller and this is this.get('targetObject'). Therefore you should send your action to the targetObject:
App.AbilityFilter = Ember.TextField.extend({
classNames: ['span3'],
keyUp: function(evt) {
this.get('targetObject').send('filterAbilities','text');
},
placeholder:'Search abilities'
});
Hope it helps.

How to nest views in the new Ember.js router API?

I have a setup screen, it consists of a sidebar and a body. The body can have a form to update the user's profile or password.
The routing looks like this:
App.Router.map(function(match) {
(match("/")).to("index");
(match("/user")).to("user", function(match) {
(match("/")).to("userIdx");
(match("/settings")).to("userSetup", function(match) {
(match("/")).to("userSetupIdx");
(match("/profile")).to("userSetupProfile");
(match("/password")).to("userSetupPassword");
});
});
});
and the wrapping setup template like this:
<script type="text/x-handlebars" data-template-name="userSetup">
<div class='sidebar'>
Sidebar
</div>
<div class='main'>
Setup <br/>
{{outlet}}
</div>
</script>
A complete example can be found here:
http://jsfiddle.net/stephanos/mgp7F/6/
What's the right approach to do this in Ember.js?
EDIT
With the help of sly7_7 I managed to make the fiddle above work: http://jsfiddle.net/ygvsS/9/. All I did was rename everything from userSetup (template, view, route) to setup. BUT obviously this is not a solution (since I have appSetup, too).
I think I have done what you are looking for, based on your comment example: http://jsfiddle.net/rt8fv/
router code:
App.Router.map(function(match){
match('/').to('home');
match('/about').to('about');
match('/contributors').to('contributors', function(match){
match('/').to('contributorsIndex');
match('/:contributor_id').to('contributor', function(match){
match('/').to('contributorIndex');
match('/details').to('contributorDetail');
match('/repos').to('contributorRepos');
});
});
});
Maybe related question: Best approach to fetch data in every state of app

Creating Web applications with Ember.js

I've just found out about Ember.js, and it looks interesting. I'd like to create a small notes app to learn how to use it.
The basic layout I have in mind is to have categories, and each category can have notes. For the UI, there would be a sidebar with the categories which will be clickable, and the notes for the category will be displayed on the other side.
But I can't quite figure out the whole template/layout system. The template system itself seems simple enough (similar enough to Rails views). But what do you do for layouts? With Rails for example, you can define layouts quite easily and then the individual views are added to that. This seems unclear to me with Ember.js.
Besides the approaches #rharper mentioned, you can also use the outlet helper, wich has been introduced in commit 5a4917b.
You can find an example here:
Handlebars:
<script type="text/x-handlebars" data-template-name="main" >
Main View
{{outlet contentView}}
{{outlet footerView}}
</script>
JavaScript:
App.viewController = Ember.Object.create({
footerView: Ember.View.create({
templateName: 'footer'
}),
contentView: Ember.View.create({
templateName: 'content'
})
});
Ember.View.create({
controllerBinding: 'App.viewController',
templateName: 'main'
}).append();
Ember.run.later(function(){
App.viewController.set('contentView', Ember.View.create({
templateName: 'new-content'
}));
}, 1000);
​
For simple wrapper-style layouts you can use Ember's built-in layout support. It only supports a single {{yield}} so may be too limited for your application.
For something a little more robust take a look at ghempton's Ember Layout. I think you'll find it quite similar to Rails layouts. He has a live example here.
Finally, it's fairly easy to create a hierarchy of views in Ember (instead of or in addition to using layouts). Tom Dale has a good collection of Ember resources and examples here.