4

I have a big chunk of deeply-nested semi-structured JSON and would like to generate HTML from it. At the moment I'm using jQote2, but much of the code inside my templates deals with dynamically finding the next template to render and then calling it. What's a single <xsl:apply-templates> in XSLT takes several lines with JavaScript and jQuote. I dearly miss the pattern matching capabilities of XSLT. Is there any (templating) library in JavaScript that allows me to dynamically decide from the data which template to render?

Here is an example of what I want. Suppose I have a JSON structure like this:

{
  items:[
   {foo:1, bar:2},
   {foo:7, baz:99},
   {foo:8, quux:3}
  ],
  curdate:'2010-07-07'
}

I'd like to have a "root" template that renders the curdate field and then renders the items. If an item contains a "bar" field, I want the item to be rendered with a template named "tpl-bar" (or something like that), otherwise a template named "tpl-foo" should be used. Filtering capabilities (like "do not render items that have a quux field") would be a nice-to-have.

I am aware of the JSONT library, however from what I see it's not dynamic enough to accomplish what I described.

If no such library exists, I'm on the verge of giving it a shot myself. But I'm not sure how to do it at the moment. Code examples or general descriptions would help me.

1
  • Unless you want to process your JSON string with XSLT 2.0 and its RegExp feature, I think you should retag. Commented Aug 4, 2010 at 14:12

1 Answer 1

2

There's also JSLT, from what I remember reading it's a little more advanced than JSONT. I've never actually used it, though. The problem is that these libraries aren't hugely popular and so not a lot of work gets done to improve them and build upon them.

On the plus side, it's open source so if you don't find a feature you want you could attempt to add it yourself.

Sign up to request clarification or add additional context in comments.

2 Comments

The JSLT website is down, atm. Too bad, as I'd love to see an XSLT port for JavaScript templating.
There is a JSLT that looks like it is for transforming JavaScript source, a much larger problem. That was described here: ajaxian.com/archives/jslt-a-javascript-alternative-to-xslt and references to the JSLT web site are broken. But a completely different JSLT just for transforming JSON objects is a very minimal piece of code described in an answer here: softwareengineering.stackexchange.com/questions/264706/… Maybe a more recent example with code for the Per function at the bottom: jsfiddle.net/c7usrpsL/12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.