minijinja 3.0.0-alpha.0

a powerful template engine for Rust with minimal dependencies
Documentation
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use std::cell::RefCell;
use std::collections::{BTreeMap, HashSet};
use std::ops::Deref;
use std::sync::Arc;
use std::{fmt, io};

use crate::vendor::self_cell::self_cell;

use crate::compiler::codegen::CodeGenerator;
use crate::compiler::instructions::Instructions;
use crate::compiler::lexer::WhitespaceConfig;
use crate::compiler::meta::find_undeclared;
use crate::compiler::parser::parse;
use crate::environment::Environment;
use crate::error::{attach_basic_debug_info, Error};
use crate::output::{Output, WriteWrapper};
use crate::syntax::SyntaxConfig;
use crate::utils::AutoEscape;
use crate::value::Value;
#[cfg(feature = "multi_template")]
use crate::vm::prepare_blocks;
use crate::vm::{self, Context, State};

/// Callback for auto escape determination
pub type AutoEscapeFunc = dyn Fn(&str) -> AutoEscape + Sync + Send;

/// Internal struct that holds template loading level config values.
#[derive(Clone)]
pub struct TemplateConfig {
    /// The syntax used for the template.
    pub syntax_config: SyntaxConfig,
    /// Controls whitespace behavior.
    pub ws_config: WhitespaceConfig,
    /// The callback that determines the initial auto escaping for templates.
    pub default_auto_escape: Arc<AutoEscapeFunc>,
}

impl TemplateConfig {
    pub(crate) fn new(default_auto_escape: Arc<AutoEscapeFunc>) -> TemplateConfig {
        TemplateConfig {
            syntax_config: SyntaxConfig::default(),
            ws_config: WhitespaceConfig::default(),
            default_auto_escape,
        }
    }
}

/// Represents a handle to a template.
///
/// Templates are stored in the [`Environment`] as bytecode instructions.  With the
/// [`Environment::get_template`] method that is looked up and returned in form of
/// this handle.  Such a template can be cheaply copied as it only holds references.
///
/// To render the [`render`](Template::render) method can be used.
#[derive(Clone)]
pub struct Template<'env: 'source, 'source> {
    env: &'env Environment<'env>,
    pub(crate) compiled: CompiledTemplateRef<'env, 'source>,
}

struct CapturedData<'state> {
    output: String,
    state: State<'state, 'state>,
}

self_cell! {
    struct CapturedCell<'source> {
        owner: Template<'source, 'source>,

        #[covariant]
        dependent: CapturedData,
    }
}

/// Represents a rendered template output together with a captured [`State`].
///
/// This type keeps the originating [`Template`] alive together with its
/// [`State`].  This is useful in situations where a temporary template handle
/// is used and a state needs to be inspected later (for instance to call
/// exported macros).
///
/// When created from [`render_captured`](Template::render_captured)
/// the [`output`](Self::output) contains the rendered string.  When created from
/// [`render_captured_to`](Template::render_captured_to) the output is
/// an empty string as the output was written to the provided writer.
pub struct Captured<'source> {
    cell: CapturedCell<'source>,
}

impl fmt::Debug for Captured<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Captured")
            .field("output", &self.output())
            .field("state", &self.state())
            .finish()
    }
}

impl<'source> Captured<'source> {
    /// Returns the rendered output.
    ///
    /// When created from [`render_captured_to`](Template::render_captured_to)
    /// this returns an empty string.
    pub fn output(&self) -> &str {
        self.cell.borrow_dependent().output.as_str()
    }

    /// Returns a reference to the captured state.
    pub fn state(&self) -> &State<'_, '_> {
        &self.cell.borrow_dependent().state
    }

    /// Invokes a closure with mutable access to the captured state.
    pub fn with_state_mut<R>(
        &mut self,
        f: impl for<'state> FnOnce(&mut State<'state, 'state>) -> R,
    ) -> R {
        self.cell
            .with_dependent_mut(|_, dependent| f(&mut dependent.state))
    }

