From 694f02141feea67b415cc44b91f27c102037ba8f Mon Sep 17 00:00:00 2001 From: Utkarsh Kukreti Date: Sun, 24 Oct 2021 02:02:12 +0530 Subject: [PATCH] return new struct DynRender from new(); add an example which uses it --- markup/examples/dynamic.rs | 34 ++++++++++++++++++++++++++++++++++ markup/src/lib.rs | 18 ++++++------------ 2 files changed, 40 insertions(+), 12 deletions(-) create mode 100644 markup/examples/dynamic.rs diff --git a/markup/examples/dynamic.rs b/markup/examples/dynamic.rs new file mode 100644 index 0000000..53bbc3b --- /dev/null +++ b/markup/examples/dynamic.rs @@ -0,0 +1,34 @@ +markup::define! { + Tabs<'a>(tabs: &'a [Tab<'a>]) { + @for tab in tabs.iter() { + @tab + } + } + + Tab<'a>( + title: &'a str, + body: markup::DynRender<'a>, + ) { + h1 { @title } + div { @body } + } +} + +fn main() { + let tabs = [ + Tab { + title: "Home", + body: markup::new! { + p { "This is the home page." } + }, + }, + Tab { + title: "About", + body: markup::new! { + p { "This is the about page." } + }, + }, + ]; + + println!("{}", Tabs { tabs: &tabs }) +} diff --git a/markup/src/lib.rs b/markup/src/lib.rs index 87747fc..72df543 100644 --- a/markup/src/lib.rs +++ b/markup/src/lib.rs @@ -191,31 +191,25 @@ tuple_impl! { A B C D E F G H } tuple_impl! { A B C D E F G H I } tuple_impl! { A B C D E F G H I J } -struct Template { - f: F, +pub struct DynRender<'a> { + f: Box std::fmt::Result + 'a>, } -pub fn new<'a, F>(f: F) -> impl Render + std::fmt::Display + 'a +pub fn new<'a, F>(f: F) -> DynRender<'a> where F: Fn(&mut dyn std::fmt::Write) -> std::fmt::Result + 'a, { - Template { f } + DynRender { f: Box::new(f) } } -impl Render for Template -where - F: Fn(&mut dyn std::fmt::Write) -> std::fmt::Result, -{ +impl<'a> Render for DynRender<'a> { #[inline] fn render(&self, writer: &mut impl std::fmt::Write) -> std::fmt::Result { (self.f)(writer) } } -impl std::fmt::Display for Template -where - F: Fn(&mut dyn std::fmt::Write) -> std::fmt::Result, -{ +impl<'a> std::fmt::Display for DynRender<'a> { #[inline] fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { Render::render(self, fmt)