sailfish/docs/en/docs/getting-started.md

62 lines
1.3 KiB
Markdown
Raw Normal View History

2020-06-09 08:19:59 -04:00
# Getting Started
## Prepare the template file
Create a new directory named `templates` in the same directory as `Cargo.toml`. Copy the following contents and paste it to a new file named `templates/hello.stpl`.
2024-03-11 17:33:11 -04:00
```rhtml
2020-06-09 08:19:59 -04:00
<html>
<body>
<% for msg in &messages { %>
<div><%= msg %></div>
<% } %>
</body>
</html>
```
Now your project structure should be like this:
```text
Cargo.toml
src/
(Source files)
templates/
hello.stpl
```
## Render the template
<ol><li>Import the sailfish crates:</li></ol>
2020-06-09 08:19:59 -04:00
```rust
2024-03-11 17:33:11 -04:00
use sailfish::RenderOnce;
2020-06-09 08:19:59 -04:00
```
<ol start="2"><li>Define the template struct to be rendered:</li></ol>
2020-06-09 08:19:59 -04:00
```rust
2024-03-11 17:33:11 -04:00
#[derive(RenderOnce)] // automatically implement `TemplateOnce` trait
2020-06-09 08:19:59 -04:00
#[template(path = "hello.stpl")] // specify the path to template
2020-06-19 01:53:16 -04:00
struct HelloTemplate {
2020-06-09 08:19:59 -04:00
// data to be passed to the template
2020-06-19 01:53:16 -04:00
messages: Vec<String>,
2020-06-09 08:19:59 -04:00
}
```
<ol start="3"><li>Render the data with <code>render_once()</code> method.</li></ol>
2020-06-09 08:19:59 -04:00
```rust
fn main() {
let ctx = HelloTemplate {
2020-07-23 22:32:51 -04:00
messages: vec![String::from("foo"), String::from("bar")],
};
2020-06-09 08:19:59 -04:00
// Now render templates with given data
println!("{}", ctx.render_once().unwrap());
}
```
That's it!
2022-02-19 00:47:00 -05:00
You can find more examples in the [example](https://github.com/rust-sailfish/sailfish/tree/master/examples) directory in the sailfish repository.