Link interpolation i18n - ember.js

I use ember-i18n to handle multiples langages in my project, and I need to insert a link inside a translation (with interpolation).
Any idea ?

Response from #jamesarosen on Github :
You can't use the {{link-to}} helper inside a translation because it
emits a DOM node, not a String.
But you can use ember-href-to addon to generate URLs.
In JavaScript:
// some-thing/component.js:
import { hrefTo } from 'ember-href-to/helpers/href-to';
text: Ember.computed('i18n.locale', function() {
const i18n = this.get('i18n');
const href = hrefTo(this, 'some.route');
const link = Ember.String.htmlSafe(`Link Text`);
return i18n.t('some.translation', { link });
})
Or in Handlebars (you'll need an htmlSafe helper):
{{t 'some.translation'
link=(htmlSafe (join 'Link Text'))}}

I face a similar problem recently and this is what I did:
Translation file (en.json) :
"some.message.key": "Successfully created <a href='{{userlink}}'> {{username}} </a>."
In the respective template/hbs file:
{{html-safe (t "some.message.key" userlink=link username=name)}}
html-safe is a helper provided by ember-cli-string-helpers add on.

Related

How to use tabulator with ember?

I want to use http://tabulator.info/ with ember. I don't understand the documentation nor can I find any guides on configuration for ember. How can I start by creating a simple table?
Looking at the examples on the site, http://tabulator.info/, it seems that tabulator only needs an element to work (and some config).
So, our end goal is going to be to use a modifier with the ability to pass the tabulator config to it.
So, this is what we'll end up with:
<div {{tabulator someConfig}}></div>
Now, unfortunately, it looks like tabulator only accepts an id in its constructor. so we'll need to dynamically add that in to appears tabulator.
First thing you'll want to do is install https://github.com/ember-modifier/ember-modifier (be sure to read the docs as this is fun stuff)
Then, create a file in your app, app/modifiers/tabulator.js
and use these contents:
import Modifier from 'ember-modifier';
import Tabulator from 'tabulator';
import { guidFor } from '#ember/object/internals';
export default class TabulatorModifier extends Modifier {
id = guidFor(this);
get config() {
return this.args.positional[0];
}
didInstall() {
this.element.id = this.id;
let config = th
this.tabulator = new Tabulator(`#${this.id}`, this.config);
}
}
And then maybe in a component or controller or something, you'd have something like:
export default class MyComponent extends Component {
get myConfig() {
return { ... };
}
}
<div {{tabulator this.myConfig}}></div>
and that should be it.
You'll want to import the CSS in your app.css

Can't Figure out the Syntax Error in App.js

I am using this tutorial to install React for the front with an API built in Django.
https://sweetcode.io/how-use-djang-react-ap/
My repository for this projects so far is here:
https://github.com/AlexMercedCoder/DjangoReactCRM
When I npm run dev I get a syntax error in App.js, I've played with it and can't seem to figure it out. The error I get is.
ERROR in ./frontend/src/components/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError:
C:\Users\alexm\projects\DjangoReactCRM\drcrm\frontend\src
\components\App.js: Unexpected token, expected "," (29:6)
27 |
28 | wrapper ? ReactDOM.render(<app>, wrapper) : null;
> 29 | </app>
App.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
class App extends Component {
state = {
data: ''
};
componentDidMount() {
fetch("/api")
.then(response => {
return response.json();
})
.then(data => this.setState({ data: JSON.stringify(data)}));
}
render(){
return (
<p>Jason data = {this.state.data}</p>
)
}
}
wrapper ? ReactDOM.render(<app>, wrapper) : null;
</app>
First, the <app> component is closed outside the ternary operator, so you'd have to use <app></ app> or even simpler <app />.
wrapper ? ReactDOM.render(<app></app>, wrapper) : null;
or
wrapper ? ReactDOM.render(<app/>, wrapper) : null;
Then, all React components must start with a capital letter
to differentiate default DOM component from those created with React, so you have to use this notation.
wrapper ? ReactDOM.render(<App />, wrapper) : null;
Finally, I do not see the utility of the ternary operator at the end of your code. Normally, the second argument when we call reactDOM.render(X, Y) must represent the DOM element in which we will render our main React component (in this case, <App />).
By default, when we create a React project with create-react-app, we don't have to deal with these settings and the DOM element is automatically defined as <div id='root'></div> (check inside the <body> in public/index.html inside your project root).
So call document.getElementById('root') to get the DOM element and simply put the result as second argument.
ReactDOM.render(<App />, document.getElementById('root'));
If it persist, I suggest you to simply create another React project with create-react-app and copy/paste only the code you need.
To get more informations: Click here
I hope it can help you.
** I apologize if my explanations are not clear or if I made some mistakes.
There are three problems in your component.
I'm guessing wrapper was supposed to be document.getElementById("root") ? Even then the ternary condition doesn't make sense. It should be something like:
ReactDOM.render(
<App />,
document.getElementById("root")
)
You defined the component as App, yet in ReactDOM.render you are using app
You have </app> at the end of the file. It doesn't do anything in this case.

Ember active link

I have a route where I want to make a sibling route's link-to's active as well. I have tried using current-when in the link-to, but it's not working for me.
my routes are as follows
//projects
//projects/:project_id
//projects/:project_id/user/:user_id
When I navigate to //projects/:project_id route, the right link is set to active. I want the same link to be active on the //projects/:project_id/users/:user_id route.
My link-to in the parent //projects hbs template is
{{#link-to "projects.project" item.projectID current-when="projects.user" tagName="tr"}}
What am I doing wrong here?
UPDATE
I was able to get it to initially work when the route is rendered by using an edited version of #ykaragol's helper function and link-to...
{{#link-to "projects.project" item.projectName active=(calculate-active 'projects.user projects.project' item.projectName) tagName="tr"}}
compute(params, hash){
var pathname = window.location.pathname.split('/');
var pathProj = pathname[2];
var currRoute = this.get('currentRouteName');
var routes = params[0].split(' ');
if( ($.inArray( currRoute, routes) > -1) && (pathProj == params[1]) ){
return true;
}
return false;
}
But it's not updating when I click on a different project...
If routes don't have dynamic segments, it works as described in docs. I've tested it within this twiddle.
But I couldn't make it work while using dynamic segment. Please check this twiddle. I suspect this maybe a bug. You can ask this question in slack.
By the way, as a workaround, you can pass a boolean to the currentWhen property (as mentioned in docs). So you can write a helper or a computed property to calculate it with a regex.
Updated:
As a second workaround, you can handle active property of link-to by yourself. Try this twiddle.

How can I include given Handlebars helpers in Ember

On Github, many Handlebars helpers are presented. You can find them here.
I'd like to use them, but have no Idea, how to include them. The code is looking as it's javascript (files are ending with .js ...), but words like 'import','export','default' are confusing me.
As I understand (guess), I have to include the if-condition.js at first. Later, the other (included) files refer to this file.
But when I do this, the console throws an Error:
Uncaught SyntaxError: Unexpected reserved word .
Has anyone an idea, how to get these codes working?
import and export are keywords for the upcoming module syntax in the next version of Javascript. You can use them today by using a transpiler to convert it to normal ES5 syntax.
However, if you're only using a few helpers, it's very easy to 'transpile' them by hand. Instead of exporting the function, just pass it to a Ember.Hanldebars.registerBoundHelper call. Here's the if-condition helper:
Ember.Handlebars.registerBoundHelper('if-condition', function() {
var args = [].slice.call(arguments);
var options = args.pop();
var context = (options.contexts && options.contexts[0]) || this;
if (!options.conditional) {
throw new Error("A conditional callback must be specified when using the if-condition helper");
}
// Gather all bound property names to pass in order to observe them
var properties = options.types.reduce(function(results, type, index) {
if (type === 'ID') {
results.push(args[index]);
}
return results;
}, []);
// Resolve actual values for all params to pass to the conditional callback
var normalizer = function() {
return Ember.Handlebars.resolveParams(context, args, options);
};
// This effectively makes the helper a bound helper
// NOTE: 'content' path is used so that multiple properties can be bound to using the `childProperties` argument,
// however this means that it can only be used with a controller that proxies values to the 'content' property
return Ember.Handlebars.bind.call(context, 'content', options, true, options.conditional, normalizer, properties);
});

How can I dynamically render HTML using Meteor Spacebars templates?

So let's say I'm storing <div>{{name}}</div> and <div>{{age}}</div> in my database.
Then I want to take the first HTML string and render it in a template - {{> template1}} which just renders the first string with the {{name}} handlebar in it. Then I want to give that newly generated template/html data, so that it can fill in the handlebar with the actual name from the database, so that we would get <div>John</div>. I've tried doing
<template name="firstTemplate">
{{#with dataGetter}}
{{> template1}}
{{/with}}
</template>
Where template1 is defined as
<template name="template1">
{{{templateInfo}}}
</template>
And templateInfo is the helper that returns the aforementioned html string with the handlebar in it from the database.
dataGetter is just this (just an example, I'm working with differently named collections)
Template.firstTemplate.dataGetter = function() {
return Users.findOne({_id: Session.get("userID")});
}
I can't get the {{name}} to populate. I've tried it a couple of different ways, but it seems like Meteor doesn't understand that the handlebars in the string need to be evaluated with the data. I'm on 0.7.0 so no Blaze, I can't upgrade at the moment due to the other packages I'm using, they just don't have 0.8+ version support as of yet. Any ideas on how I can get this to work are much appreciated.
In 1.0 none of the methods described above work. I got this to work with the function below defined in the client code. The key was to pass the options { isTemplate: true} to the compile function.
var compileTemplate = function(name, html_text) {
try {
var compiled = SpacebarsCompiler.compile(html_text, { isTemplate:true });
var renderer = eval(compiled);
console.log('redered:',renderer);
//Template[name] = new Template(name,renderer);
UI.Template.__define__(name, renderer);
} catch (err){
console.log('Error compiling template:' + html_text);
console.log(err.message);
}
};
The you can call with something like this on the client:
compileTemplate('faceplate', '<span>Hello!!!!!!{{_id}}</span>');
This will render with a UI dynamic in your html
{{> Template.dynamic template='faceplate'}}
You can actually compile strings to templates yourself using the spacebars compiler.. You just have to use meteor add spacebars-compiler to add it to your project.
In projects using 0.8.x
var compiled = Spacebars.compile("<div>{{name}}</div> and <div>{{age}}</div>");
var rendered = eval(compiled);
Template["dynamicTemplate"] = UI.Component.extend({
kind: "dynamicTemplate",
render: rendered
});
In projects using 0.9.x
var compiled = SpacebarsCompiler.compile("<div>{{name}}</div> and <div>{{age}}</div>");
var renderer = eval(compiled);
Template["dynamicTemplate"] = Template.__create__("Template.dynamicTemplate", rendered);
Following #user3354036's answer :
var compileTemplate = function(name, html_text) {
try {
var compiled = SpacebarsCompiler.compile(html_text, { isTemplate:true }),
renderer = eval(compiled);
console.log('redered:',renderer);
//Template[name] = new Template(name,renderer);
UI.Template.__define__(name, renderer);
} catch (err) {
console.log('Error compiling template:' + html_text);
console.log(err.message);
}
};
1) Add this in your HTML
{{> Template.dynamic template=template}}
2) Call the compileTemplate method.
compileTemplate('faceplate', '<span>Hello!!!!!!{{_id}}</span>');
Session.set('templateName','faceplate');
Save the template name in a Session variable. The importance of this is explained in the next point.
3) Write a helper function to return the template name. I have used Session variable to do so. This is important if you are adding the dynamic content on a click event or if the parent template has already been rendered. Otherwise you will never see the dynamic template getting rendered.
'template' : function() {
return Session.get('templateName');
}
4) Write this is the rendered method of the parent template. This is to reset the Session variable.
Session.set('templateName','');
This worked for me. Hope it helps someone.
If you need to dynamically compile complex templates, I would suggest Kelly's answer.
Otherwise, you have two options:
Create every template variation, then dynamically choose the right template:
eg, create your templates
<template name="displayName">{{name}}</template>
<template name="displayAge">{{age}}</template>
And then include them dynamically with
{{> Template.dynamic template=templateName}}
Where templateName is a helper that returns "age" or "name"
If your templates are simple, just perform the substitution yourself. You can use Spacebars.SafeString to return HTML.
function simpleTemplate(template, values){
return template.replace(/{{\w+}}/g, function(sub) {
var p = sub.substr(2,sub.length-4);
if(values[p] != null) { return _.escape(values[p]); }
else { return ""; }
})
}
Template.template1.helpers({
templateInfo: function(){
// In this context this/self refers to the "user" data
var templateText = getTemplateString();
return Spacebars.SafeString(
simpleTemplate(templateText, this)
);
}
Luckily, the solution to this entire problem and any other problems like it has been provided to the Meteor API in the form of the Blaze package, which is the core Meteor package that makes reactive templates possible. If you take a look at the linked documentation, the Blaze package provides a long list of functions that allow for a wide range of solutions for programmatically creating, rendering, and removing both reactive and non-reactive content.
In order to solve the above described problem, you would need to do the following things:
First, anticipate the different HTML chunks that would need to be dynamically rendered for the application. In this case, these chunks would be <div>{{name}}</div> and <div>{{age}}</div>, but they could really be anything that is valid HTML (although it is not yet part of the public API, in the future developers will have more options for defining this content in a more dynamic way, as mentioned here in the documentation). You would put these into small template definitions like so:
<template name="nameDiv">
<div>{{name}}</div>
</template>
and
<template name="ageDiv">
<div>{{age}}</div>
</template>
Second, the definition for the firstTemplate template would need to be altered to contain an HTML node that can be referenced programmatically, like so:
<template name="firstTemplate">
<div></div>
</template>
You would then need to have logic defined for your firstTemplate template that takes advantage of some of the functions provided by the Blaze package, namely Blaze.With, Blaze.render, and Blaze.remove (although you could alter the following logic and take advantage of the Blaze.renderWithData function instead; it is all based on your personal preference for how you want to define your logic - I only provide one possible solution below for the sake of explanation).
Template.firstTemplate.onRendered(function() {
var dataContext = Template.currentData();
var unrenderedView = Blaze.With(dataContext, function() {
// Define some logic to determine if name/age template should be rendered
// Return either Template.nameDiv or Template.ageDiv
});
var currentTemplate = Template.instance();
var renderedView = Blaze.render(unrenderedView, currentTemplate.firstNode);
currentTemplate.renderedView = renderedView;
});
Template.firstTemplate.onDestroyed(function() {
var renderedView = Template.instance().renderedView;
Blaze.remove(renderedView);
});
So what we are doing here in the onRendered function for your firstTemplate template is dynamically determining which of the pieces of data that we want to render onto the page (either name or age in your case) and using the Blaze.With() function to create an unrendered view of that template using the data context of the firstTemplate template. Then, we select the firstTemplate template element node that we want the dynamically generated content to be contained in and pass both objects into the Meteor.render() function, which renders the unrendered view onto the page with the specified element node as the parent node of the rendered content.
If you read the details for the Blaze.render() function, you will see that this rendered content will remain reactive until the rendered view is removed using the Blaze.remove() function, or the specified parent node is removed from the DOM. In my example above, I am taking the reference to the rendered view that I received from the call to Blaze.render() and saving it directly on the template object. I do this so that when the template itself is destroyed, I can manually remove the rendered view in the onDestroyed() callback function and be assured that it is truly destroyed.
A very simple way is to include in the onRendered event a call to the global Blaze object.
Blaze.renderWithData(Template[template_name], data ,document.getElementById(template_id))