diff options
author | larros <larserik.rosengren@gmail.com> | 2017-09-26 10:02:44 +0200 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2017-09-26 10:02:44 +0200 |
commit | df58dcb49db77b2c283db3c9a8a738bdff3a8e37 (patch) | |
tree | 0de4a117d1e97216381b8336a1cec826e894d075 /askama_shared/src/lib.rs | |
parent | 4e919e47539b5fa346f1cac323ab250558b834bc (diff) | |
download | askama-df58dcb49db77b2c283db3c9a8a738bdff3a8e37.tar.gz askama-df58dcb49db77b2c283db3c9a8a738bdff3a8e37.tar.bz2 askama-df58dcb49db77b2c283db3c9a8a738bdff3a8e37.zip |
Add support for importing template files with macros (#51)
* Fix review comments for macro imports
Diffstat (limited to '')
-rw-r--r-- | askama_shared/src/lib.rs | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/askama_shared/src/lib.rs b/askama_shared/src/lib.rs index 066faca..a7deaff 100644 --- a/askama_shared/src/lib.rs +++ b/askama_shared/src/lib.rs @@ -21,7 +21,11 @@ mod input; mod parser; use input::Print; +use parser::{Node, Macro}; +use std::borrow::Cow; +use std::collections::HashMap; +use std::path::Path; /// Takes a `syn::DeriveInput` and generates source code for it /// @@ -33,16 +37,53 @@ use input::Print; pub fn build_template(ast: &syn::DeriveInput) -> String { let data = input::TemplateInput::new(ast); let nodes = parser::parse(data.source.as_ref()); + let imports = Imports::new(&nodes, &data.path); + let imported = imports.parse(); if data.meta.print == Print::Ast || data.meta.print == Print::All { println!("{:?}", nodes); } - let code = generator::generate(&data, &nodes); + let code = generator::generate(&data, &nodes, &imported); if data.meta.print == Print::Code || data.meta.print == Print::All { println!("{}", code); } code } + +pub struct Imports<'a> { + pub sources: Vec<Cow<'a, str>> +} + +impl <'a> Imports<'a> { + pub fn new(parent_nodes: &'a [Node], parent_path: &'a Path) -> Imports<'a> { + let sources = parent_nodes.iter().filter_map(|n| { + match *n { + Node::Import(_, ref import_path) => { + let path = path::find_template_from_path(import_path, Some(parent_path)); + let src = path::get_template_source(&path); + Some(Cow::Owned(src)) + }, + _ => None, + } + }).collect(); + Imports { + sources, + } + } + + pub fn parse(&'a self) -> HashMap<&'a str, Macro<'a>> { + self.sources.iter() + .flat_map(|s| parser::parse(s.as_ref())) + .filter_map(|n| { + match n { + Node::Macro(name, m) => Some((name, m)), + _ => None, + }}) + .collect() + } +} + + mod errors { error_chain! { foreign_links { |