    /// Consumes the capture and returns the rendered output string.
    ///
    /// When created from [`render_captured_to`](Template::render_captured_to)
    /// this returns an empty string.
    pub fn into_output(mut self) -> String {
        self.cell
            .with_dependent_mut(|_, dependent| std::mem::take(&mut dependent.output))
    }
}

impl fmt::Debug for Template<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut ds = f.debug_struct("Template");
        ds.field("name", &self.name());
        #[cfg(feature = "internal_debug")]
        {
            ds.field("instructions", &self.compiled.instructions);
            ds.field("blocks", &self.compiled.blocks);
        }
        ds.field("initial_auto_escape", &self.compiled.initial_auto_escape);
        ds.finish()
    }
}

impl<'env, 'source> Template<'env, 'source> {
    pub(crate) fn new(
        env: &'env Environment<'env>,
        compiled: CompiledTemplateRef<'env, 'source>,
    ) -> Template<'env, 'source> {
        Template { env, compiled }
    }

    /// Returns the name of the template.
    pub fn name(&self) -> &str {
        self.compiled.instructions.name()
    }

    /// Returns the source code of the template.
    pub fn source(&self) -> &str {
        self.compiled.instructions.source()
    }

    /// Renders the template into a string.
    ///
    /// The provided value is used as the initial context for the template.  It
    /// can be any object that implements `Into<Value>`.  The
    /// [`context!`](crate::context) macro can be used to create an ad-hoc context.
    /// Serde values can be passed explicitly with the
    /// `minijinja::value::Serde` wrapper.
    ///
    /// For very large contexts and to avoid the overhead of serialization of
    /// potentially unused values, you might consider using a dynamic
    /// [`Object`](crate::value::Object) as value.  For more
    /// information see [Map as Context](crate::value::Object#map-as-context).
    ///
    /// ```
    /// # use minijinja::{Environment, context};
    /// # let mut env = Environment::new();
    /// # env.add_template("hello", "Hello {{ name }}!").unwrap();
    /// let tmpl = env.get_template("hello").unwrap();
    /// println!("{}", tmpl.render(context!(name => "John")).unwrap());
    /// ```
    ///
    /// To render a single block use [`render_captured`](Self::render_captured)
    /// in combination with [`State::render_block`].
    ///
    pub fn render<V: Into<Value>>(&self, ctx: V) -> Result<String, Error> {
        self._render(ctx.into())
    }

