djc / askama

Type-safe, compiled Jinja-like templates for Rust
Apache License 2.0
3.49k stars 219 forks source link

Example of using DynTemplate #713

Open garytaylor opened 2 years ago

garytaylor commented 2 years ago

Being relatively new to rust, as I am sure others are, I am struggling to have a struct that derives 'Template' contain a field of type 'Anything that implements Template'. In other words, I want to dynamically render another template inside mine (not just include some html - I actually want to render a completely new template)

It seems I cannot do anything like put a box around Template as it is not object safe - the compiler suggested using DynTemplate

However, I cannot figure out how to use it

Maybe an example could be added to show this ?

Thanks

Gary

djc commented 2 years ago

For a template within a template, you can just treat the inner value as an expression in the outer template. Because all implementers of Template also implement fmt::Display, that should just work.

garytaylor commented 2 years ago

Yes, but I want to pass in the inner template as opposed to it being hard coded. I have developed a "Modal" component that can contain any other type of component - but the inner component needs to be passed in somehow - does that make sense ?

djc commented 2 years ago

Sure, it could also just be a T: Template or T: fmt::Display. DynTemplate is implemented by the macro for any type that impls Template and can be used like any object-safe trait.

garytaylor commented 2 years ago

I have yet to get used to generics - it's my next challenge in learning rust. The whole project I am doing is really just for learning, but it will have a final use if it is good enough quality. I come from a ruby background but also java from 20 years ago. I will take a look at going down that path - thanks for your help