500 Lines Series

A Template Engine

A template engine automatically generate codes by introducing programming flow-control method.

In an interpretation model, parsing produces a data structure representing the structure of the template. The rendering phase walks that data structure, assembling the result text based on the instructions it finds. For a real-world example, the Django template engine uses this approach.
In a compilation model, parsing produces some form of directly executable code. The rendering phase executes that code, producing the result. Jinja2 and Mako are two examples of template engines that use the compilation approach.
Our implementation of the engine uses compilation: we compile the template into Python code. When run, the Python code assembles the result.

  1. Faster performance, by using shortcuts
# The way we're used to seeing it:
result.append("hello")

# But this works the same:
append_result = result.append
append_result("hello")
  1. Use "*" to control para
self.code.extend([" " * self.indent_level, line, "\n"])
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容