    /// Like [`render`](Self::render) but also returns the evaluated [`State`]
    /// while keeping the template alive with the returned state.
    ///
    /// This is primarily useful when working with temporary template handles,
    /// as the resulting [`State`] can continue to be used through the returned
    /// wrapper.
    ///
    /// ```
    /// # use minijinja::{Environment, value::Value};
    /// let env = Environment::new();
    /// let rendered = env
    ///     .template_from_str("{% set x = 42 %}")
    ///     .unwrap()
    ///     .render_captured(())
    ///     .unwrap();
    /// assert_eq!(rendered.output(), "");
    /// assert_eq!(rendered.state().lookup("x"), Some(Value::from(42)));
    /// ```
    pub fn render_captured<V: Into<Value>>(&self, ctx: V) -> Result<Captured<'source>, Error> {
        self.clone()._capture_state(ctx.into())
    }

    /// Like [`render`](Self::render) but writes to an [`io::Write`] and keeps
    /// the template alive with the returned state.
    ///
    /// This is useful when working with temporary template handles and
    /// the state needs to be inspected afterwards.  The [`output`](Captured::output)
    /// of the returned [`Captured`] will be an empty string since the
    /// output was written to the provided writer.
    ///
    /// ```
    /// # use minijinja::{Environment, context};
    /// let env = Environment::new();
    /// let mut buf = Vec::new();
    /// let captured = env
    ///     .template_from_str("{% set x = 42 %}Hello!")
    ///     .unwrap()
    ///     .render_captured_to((), &mut buf)
    ///     .unwrap();
    /// assert_eq!(std::str::from_utf8(&buf).unwrap(), "Hello!");
    /// assert_eq!(captured.output(), "");
    /// ```
    pub fn render_captured_to<V: Into<Value>, W: io::Write>(
        &self,
        ctx: V,
        w: W,
    ) -> Result<Captured<'source>, Error> {
        let root = ctx.into();
        let w = std::cell::RefCell::new(WriteWrapper { w, err: None });
        self.clone()
            ._capture_state_with_output(root, &w)
            .map_err(|err| w.into_inner().take_err(err))
    }

    fn _render(&self, root: Value) -> Result<String, Error> {
        let mut rv = String::with_capacity(self.compiled.buffer_size_hint);
        self._eval(root, &mut Output::new(&mut rv)).map(|_| rv)
    }

    fn _capture_state(self, root: Value) -> Result<Captured<'source>, Error> {
        let this: Template<'source, 'source> = self;
        let cell = ok!(CapturedCell::try_new(
            this,
            move |template| -> Result<CapturedData<'_>, Error> {
                let mut output = String::with_capacity(template.compiled.buffer_size_hint);
                let (_, state) = ok!(template._eval(root, &mut Output::new(&mut output)));
                Ok(CapturedData { output, state })
            }
        ));
        Ok(Captured { cell })
    }

    fn _capture_state_with_output<W: io::Write>(
        self,
        root: Value,
        w: &RefCell<WriteWrapper<W>>,
    ) -> Result<Captured<'source>, Error> {
        let this: Template<'source, 'source> = self;
        let cell = ok!(CapturedCell::try_new(
            this,
            move |template| -> Result<CapturedData<'_>, Error> {
                let (_, state) = ok!(template._eval(root, &mut Output::new(&mut *w.borrow_mut())));
                Ok(CapturedData {
                    output: String::new(),
                    state,
                })
            }
        ));
        Ok(Captured { cell })
    }

    fn _eval(
        &self,
        root: Value,
        out: &mut Output,
    ) -> Result<(Option<Value>, State<'_, 'env>), Error> {
        vm::eval(
            self.env,
            &self.compiled.instructions,
            root,
            &self.compiled.blocks,
            out,
            self.compiled.initial_auto_escape,
        )
    }

    /// Returns a set of all undeclared variables in the template.
    ///
    /// This returns a set of all variables that might be looked up
    /// at runtime by the template.  Since this runs a static
    /// analysis, the actual control flow is not considered.  This
    /// also cannot take into account what happens due to includes,
    /// imports or extending.  If `nested` is set to `true`, then also
    /// nested trivial attribute lookups are considered and returned.
    ///
    /// ```rust
    /// # use minijinja::Environment;
    /// let mut env = Environment::new();
    /// env.add_template("x", "{% set x = foo %}{{ x }}{{ bar.baz }}").unwrap();
    /// let tmpl = env.get_template("x").unwrap();
    /// let undeclared = tmpl.undeclared_variables(false);
    /// // returns ["foo", "bar"]
    /// let undeclared = tmpl.undeclared_variables(true);
    /// // returns ["foo", "bar.baz"]
    /// ```
    ///
    /// Note that this does not special case global variables.  This means
    /// that for instance a template that uses `namespace()` will return
    /// `namespace` in the return value.
    pub fn undeclared_variables(&self, nested: bool) -> HashSet<String> {
        match parse(
            self.compiled.instructions.source(),
            self.name(),
            self.compiled.syntax_config.clone(),
            // TODO: this is not entirely great, but good enough for this use case.
            Default::default(),
        ) {
            Ok(ast) => find_undeclared(&ast, nested),
            Err(_) => HashSet::new(),
        }
    }

    /// Creates an empty [`State`] for this template.
    ///
    /// It's very rare that you need to actually do this but it can be useful when
    /// testing values or working with macros or other callable objects from outside
    /// the template environment.
    pub fn new_state(&self) -> State<'_, 'env> {
        State::new(
            Context::new(self.env),
            self.compiled.initial_auto_escape,
            &self.compiled.instructions,
            #[cfg(feature = "multi_template")]
            prepare_blocks(&self.compiled.blocks),
        )
    }

    /// Returns the instructions and blocks if the template is loaded from the
    /// environment.
    ///
    /// For templates loaded as string on the environment this API contract
    /// cannot be upheld because the template might not live long enough.  Under
    /// normal circumstances however such a template object would never make it
    /// to the callers of this API as this API is used for including or extending,
    /// both of which should only ever get access to a template from the environment
    /// which holds a borrowed ref.
    #[cfg(feature = "multi_template")]
    pub(crate) fn instructions_and_blocks(
        &self,
    ) -> Result<
        (
            &'env Instructions<'env>,
            &'env BTreeMap<&'env str, Instructions<'env>>,
        ),
        Error,
    > {
        match self.compiled {
            CompiledTemplateRef::Borrowed(x) => Ok((&x.instructions, &x.blocks)),
            CompiledTemplateRef::Owned(_) => Err(Error::new(
                crate::ErrorKind::InvalidOperation,
                "cannot extend or include template not borrowed from environment",
            )),
        }
    }

    /// Returns the initial auto escape setting.
    #[cfg(feature = "multi_template")]
    pub(crate) fn initial_auto_escape(&self) -> AutoEscape {
        self.compiled.initial_auto_escape
    }
}

