Skip to main content

flm_core/stdlib/features/compose/
engines.rs

1//! The template engine that the feature `compose` contributes, [`ContentOnlyEngine`]
2//! (`content-only`).
3//!
4//! A template engine is the code that applies a compose template written in its language
5//! to what the compose template reads ([`TemplateEngine`]); a compose template refers to
6//! its template engine by name. A host contributes the engines of the template languages
7//! it reads.
8
9use std::sync::Arc;
10
11use super::{Template, TemplateContext, TemplateEngine, TemplateShipper};
12
13/// The name of [`ContentOnlyEngine`], `content-only`.
14pub const CONTENT_ONLY: &str = "content-only";
15
16/// The template engine `content-only`: it writes the pieces placed before the content, the
17/// content, and the pieces placed after it, each beginning on a line of its own, with
18/// nothing around them.
19///
20/// It reads no text of the compose template and ships no file. An empty part is left out, and a result that
21/// is not empty ends with a line break.
22#[derive(Debug, Default, Clone, Copy)]
23pub struct ContentOnlyEngine;
24
25impl TemplateEngine for ContentOnlyEngine {
26    fn name(&self) -> &str {
27        CONTENT_ONLY
28    }
29
30    fn render(
31        &self,
32        _template: &Template,
33        context: &TemplateContext,
34        _shipper: &Arc<dyn TemplateShipper>,
35    ) -> Result<String, String> {
36        fn at<'c>(context: &'c TemplateContext, place: &'static str) -> impl Iterator<Item = &'c str> + 'c {
37            context.pieces.iter().filter(move |piece| piece.place == place).map(|piece| piece.text.as_str())
38        }
39        let content = context
40            .regions
41            .iter()
42            .find(|(name, _)| name == crate::core::region::CONTENT)
43            .map(|(_, text)| text.as_str());
44        let parts: Vec<&str> = at(context, "before-content")
45            .chain(content)
46            .chain(at(context, "after-content"))
47            .filter(|part| !part.is_empty())
48            .collect();
49        let mut out = String::new();
50        for part in parts {
51            if !out.is_empty() && !out.ends_with('\n') {
52                out.push('\n');
53            }
54            out.push_str(part);
55        }
56        if !out.is_empty() && !out.ends_with('\n') {
57            out.push('\n');
58        }
59        Ok(out)
60    }
61}