I’m working on a small to-do app with HTMX and Rust to get more familiar with both, but I’m running into a parsing issue with my templates.
Here’s my cargo.toml
:
[package]
name = "todo2"
version = "0.1.0"
edition = "2021"
[dependencies]
askama = { version = "0.12.1", features = ["with-rocket"] }
askama_rocket = "0.12.0"
rocket = {version = "0.5.0", features = ["json"] }
mongodb = "2.8.2"
serde = "1.0.198"
leptos = "0.6.11"
Rocket for the webserver, askama (and it’s rocket integration) for the templating.
Here’s main.rs
:
#[macro_use]
extern crate rocket;
use askama_rocket::Template;
use mongodb::bson::oid::ObjectId;
use rocket::{fs::{relative, FileServer, Options}, http::Status, response::{content, status}};
struct Item {
id: ObjectId,
completed: bool,
starred: bool,
text: String
}
#[derive(Template)]
#[template(path = "base.html")]
struct Homepage {
title: &'static str,
items: Vec<Item>
}
#[get("/")]
fn hello() -> status::Custom<content::RawHtml<String>> {
let new_item1 = Item { completed: false, starred: false, text: "Example to-do item 1".to_owned() };
let new_item2 = Item { completed: false, starred: true, text: "Example to-do item 2".to_owned() };
let new_item3 = Item { completed: true, starred: false, text: "Example to-do item 3".to_owned() };
let new_item4 = Item { completed: true, starred: true, text: "Example to-do item 4".to_owned() };
let items = vec![new_item1, new_item2, new_item3, new_item4];
let home = Homepage {
title: "To-Do",
items: items
};
let body = home.render().unwrap();
status::Custom(Status::Ok, content::RawHtml(body))
}
#[post("/")]
fn greet() -> status::Custom<content::RawHtml<String>> {
let response = String::from("
<p>Response from <b>HTMX</b>!</p>
");
status::Custom(Status::Ok, content::RawHtml(response))
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", FileServer::new(relative!("www"), Options::None))
.mount("/", routes![hello, greet])
}
And of course, base.html
:
{% import "item.html" as item(data) %}
<!DOCTYPE html>
<html>
<head>
<script src='https://unpkg.com/htmx.org@latest'></script>
<link rel="stylesheet" href="style.css">
<title>{{ title }}</title>
{% block head %}{% endblock %}
</head>
<body>
<h1>Hello World</h1>
<table>
<tbody hx-target="closest tr" hx-swap="outerHTML">
{% for data in items %}
{{ call item(data) }}
{% endfor %}
<tr>
<td><button disabled="disabled">X</button></td>
<td><input type="checkbox" name="completed" disabled></td>
<td><img src="/media/star.png"></td>
<td><input type="text" name="text" maxlength="255"></td>
<td><button hx-post="/" hx-include="closest tr">></button></td>
</tr>
</tbody>
</table>
</body>
</html>
The compiler error I’m getting is:
error: problems parsing template source at row 1, column 29 near:
"(data) %}nn<!DOCTYPE html>n<html>n<head>"...
--> src/main.rs:15:10
|
15 | #[derive(Template)]
| ^^^^^^^^
|
= note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info)