#[derive(Clone)]
pub(crate) enum CompiledTemplateRef<'env: 'source, 'source> {
    Owned(Arc<CompiledTemplate<'source>>),
    Borrowed(&'env CompiledTemplate<'source>),
}

impl<'source> Deref for CompiledTemplateRef<'_, 'source> {
    type Target = CompiledTemplate<'source>;

    fn deref(&self) -> &Self::Target {
        match *self {
            CompiledTemplateRef::Owned(ref x) => x,
            CompiledTemplateRef::Borrowed(x) => x,
        }
    }
}

/// Represents a compiled template in memory.
pub struct CompiledTemplate<'source> {
    /// The root instructions.
    pub instructions: Instructions<'source>,
    /// Block local instructions.
    pub blocks: BTreeMap<&'source str, Instructions<'source>>,
    /// Optional size hint for string rendering.
    pub buffer_size_hint: usize,
    /// The syntax config that created it.
    pub syntax_config: SyntaxConfig,
    /// The initial setting of auto escaping.
    pub initial_auto_escape: AutoEscape,
}

impl fmt::Debug for CompiledTemplate<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut ds = f.debug_struct("CompiledTemplate");
        #[cfg(feature = "internal_debug")]
        {
            ds.field("instructions", &self.instructions);
            ds.field("blocks", &self.blocks);
        }
        ds.finish()
    }
}

impl<'source> CompiledTemplate<'source> {
    /// Creates a compiled template from name and source using the given settings.
    pub fn new(
        name: &'source str,
        source: &'source str,
        config: &TemplateConfig,
    ) -> Result<CompiledTemplate<'source>, Error> {
        attach_basic_debug_info(Self::_new_impl(name, source, config), source)
    }

    fn _new_impl(
        name: &'source str,
        source: &'source str,
        config: &TemplateConfig,
    ) -> Result<CompiledTemplate<'source>, Error> {
        let ast = ok!(parse(
            source,
            name,
            config.syntax_config.clone(),
            config.ws_config
        ));
        let mut g = CodeGenerator::new(name, source);
        g.compile_stmt(&ast);
        let buffer_size_hint = g.buffer_size_hint();
        let (instructions, blocks) = g.finish();
        Ok(CompiledTemplate {
            instructions,
            blocks,
            buffer_size_hint,
            syntax_config: config.syntax_config.clone(),
            initial_auto_escape: (config.default_auto_escape)(name),
        })
    }
}