templatesというディレクトリに、ルート名と同じファイル名でhtmlファイルを作成するというルールにする。
fn main() {
let address = "192.168.33.10:8000";
let mut routes = HashMap::new();
let mut paths: Vec<&str> = Vec::new();
paths.push("index");
paths.push("hello");
for path in paths {
let temp_path = format!("./templates/{}.html", path);
let content = fs::read_to_string(temp_path).unwrap();
let route_path = format!("/{}", path);
routes.insert(
route_path, content,
);
}
println!("{:?}", routes);
}
{“/index”: “
Hello from Rust!
“, “/hello”: “
Welcome to the Rust server!
“}
teraの場合は、tera.renderとして、任意のファイル名を指定できるようにしている。これも、hashmapで、ルート名とファイル名をkey, valueで持っていれば、問題なくできそうでる。
### テンプレートエンジンの変数の扱い
hashmapでkeyとvalueを格納して、htmlの{{ @name }} とkeyが一致したものをvalueに変換すればできそうである。。
let mut context = tera::Context::new();
context.insert("title", "Index page");
{{title}}
### Rustで{{ }}を置換するように実装
let mut content = HashMap::new();
content.insert(
"title",
"index page",
);
let mut data = HashMap::new();
for (key, value) in content {
let k = format!("{{{{ {} }}}}", key);
data.insert(
k, value,
);
};
println!("{:?}", data);
let mut str = "<h1>Welcome to the {{ title }} server!</h1>";
for (key, value) in data {
let s = &str.replace(&key, value);
println!("{}", s);
};
### テンプレートに引き渡す変数がある時
pathにhashmapで変数のセットを紐づけて、後で置換するようにする。
let mut content = HashMap::new();
content.insert(
"title",
"index page",
);
let mut data = HashMap::new();
for (key, value) in content {
let k = format!("{{{{ {} }}}}", key);
data.insert(
k, value,
);
};
let mut str = "<h1>Welcome to the {{ title }} server!</h1>";
let mut paths: Vec<(&str, Option<HashMap<String, &str>>)> = Vec::new();
paths.push(("index", Some(data)));
paths.push(("hello", None));
println!("{:?}", paths);
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.33s
Running `target/debug/ares`
[(“index”, Some({“{{ title }}”: “index page”})), (“hello”, None)]
### 全部繋げる
let mut paths: Vec<(&str, Option<HashMap<String, &str>>)> = Vec::new();
let mut content = HashMap::new();
content.insert(
"title",
"index page",
);
content.insert(
"data1",
"10000",
);
let mut data = HashMap::new();
for (key, value) in content {
let k = format!("{{{{ {} }}}}", key);
data.insert(
k, value,
);
};
paths.push(("index", Some(data)));
paths.push(("hello", None));
let mut routes = HashMap::new();
for (path, v) in paths {
let temp_path = format!("./templates/{}.html", path);
let mut content = fs::read_to_string(temp_path).unwrap();
match v {
Some(data) =>
for (key, value) in data {
content = content.replace(&key, value);
},
None => {},
}
let route_path = format!("/{}", path);
routes.insert(
route_path, content,
);
};
println!("{:?}", routes);
{“/index”: “
Hello from Rust! title:index page
“, “/hello”: “
Welcome to the Rust server!
“}