A templating language that looks like Lisp and compiles to HTML
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compiler.js 1.0KB

123456789101112131415161718192021222324252627282930313233343536
  1. module.exports = class Compiler {
  2. constructor(tree, context) {
  3. this.tree = tree
  4. this.context = context
  5. this.result = ''
  6. }
  7. compile() {
  8. this.tree.forEach(node => {
  9. if (node.type === 'functionCall') {
  10. const attributes = node.args.map(arg => `${arg.attributeName}="${this.compileAttribute(arg.attributeValue)}"`)
  11. const compiler = new Compiler(node.subtree, this.context)
  12. const content = compiler.compile()
  13. this.result += `<${node.functionName}${attributes.length ? ' ' : ''}${attributes.join(' ')}>${content}</${node.functionName}>`
  14. } else if (node.type === 'string') {
  15. this.result += node.content
  16. } else if (node.type === 'identifier') {
  17. this.result += this.lookup(node.name)
  18. }
  19. })
  20. return this.result.trim()
  21. }
  22. compileAttribute(attribute) {
  23. if (attribute.type === 'string') {
  24. return attribute.content
  25. } else if (attribute.type === 'identifier') {
  26. return this.lookup(attribute.name)
  27. }
  28. }
  29. lookup(name) {
  30. return this.context[name]
  31. }
  32. }