Last updated

🔗What's up with transpilation?

Transpilation is the process of converting source code from one programming language to another. In this case, Tim is capable of transpiling its own scripting language into multiple target languages, such as JavaScript, Python, PHP, Lua, Ruby and Nim. This allows developers to write their templates in Tim's scripting language while still being able to use the generated code in their preferred programming language.

🔗Benefits of transpilation

Transpilation allows developers to write their templates in Tim's scripting language while still being able to use their favorite stack, tools and programming languages.

The front-end migration process can be a daunting task. Having your front-end logic written in scripting language like Tim can make the transition smoother, as you can transpile your existing code to the target language without having to rewrite it from scratch.

🔗Transpiling to JavaScript

Transpiling a Tim template to JavaScript is straightforward. Here, we have a simple Tim template that includes a variable and some HTML elements:

// Tim template with scripting language
div.container
  var name = "Tim Engine"
  p: $name

Now, using the src command, we can pass --ext:js to specify the target language for transpilation:

tim src example.timl --ext:js

The resulting JavaScript code would look something like this:

class Test {
  static render() {
    let html = "";
    {
      html += `<div class=\"container\">`;
        /** @type {any} */
        let name = "Tim Engine";
        {
          html += `<p>`;
          html += String(name);
          html += `</p>`;
        }
      html += `</div>`;
    }
    return html;
  }
}
module.exports = Test;

As you can see from the example, the Tim template is transpiled into a JavaScript class with a static render method that generates the HTML output. The variable name is defined and used within the method, demonstrating how the scripting language is transpiled into JavaScript code.

🔗Transpiling to Ruby

Transpiling the same template into Ruby is also possible using the --ext:rb flag. This will generate the following Ruby code:

class Test
  # @param args [Array] Additional arguments (not used in this method).
  # @return [String] The generated HTML for the homepage.
  def self.render(*args)
    html = +""
    html << "<div class=\"container\">"
        name = "Tim Engine"
        html << "<p>"
        html << name
        html << "</p>"
    html << "</div>"
    html
  end
end