Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store large string literals to be used with the format macro without littering code?

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?

like image 383
janqo Avatar asked Oct 21 '25 06:10

janqo


1 Answers

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);
like image 83
user2722968 Avatar answered Oct 23 '25 23:10

user2722968



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!