Writing handlebars in Ember - javascript

I have a small app which is multilingual. The text of the app is coming from the server. The text can be in different language. For now lets stick to Swedish and English. User can switch between languages. What I am trying to do is when the app loads get the text in both languages and store it in models in Ember.
Then I am trying to write a Handlebars helper which will allow me to switch between the languages. For example the data from the server I am getting is in this form.
langData: {
sv_SE: {
start_page: "..."
},
en_US: {
start_page: "..."
}
My model for this is language.js which is like this
App.Language = DS.Model.extend({
language: DS.attr('string'),
start_page: DS.attr('string'),
});
In my handles bar I am trying to do something like this
Ember.Handlebars.helper('__', function(key, lang, options) {
// get the text specified for the language. A function which will check the language model and
// fetch data for the particular key from it
});
I am calling the handles bar like this
{{__ start_page en_US}}
What I am thinking that, this will return me start page text in English language.
Is this the right way? If not what will be the right way? Also, I will have different text strings which will be used in different hbs files.

I've used Ember-I18n for a project successfully. It gives you a place to put your translations outside a model. I then load the current language based on a cookie or a setting on the user model. Switching to a different language does require a full-page reload for me, but you might be able to get it to work without that.

Related

Using handlebars.js for dynamic user content?

Handlebars is commonly used on static predefined html templates and then given dynamic data via JSON, but what if the template itself comes from json?
I'm trying to build a community forum whereby I have a template that gets filled in for where the users post goes. The post itself however also contains template information (which is dynamic). How can I get handlebars to process a dynamic template that just came out of ajax?
For example, a users post can contain any or all of the following in any order: text, pictures, links, videos, etc.
The content will look something like this:
{{text-open}} blablabla heres a picture {{text-close}}{{image-open}}
http://someRandomUrl.com {{image-close}} {{image-open}}
http://anotherRandomUrl {{image-close}}
I'm not sure how to do this with handlebars. I have the feeling maybe I should just use a string replace function? But would that be the optimal method?
You just have to compile the template:
fetch("post.hbs")
.then(source => Handlebars.compile(source))
.then(postTemplate => {
// Do stuff, then fill the template:
postElement.innerHTML = postTemplate(postData);
});

Storing HTML in Firebase (AngularFire), good idea or bad?

Is it a good idea to store HTML in Firebase (AngularFire)?
I have a website where I am creating an admin site where users can make HTML elements. I want people to save these elements and the order and the content within the elements. So I thought it would be much easier to just store the whole HTML as a string and load it in when they return. Bad idea?
Here is what I have (simplification):
$scope.save = function() {
var refState = new Firebase("https://<name>.firebaseio.com/users/" + currentAuth.uid + "/state");
var html = "<div>hello</div>";
refState.set({
"state": html
}, function(error) {
if (error) {
console.log("not been saved")
}
})
}
And in my HTML I retrieve want to display it like this using Angular, (yeah I know now how to render HTML in Angular thanks to the comments :)
<div class="well col-md-12">
{{sync[3].state}}
</div>
Storing stringified HTML in firebase is no worse than storing it in a different datastore. You'll want to consider XSS issues, including things like what if they define <style>body{display:none}</style> in their html.
Are you creating a real full fleshed content creation system? If so, it's sometimes hard to get away from user defined HTML, usually from CKeditor, tinymce, etc. However, if the items that they're building are all similar, you should consider how you can store/restore them in a better data format. Most of the time there is a better way to save and restore user defined content that storing straight HTML.
I'd suggest checking out Firepad.
Firepad is a drop-in "Open source collaborative code and text editing" experience for Firebase apps.
"Firepad can use either the CodeMirror editor or the Ace editor to render documents."
Easily allows for a rich text-editor experience that seamlessly stores/syncs the content in a Firebase instance.
As the documentation describes, this is how you initialize Firepad:
<div id="firepad"></div>
<script>
var firepadRef = new Firebase('<FIREBASE URL>');
var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror,
{ richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!' });
</script>
It's perfectly fine to store HTML in Firebase.
Koding.com, Nitrous.io, and more use Firepad for their collaborative code editor products.
I think it's very bad idea to store html in firebase, store only pain text
How to render html with angular templates

How to manipulate HTML table once it's returned from backend like Node.js?

Here's the situation: I use Node.js as my backend, and use markdown to edit and post my blog article. And when a client requests the specific URL, such as http://www.example.com/blog/article_1, I returned the blog contents from Node.js with some template like ejs, which would be something like the follows:
app.get("/blog/article1", function(req, res) {
var article = something // this is a valid HTML converted from a markdown file
res.render("article1", {
title: "my blog article 1",
article: article
});
});
In the above code, I render article.ejs with title and article variable. The article variable is a valid HTML to be injected to the ejs template. So far, it' fine.
However, if I want to display a HTML table which is written in the original markdown file, with Bootstrap 3's responsive table functionality, (i.e. <div class="table-responsive"><table class="table">...actual table...</table></div>), how can I do it? Right now the table in my markdown file is just a markdown file, and I don't think that it's the best idea to just modify all of my markdown files on which I insert or wrap with the <div class="table-responsive">...</div> line; the files might also be used in a situation other than Bootstrap.
In other words, is it feasible to dynamically or programmatically inject the responsive functionality to the table once the template is returned by Node.js? And is it also feasible to inject the responsive table functionality selectively? (in other words choose arbitrarily some tables that I want to add the responsive function?)
Continuing on from the comments: It's actually not that difficult to fork and modify a project. The faster you can get used to working with open source libraries the better your experience will be with Node. Things move pretty quickly in the Node world, and sometimes things won't work like they are expected to. You can either wait around for a fix, or roll up your sleeves and pitch in.
I found a way to update the markdown templates using their addTemplate method. However the version of Marked the project is using (2.8) doesn't support custom templates. I've forked the repository and updated the version of marked as well as fixed the issues this caused with the tests. I also added a restriction to prevent it from using Express 4 which breaks all the tests. I submitted these as a pull request to the original repo, but in the mean time you could use my version to write something like the following.
untested
var
express = require('express'),
app = express(),
Poet = require('poet'),
marked = require('marked'),
renderer = new marked.Renderer();
renderer.table = function(header, body) {
return '<div class="table-responsive"><table class="table">' + header + body + '</table></div>';
}
var poet = Poet(app, {
posts: './_posts/',
postsPerPage: 5,
metaFormat: 'json'
});
poet.addTemplate({ ext: 'markdown', fn: function(s) {
return marked(s);
}});
Alternatively, if all you're using poet for is the markdown conversion, you might as well use marked directly and cut out the dependency on poet.

How should I handle Asp.net MVC URLs in javascript calls?

I am attempting to write a javascript heavy portion of my Asp.net MVC Web App (this portion of the website is a RIA using Extjs). However, I have come up to a standstill at the correct way to handle URLs in the javascript.
For example, right now I have an Ajax call to the List action in the ObjectsController, which resides in the Reading area. The List action takes a parameter of documentId (int). As of right now, this maps to /Reading/Objects/List since I have no changed routing yet (the site is too young at the moment to finalize routes). Normally in a view, to put this URL in a string I would do #Html.Action("List", "Objects", new { area = "Reading", documentId = 3).
However, this doesn't work when dealing with javascript, since javascript isn't parsed by a viewengine.
To get around this, I have a very small view that returns javascript constants, such as URLs, that is loaded prior to my main application's js files. The issue is that I can't call Html.Action for this action because at constant creation time I (obviously) do not know what documentId the ajax calls are going to be, and if you exclude documentId from the Html.Action call an exception occurs. The documentId could change during the normal workflow of the application.
How do I handle this? I don't want to hardcode the URL to /Reading/Objects/List because if I change my routing for this (for a more user friendly json API), or this web app isn't hosted on the root of the domain, the URL will no longer be valid.
How does everyone else handle MVC URLs in their javascript calls?
Here's a safe technique that I've been using. Even if your route changes, your JavaScript will automatically conform to the new route:
<script>
var url = '#Url.Action("List", "Objects", new { area = "Reading", documentId = "_documentId_")';
var id = 100;
var finalUrl = url.replace('_documentId_', id);
</script>
"_documentId_" is essentially a dummy placeholder. Then inside my JavaScript, I replace "_documentId_" with the proper id value once I know what it is. This way, regardless of how your route is configured, your URL will conform.
Update: Dec 20
I just saw this interesting blog post. The author built a library that allows you to build routes inside of your JavaScript file with intellisense support in VisualStudio.
http://weblogs.asp.net/zowens/archive/2010/12/20/asp-net-mvc-javascript-routing.aspx
Personally I use unobtrusive javascript and avoid mixing markup with javascript. AJAX calls are normally triggered by clicking on some buttons or links:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading", documentId = 3 }, new { id = "foo" })
and then in a separate js file I would attach and handle the onclick event (example with jquery):
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href);
return false;
});
});
As you can I didn't need to use any hardcoded URL in my javascript file. URLs should always be handled by the routing engine and generated with html helpers.
If it was a <form> instead of a link I would simply handle the onsubmit event (the same way) and use the form's action attribute to get the URL.
UPDATE:
After pointing out in the comments section that the documentId is known only at client-side you could do this:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading" }, new { id = "foo" })
And then:
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href, { documentId: '123' });
return false;
});
});
Turns out, this was all solved by using Url.Action() instead of Html.Action(). Url.Action() is (so far) allowing me to generate URLS without all of the parameters. I am assuming that this only works when the route does not specify the parameters in the target URL itself.

