Reputation: 118
I have a function in my library that takes some variables and returns an HTML page with those variables inserted. What is the best practice not to litter my module with a large HTML literal? I mean that when I read my code it just "doesn't seem right" to have a piece of HTML that I have to scroll through.
I use the format!
macro with "{}" in places in the literal where I want insert variables so I guess that keeping the page as a file and loading it wouldn't work. I don't have to use format!
macro, but it seems elegant to not process text manually when I have this kind of tool.
Would creating an entire module just to hold this page be a good practice? In my mind a module is something "bigger", but maybe that's the best thing to do?
Upvotes: 4
Views: 977
Reputation: 16535
You can save the HTML in an external file and include it via std::include_str
. For example
let html_code = format!(include_str!("src/index.html"), my, values, in, the, template);
A playground application doesn't quite work here due to the compile-time requirement of the file, but locally the following worked:
src/
foo.txt -- "{}"
main.rs -- println!(include_str!("foo.txt"), 1234);
Upvotes: 4