项目作者: ReSpeak

项目描述 :
T4-like templates for rust
高级语言: Rust
项目地址: git://github.com/ReSpeak/t4rust.git
创建时间: 2017-10-11T01:00:23Z
项目社区:https://github.com/ReSpeak/t4rust

开源协议:Other

下载


t4rust

dependency status

About

t4rust is a minimal templating engine, inspired by the T4 syntax.

Example

A simple example how to create a template.

  1. use t4rust_derive::Template;
  2. // Add this attribute to use a template
  3. #[derive(Template)]
  4. // Specify the path to the template file here
  5. #[TemplatePath = "./examples/doc_example1.tt"]
  6. // Add this attribute if you want to get debug parsing information
  7. // This also enables writing temporary files, you might get better error messages.
  8. //#[TemplateDebug]
  9. struct Example {
  10. // Add fields to the struct you want to use in the template
  11. name: String,
  12. food: String,
  13. num: i32,
  14. }
  15. fn main() {
  16. // Generate your template by formating it.
  17. let result = format!("{}", Example { name: "Splamy".into(), food: "Cake".into(), num: 3 });
  18. println!("{}", result);
  19. }

doc_example1.tt:

  1. Hello From Template!
  2. My Name is: <# write!(_fmt, "{}", self.name)?; #>
  3. I like to eat <#= self.food #>.
  4. <# for num in 0..self.num { #>Num:<#= num + 1 #>
  5. <# } #>

Output:

  1. Hello From Template!
  2. My Name is: Splamy
  3. I like to eat Cake.
  4. Num:1
  5. Num:2
  6. Num:3

Syntax

You can simply write rust code within code blocks.

Code is written within <# and #> blocks.
If you want to write a <# in template text without starting a code block
simply write it twice: <#<#. Same goes for the #> in code blocks.
You dont need to duplicate the <# within code blocks and #> not in
template text blocks.

You can use <#= expr #> to print out a single expression.

Maybe you noticed the magical _fmt in the template. This variable gives you
access to the formatter and e.g. enables you to write functions in your
template. <# write!(_fmt, "{}", self.name)?; #> is equal to <#= self.name #>.

Warning: Make sure to never create a variable called _fmt! You will get
weird compiler errors.

Features

Auto-escaping

Use the escape directive in your .tt file:

  1. <#@ escape function="escape_html" #>`

And a function with this signature in your code:

  1. fn escape_html(s: &str) -> String {
  2. todo!(); /* Your escaping code here */
  3. }

All expression blocks (e.g. <#= self.name #>) will call the escape
function before inserted.

You can redeclare this directive as many times and where you want in your
template to change or disable (with function="") the escape function.

License

Licensed under either of

at your option.