I am in the process of building an isomorphic JavaScript framework and I need some help deciding between two options for our templates.
I have two different strategies I am trying to choose between. I have both working and functionally either will be fine, but thing in particular I am trying to think about now is which one would be easier to grok and more accepted by developers/contractors we hire or community members we get to help out on open source pieces.
Note: both options using our jeff.js templating lib which is essentially JavaScript/JSON instead of HTML.
The basic idea here is to have Node functions that are used to either bind data on the server side or generate HTML for the client side. For ex:
repeat(model.questions, function (question) {
return div({ class: 'blah'}, question.title);
})
Which would generate this on the server:
<div class="blah">something 1</div>
<div class="blah">something else 2</div>
<div class="blah">one more thing 3</div>
Or this on the client:
<div class="blah" ng-repeat="question in questions">{{ question.title }}</div>
The way this works is that essentially the server side runtime and client side build process have different implementations of the repeat() function.
We can actually use the Angular Style witin our jeff.js templates like this:
div({ 'ng-repeat': 'question in questions' }, '{{ question.title }}')
which will generate the exact same HTML on the server and client as Option 1 above. For the client generation, the code is very simple since the markup is a match to the final client HTML. For the server, the jeff.js template engine has rendering handlers for all Angular tags that are binding in nature (i.e. ng-repeat, ng-bind, ng-show, etc.) and the server values are dynamically injected through a series of JavaScript evals. So, sort of cool...but sort of evil as well ;)
Just out of curiosity, what does a non-trivial example look like in these two formats (server-side)? It's not immediately obvious to me how you're handling nesting. For example, how would you output something like this:
Assuming that the href and text values there were passed in from your JSON model.
I'm leaning towards #2 as well either way. It seems to keep both client and server closer contextually.
Also, you can probably implement it without an eval statement if you didn't trust the template source - it'd just be harder. You would need still to eval if you expect to support any possible statement, similar to what angular gives you with
{{ 2 + 2}}
. But if you're just looking to access objects in your model you could do some fancy string parsing along these lines:http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference