I want to build a template engine (ITT not another template engine...) based on Razor.

I've been at it for quite a long time not getting anywhere and quite frankly I'm at my limit. I've tried rolling my own, I've tried generating using ANTLR and I reckon I just need someone to tell me if I have to bite the bullet and do this the hard way.

To be honest I've been trying to do this as simple as possible.

'@' denotes the start of a special statement. A statement could be:

  • an identifier of a variable
  • an identifier of a function call. Parens must be balanced, and handle strings.
  • the start of one of Java's logic constructs (if, for, while/do)
  • a single line statement that yields a output value @( )
  • a multi line block of statements @{ }

The part which is killing me: everything within {} is treated as code UNLESS:

  • it is escaped with @:. The line is treated as text
  • a html tag is found . Everything from that point on is treated as text

So, now we have issues as the '<' token now has context. It could either LT or the start of a HTML tag. It does not help either that a tag could also have attributes, and each attribute could also have special statements in them. Then, I also need to balance brackets and string quotes as well.

There is also the added complexity of the lack of terminating sentinels (unlike say, php, which has tags).

It seems impossible to parse these as alternating CODE - RAW - CODE - RAW tokens, so that the end result is simply me combining pieces of tokens into a Java class and let the Java compiler handle syntax. I'm just about to double down and reimplement the Java grammar and parse everything. Something which I am not keen on doing... :(

Anyway, let me know if there's any easier ways to approach this, or how you would attempt this exercise.

Regards, Daryl

  • 2
    have you looked into asp.net mvc source code to see how they do it? – devnull Feb 6 '14 at 6:51
  • @devnull have not actually... I wasn't aware there was source code available? I'll check. – Daryl Teo Feb 6 '14 at 7:13
  • @devnull well, some 50 odd classes. Not hard at all... =.= well I guess I was right (unfortunately...) I'm going to have to parse the entire thing as code. No laziness here. – Daryl Teo Feb 6 '14 at 7:21
  • Razor templates are converted (transcompiled?) in to C# classes (of type IView IIRC) which are then compiled and the single method called as normal. Perhaps you can do the same thing? (Will post this as an answer if that's better) – Andy Hunt Feb 6 '14 at 8:38
  • @AndyBursh That's what I wish to do. The problem is the transcompilation step. – Daryl Teo Feb 6 '14 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.