Django Dynamic Drop-down List from Database

I wanted to develop a Django app and one of the functionalities I'd like to have is dynamic drop-down lists...specifically for vehicle makes and models...selecting a specific make will update the models list with only the models that fall under that make....I know this is possible in javascript or jQuery (this would be my best choice if anyone has an answer) but I don't know how to go about it.
Also, I'd want the make, model, year and series to be common then the other attributes like color, transmission etc to be variables so that one needs only enter the make, model, year, and series only for a new vehicle. Any ideas would be highly appreciated.
The 3 things you mention being common, make, model, year, would be the 3 input values. When given to the server, an object containing the details would be returned to the calling page. That page would parse the object details (using JavaScript), and update the UI to display them to the user.
From the Django side, there needs to be the facilities to take the 3 inputs, and return the output. From the client-side, there needs to be the facilities to pass the 3 inputs to the server, and then appropriately parse the server's response.
There is a REST api framework for Django that makes it rather easy to add the "api" mentioned above -- Piston. Using Piston, you'd simply need to make a URL for that resource, and then add a handler to process it. (you'll still need to skim the Piston documentation, but this should give you an idea of what it looks like)
urls.py:
vehicle_details = Resource(handler=VehicleDetails)
url(r'^vehicle/(?<make>.*)/(?<model>.*)/(?<year\d{2,4}/(?P<emitter_format>[a-z]{1,4}), vehicle_details, name='vehicle_details'),
handler.py:
class VehicleDetails(BaseHandler):
methods_allowed = ('GET',)
model = Vehicles #whatever your Django vehicle model is
def read(self, request, *args, **kwargs):
# code to query the DB and select the options
# self.model.objects.filter()...
# Build a custom object or something to return
return custom_object
This simply sets up the url www.yoursite.com/vehicle/[make]/[model]/[year]/json to return a custom data object in JSON for jquery to parse.
On the client side, you could use jquery to setup an event (bind) so that when all 3 drop downs have a value selected, it will execute a $.get() to the api URL. When it gets this result back, it passes it into the Jquery JSON parser, and gives the custom object, as a javascript object. That object could then be used to populate more drop down menus.
(Big warning, I just wrote the following off the top of my head, so it's not meant to be copy and pasted. It's just for the general idea.)
<script type="text/javascript">
// On document load
$(function() {
$('#dropdown_make').bind('change', checkForValues());
$('#dropdown_model').bind('change', checkForValues());
$('#dropdown_year').bind('change', checkForValues());
});
function checkForValues() {
if ($('#dropdown_make').val() && $('#dropdown_model').val() && $('#dropdown_year').val())
updateOptions();
}
function updateOptions() {
url = '/vehicle/';
url += $('#dropdown_make').val() + '/';
url += $('#dropdown_model').val() + '/';
url += $('#dropdown_year').val() + '/';
url += 'json/';
$.get(url, function(){
// Custom data object will be returned here
})
}
</script>
This is uncanny: Dynamic Filtered Drop-Down Choice Fields With Django
His question:
"Here is the situation: I have a database with car makes and models. When a user selects a make, I want to update the models drop-down with only the models associated with that make. ... Therefore I want to use Ajax to populate the data."
You're not the same guy? :)

Categories

Resources