Skip to content

Commit

Permalink
return new struct DynRender from new(); add an example which uses it
Browse files Browse the repository at this point in the history
  • Loading branch information
utkarshkukreti committed Oct 23, 2021
1 parent d16871e commit 694f021
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
34 changes: 34 additions & 0 deletions markup/examples/dynamic.rs
Original file line number Diff line number Diff line change
@@ -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 })
}
18 changes: 6 additions & 12 deletions markup/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: F,
pub struct DynRender<'a> {
f: Box<dyn Fn(&mut dyn std::fmt::Write) -> 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<F> Render for Template<F>
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<F> std::fmt::Display for Template<F>
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)
Expand Down

0 comments on commit 694f021

Please sign in to comment.