123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- use comrak::{markdown_to_html, ComrakOptions};
-
- use post::Post;
-
- pub fn render_post(layout: &str, post_template: &str, post: &Post) -> String {
- layout.replace(
- "{{ contents }}",
- &post_template.replace("{{ title }}", &post.title).replace(
- "{{ body }}",
- &markdown_to_html(&post.body, &ComrakOptions::default()),
- ),
- )
- }
-
- pub fn render_post_listing(
- layout: &str,
- post_listing_template: &str,
- post_item_template: &str,
- posts: &Vec<Post>,
- ) -> String {
- layout.replace(
- "{{ contents }}",
- &post_listing_template.replace(
- "{{ post_listing }}",
- &posts
- .iter()
- .map(|ref post| {
- post_item_template
- .replace("{{ slug }}", &post.slug)
- .replace("{{ title }}", &post.title)
- }).collect::<Vec<String>>()
- .join("\n"),
- ),
- )
- }
-
- #[cfg(test)]
- mod tests {
- #[allow(unused_imports)]
- use super::{render_post, render_post_listing, Post};
-
- #[test]
- fn test_render_post() {
- let output = render_post(
- "<html><head><title>Test</title></head><body>{{ contents }}</body></html>",
- "<article><h1>{{ title }}</h1><div>{{ body }}</div></article>",
- &Post {
- title: String::from("hello world"),
- body: String::from("lorem ipsum dolor sit amet"),
- slug: String::from("hello-world"),
- },
- ).replace("\n", "");
-
- assert_eq!(
- "<html><head><title>Test</title></head><body><article><h1>hello wo\
- rld</h1><div><p>lorem ipsum dolor sit amet</p></div></article></b\
- ody></html>",
- &output,
- );
- }
-
- #[test]
- fn test_render_post_listing() {
- let posts = vec![
- Post {
- title: String::from("First post"),
- body: String::from("lorem ipsum dolor sit amet"),
- slug: String::from("first-post"),
- },
- Post {
- title: String::from("Second post"),
- body: String::from("lorem ipsum dolor sit amet"),
- slug: String::from("second-post"),
- },
- Post {
- title: String::from("Third post"),
- body: String::from("lorem ipsum dolor sit amet"),
- slug: String::from("third-post"),
- },
- ];
- let output = render_post_listing(
- "<html><head><title>Test</title></head><body>{{ contents }}</body></html>",
- "<ul>{{ post_listing }}</ul>",
- "<li><a href=\"/{{ slug }}\">{{ title }}</a></li>",
- &posts,
- ).replace("\n", "");
-
- assert_eq!(
- "<html><head><title>Test</title></head><body><ul><li><a href=\"/fir\
- st-post\">First post</a></li><li><a href=\"/second-post\">Second po\
- st</a></li><li><a href=\"/third-post\">Third post</a></li></ul></bo\
- dy></html>",
- &output,
- );
- }
- }
|