4

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
janqo
  • 118
  • 5
  • Please define "litter", ideally with some objective metrics. What is "litter" to you might not be to other people, and it's a shame if someone tries to help you only to also "litter". Providing an example of what code you have (with a truncated literal!) is likely to also help. – Shepmaster Aug 08 '19 at 20:01
  • 1
    It'd be good to state what *hard constraints* you have. Are you requiring that specifically the `format` macro be used? – Shepmaster Aug 08 '19 at 20:04
  • 1
    `format!` seems to be the wrong tool to generate large pieces of HTML. – mcarton Aug 08 '19 at 20:06
  • @mcarton how is that wrong? – janqo Aug 08 '19 at 20:30
  • @Shepmaster it's hard to provide objective metrics as the question is rather about practices and appearance of code – janqo Aug 08 '19 at 20:31
  • 2
    @janqo at the very least you'd want a tool that understands HTML escaping. – mcarton Aug 08 '19 at 21:22

1 Answers1

4

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);
Optimistic Peach
  • 3,862
  • 2
  • 18
  • 29
user2722968
  • 13,636
  • 2
  • 46
  • 67
  • *I use the `format!` macro with "{}" in places in the literal* — please demonstrate how that would work with your solution. See also [println! error: expected a literal / format argument must be a string literal](https://stackoverflow.com/q/27734708/155423) – Shepmaster Aug 08 '19 at 20:02
  • 2
    @Shepmaster it in fact does work, I tested it locally and is reflected in my edit. – Optimistic Peach Aug 08 '19 at 22:34