1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
//! Primary entry point for compiling and rendering templates.
use serde::Serialize;

#[cfg(feature = "fs")]
use std::ffi::OsStr;
#[cfg(feature = "fs")]
use std::path::Path;

use crate::{
    escape::{self, EscapeFn},
    helper::{HandlerRegistry, HelperRegistry},
    output::{Output, StringOutput},
    parser::{Parser, ParserOptions},
    template::{Template, Templates},
    Error, Result,
};

/// Registry is the entry point for compiling and rendering templates.
///
/// A template name is always required for error messages.
pub struct Registry<'reg> {
    helpers: HelperRegistry<'reg>,
    handlers: HandlerRegistry<'reg>,
    templates: Templates,
    escape: EscapeFn,
    strict: bool,
}

impl<'reg> Registry<'reg> {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self {
            helpers: HelperRegistry::new(),
            handlers: Default::default(),
            templates: Default::default(),
            escape: Box::new(escape::html),
            strict: false,
        }
    }

    /// Set the strict mode.
    pub fn set_strict(&mut self, strict: bool) {
        self.strict = strict
    }

    /// Get the strict mode.
    pub fn strict(&self) -> bool {
        self.strict
    }

    /// Set the escape function for rendering.
    pub fn set_escape(&mut self, escape: EscapeFn) {
        self.escape = escape;
    }

    /// The escape function to use for rendering.
    pub fn escape(&self) -> &EscapeFn {
        &self.escape
    }

    /// Helper registry.
    pub fn helpers(&self) -> &HelperRegistry<'reg> {
        &self.helpers
    }

    /// Mutable reference to the helper registry.
    pub fn helpers_mut(&mut self) -> &mut HelperRegistry<'reg> {
        &mut self.helpers
    }

    /// Event handler registry.
    pub fn handlers(&self) -> &HandlerRegistry<'reg> {
        &self.handlers
    }

    /// Mutable reference to the event handler registry.
    pub fn handlers_mut(&mut self) -> &mut HandlerRegistry<'reg> {
        &mut self.handlers
    }

    /// Templates collection.
    pub fn templates(&self) -> &Templates {
        &self.templates
    }

    /// Get a named template.
    pub fn get_template(&self, name: &str) -> Option<&Template> {
        self.templates.get(name)
    }

    /// Insert a named string template.
    pub fn insert<N, C>(&mut self, name: N, content: C) -> Result<()>
    where
        N: AsRef<str>,
        C: AsRef<str>,
    {
        let name = name.as_ref().to_owned();
        let template = self.compile(
            content.as_ref().to_owned(),
            ParserOptions::new(name.clone(), 0, 0),
        )?;
        self.templates.insert(name, template);
        Ok(())
    }

    /// Add a named template from a file.
    ///
    /// Requires the `fs` feature.
    #[cfg(feature = "fs")]
    pub fn add<P>(&mut self, name: String, file: P) -> Result<()>
    where
        P: AsRef<Path>,
    {
        let (_, content) = self.read(file)?;
        let template =
            self.compile(content, ParserOptions::new(name.clone(), 0, 0))?;
        self.templates.insert(name, template);
        Ok(())
    }

    /// Load a file and use the file path as the template name.
    ///
    /// Requires the `fs` feature.
    #[cfg(feature = "fs")]
    pub fn load<P: AsRef<Path>>(&mut self, file: P) -> Result<()> {
        let (name, content) = self.read(file)?;
        let template =
            self.compile(content, ParserOptions::new(name.clone(), 0, 0))?;
        self.templates.insert(name, template);
        Ok(())
    }

    /// Load all the files in a target directory that match the
    /// given extension.
    ///
    /// The generated name is the file stem; ie, the name of the file
    /// once the extension has been removed.
    ///
    /// Requires the `fs` feature.
    #[cfg(feature = "fs")]
    pub fn read_dir<P: AsRef<Path>>(
        &mut self,
        file: P,
        extension: &str,
    ) -> Result<()> {
        let ext = OsStr::new(extension);
        for entry in std::fs::read_dir(file.as_ref())? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                if let Some(extension) = path.extension() {
                    if extension == ext {
                        let name = path
                            .file_stem()
                            .unwrap()
                            .to_string_lossy()
                            .to_owned()
                            .to_string();
                        let (_, content) = self.read(path)?;
                        let template = self.compile(
                            content,
                            ParserOptions::new(name.clone(), 0, 0),
                        )?;
                        self.templates.insert(name, template);
                    }
                }
            }
        }
        Ok(())
    }

    #[cfg(feature = "fs")]
    fn read<P: AsRef<Path>>(
        &self,
        file: P,
    ) -> std::io::Result<(String, String)> {
        let path = file.as_ref();
        let name = path.to_string_lossy().to_owned().to_string();
        let content = std::fs::read_to_string(path)?;
        Ok((name, content))
    }

    /// Compile a string to a template.
    ///
    /// To compile a template and add it to this registry use [insert()](Registry#method.insert),
    /// [add()](Registry#method.add), [load()](Registry#method.load) or [read_dir()](Registry#method.read_dir).
    pub fn compile<'a, S>(
        &self,
        template: S,
        options: ParserOptions,
    ) -> Result<Template>
    where
        S: AsRef<str>,
    {
        Ok(Template::compile(template.as_ref().to_owned(), options)?)
    }

    /// Compile a string to a template using the given name.
    ///
    /// This is a convenience function for calling [compile()](Registry#method.compile)
    /// using parser options with the given name.
    pub fn parse<'a, S>(&self, name: &str, template: S) -> Result<Template>
    where
        S: AsRef<str>,
    {
        self.compile(template, ParserOptions::new(name.to_string(), 0, 0))
    }

    /// Lint a template.
    pub fn lint<S>(&self, name: &str, template: S) -> Result<Vec<Error>>
    where
        S: AsRef<str>,
    {
        let mut errors: Vec<Error> = Vec::new();
        let mut parser = Parser::new(
            template.as_ref(),
            ParserOptions::new(name.to_string(), 0, 0),
        );
        parser.set_errors(&mut errors);
        for _ in parser {}
        Ok(errors)
    }

    /// Render a template without registering it and return
    /// the result as a string.
    ///
    /// This function buffers the template nodes before rendering.
    pub fn once<T, S>(&self, name: &str, source: S, data: &T) -> Result<String>
    where
        T: Serialize,
        S: AsRef<str>,
    {
        let mut writer = StringOutput::new();
        let template = self.compile(
            source.as_ref(),
            ParserOptions::new(name.to_string(), 0, 0),
        )?;
        template.render(self, name, data, &mut writer)?;
        Ok(writer.into())
    }

    /*

    /// Stream a dynamic template and buffer the result to a string.
    ///
    /// Requires the `stream` feature.
    #[cfg(feature = "stream")]
    pub fn stream<T>(
        &self,
        name: &str,
        source: &str,
        data: &T,
    ) -> Result<String>
    where
        T: Serialize,
    {
        let mut writer = StringOutput::new();
        let options = ParserOptions::new(name.to_string());
        self.stream_to_write(name, source, data, &mut writer, options)?;
        Ok(writer.into())
    }

    /// Stream a dynamic template to a writer.
    ///
    /// Requires the `stream` feature.
    #[cfg(feature = "stream")]
    pub fn stream_to_write<T>(
        &self,
        name: &str,
        source: &str,
        data: &T,
        writer: &mut impl Output,
        options: ParserOptions,
    ) -> Result<()>
    where
        T: Serialize,
    {
        let mut buffer: Vec<Node<'_>> = Vec::new();
        let mut rc = Render::new(
            self.strict(),
            self.escape(),
            self.helpers(),
            self.templates(),
            source,
            data,
            Box::new(writer),
        )?;

        // FIXME: implement this, currently not working as we store the
        // FIXME: next and previous nodes in the renderer which means
        // FIXME: node is not living long enough for the renderer to
        // FIXME: do it's job.
        let parser = Parser::new(source, options);
        let hint: Option<TrimHint> = Default::default();
        for node in parser {
            let node = node?;
            //let node = buffer.last().unwrap();
            for event in node.iter().trim(hint) {
                println!("{:#?}", event.node);
                //rc.render_node(event.node, event.trim)?;
            }
            //buffer.push(node);
        }

        drop(buffer);

        Ok(())
    }
    */

    /// Render a named template and buffer the result to a string.
    ///
    /// The named template must exist in the templates collection.
    pub fn render<T>(&self, name: &str, data: &T) -> Result<String>
    where
        T: Serialize,
    {
        let mut writer = StringOutput::new();
        self.render_to_write(name, data, &mut writer)?;
        Ok(writer.into())
    }

    /// Render a compiled template without registering it and
    /// buffer the result to a string.
    pub fn render_template<'a, T>(
        &self,
        name: &str,
        template: &Template,
        data: &T,
    ) -> Result<String>
    where
        T: Serialize,
    {
        let mut writer = StringOutput::new();
        template.render(self, name, data, &mut writer)?;
        Ok(writer.into())
    }

    /// Render a named template to a writer.
    ///
    /// The named template must exist in the templates collection.
    pub fn render_to_write<T>(
        &self,
        name: &str,
        data: &T,
        writer: &mut impl Output,
    ) -> Result<()>
    where
        T: Serialize,
    {
        let tpl = self
            .templates
            .get(name)
            .ok_or_else(|| Error::TemplateNotFound(name.to_string()))?;
        tpl.render(self, name, data, writer)?;

        Ok(())
    }
}