views:

129

answers:

5

I'm looking to create my own custom domain specific language that outputs HTML.

Basically, I want to be able to create quizzes using my own markup, but have that compiled / generated into HTML. For example:

> What is your favorite color?
* Blue
* Green
* Red

should output

<form action="" method="post">
<ul>
  <li>What is your favorite color?</li>
  <input type="radio" name="q1" answer="a" /> Blue <br />
  <input type="radio" name="q1" answer="b" /> Green <br />
  <input type="radio" name="q1" answer="c" /> Red <br />
</ul>

I know that ANTLR does something similar it but doesn't have an HTML output. Any other suggestions?

+1  A: 

You could try using Python Lex-Yacc. I've used it in the past for some academic experiments, and it worked nicely.

thedz
A: 

I would look for a tool (or write my own) that could generate XML:

<question text="What is you favorite color?">
  <choice text="Blue"/>
  <choice text="Green"/>
  <choice text="Red"/>
</question>

I would then use XSLT to transform the XML into HTML. In that way it decouples the presentation from the parsing.

Martin Liversage
HTML != Presentation. In that sense, there's no point in translating this into XML and then transform the XML to HTML using XSLT. Seems like an unnecessary additional step with no real benefit.
Lior Cohen
Any sensible approach will require a parser that parses the questionaire into a real or virtual parse tree. The HTML is then generated by visiting the tree. I'm merely suggesting to use XML for the intermediate representation and XSLT as the HTML generator. If required the XML representation could be in memory to avoid any external files. Text templates (http://msdn.microsoft.com/en-us/library/bb126445.aspx) is another nice tool for generating HTML. In my opinion embedding HTML into code is much less desirable.
Martin Liversage
A: 

ANTLR can be coupled with StringTemplate to output HTML. In this lab, Terence demonstrates using ANTLR and StringTemplate together.

Paul
A: 

I personally think that you don't need antlr in this case. You can simply use a couple of String.split to acheive this. For example, given '>' and '*' are reserved words,

String[] questions = text.split(">");
for(String question: questions){
    String[] item = question.split("*");
    System.out.println("<ul>);
    System.out.println("<li>" + item[0] + "</li>");
    for(int i = 1; i<item.length; i++){
     System.out.println("<input type=\"radio\" name=\"q1\" answer=\"" + i + "\" />" + item[i] + "<br />);
    }
    System.out.println("</ul>);
}

suits your need just fine.

Winston Chen
A: 

I like using TMF Xtext from Eclipse project, it is very simple and in combination with M2T Xpand can easily achieve your goal.

Gabriel Ščerbák