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
//! The Liquid templating language for Rust //! //! __http://liquidmarkup.org/__ //! //! ```toml //! [dependencies] //! liquid = "0.9" //! ``` //! //! ## Example //! ```rust //! use liquid::{Renderable, Context, Value}; //! //! let template = liquid::parse("Liquid! {{num | minus: 2}}", Default::default()).unwrap(); //! //! let mut context = Context::new(); //! context.set_val("num", Value::Num(4f32)); //! //! let output = template.render(&mut context); //! assert_eq!(output.unwrap(), Some("Liquid! 2".to_string())); //! ``` #![crate_name = "liquid"] #![doc(html_root_url = "https://cobalt-org.github.io/liquid-rust/")] // Deny warnings, except in dev mode #![deny(warnings)] // #![deny(missing_docs)] #![cfg_attr(feature="dev", warn(warnings))] #[macro_use] extern crate lazy_static; extern crate regex; extern crate chrono; use std::collections::HashMap; use lexer::Element; use tags::{assign_tag, cycle_tag, include_tag, break_tag, continue_tag, comment_block, raw_block, for_block, if_block, unless_block, capture_block, case_block}; use std::default::Default; use std::fs::File; use std::io::prelude::Read; use std::path::{PathBuf, Path}; use error::Result; pub use value::Value; pub use context::Context; pub use template::Template; pub use error::Error; pub use filters::FilterError; pub use token::Token; pub mod lexer; pub mod parser; mod token; mod error; mod template; mod output; mod text; mod tags; mod filters; mod value; mod variable; mod context; /// A trait for creating custom tags. This is a simple type alias for a function. /// /// This function will be called whenever the parser encounters a tag and returns /// a new [Renderable](trait.Renderable.html) based on its parameters. The received parameters /// specify the name of the tag, the argument [Tokens](lexer/enum.Token.html) passed to /// the tag and the global [`LiquidOptions`](struct.LiquidOptions.html). /// /// ## Minimal Example /// ``` /// # use liquid::{Renderable, LiquidOptions, Context, Error}; /// /// struct HelloWorld; /// /// impl Renderable for HelloWorld { /// fn render(&self, _context: &mut Context) -> Result<Option<String>, Error>{ /// Ok(Some("Hello World!".to_owned())) /// } /// } /// /// let mut options : LiquidOptions = Default::default(); /// options.tags.insert("hello_world".to_owned(), Box::new(|_tag_name, _arguments, _options| { /// Ok(Box::new(HelloWorld)) /// })); /// /// let template = liquid::parse("{{hello_world}}", options).unwrap(); /// let mut data = Context::new(); /// let output = template.render(&mut data); /// assert_eq!(output.unwrap(), Some("Hello World!".to_owned())); /// ``` pub type Tag = Fn(&str, &[Token], &LiquidOptions) -> Result<Box<Renderable>>; /// A trait for creating custom custom block-size tags (`{% if something %}{% endif %}`). /// This is a simple type alias for a function. /// /// This function will be called whenever the parser encounters a block and returns /// a new `Renderable` based on its parameters. The received parameters specify the name /// of the block, the argument [Tokens](lexer/enum.Token.html) passed to /// the block, a Vec of all [Elements](lexer/enum.Element.html) inside the block and /// the global [`LiquidOptions`](struct.LiquidOptions.html). pub type Block = Fn(&str, &[Token], Vec<Element>, &LiquidOptions) -> Result<Box<Renderable>>; /// Any object (tag/block) that can be rendered by liquid must implement this trait. pub trait Renderable: Send + Sync { /// Renders the Renderable instance given a Liquid context. /// The Result that is returned signals if there was an error rendering, /// the Option<String> that is wrapped by the Result will be None if /// the render has run successfully but there is no content to render. fn render(&self, context: &mut Context) -> Result<Option<String>>; } /// Options that `liquid::parse` takes #[derive(Default)] pub struct LiquidOptions { /// Holds all custom block-size tags pub blocks: HashMap<String, Box<Block>>, /// Holds all custom tags pub tags: HashMap<String, Box<Tag>>, /// The path to which paths in include tags should be relative to pub file_system: Option<PathBuf>, } impl LiquidOptions { /// Creates a LiquidOptions instance, pre-seeded with all known /// tags and blocks. pub fn with_known_blocks() -> LiquidOptions { let mut options = LiquidOptions::default(); options.register_known_blocks(); options } /// Registers all known tags and blocks in an existing options /// struct pub fn register_known_blocks(&mut self) { self.register_tag("assign", Box::new(assign_tag)); self.register_tag("break", Box::new(break_tag)); self.register_tag("continue", Box::new(continue_tag)); self.register_tag("cycle", Box::new(cycle_tag)); self.register_tag("include", Box::new(include_tag)); self.register_block("raw", Box::new(raw_block)); self.register_block("if", Box::new(if_block)); self.register_block("unless", Box::new(unless_block)); self.register_block("for", Box::new(for_block)); self.register_block("comment", Box::new(comment_block)); self.register_block("capture", Box::new(capture_block)); self.register_block("case", Box::new(case_block)); } /// Inserts a new custom block into the options object pub fn register_block(&mut self, name: &str, block: Box<Block>) { self.blocks.insert(name.to_owned(), block); } /// Inserts a new custom tag into the options object pub fn register_tag(&mut self, name: &str, tag: Box<Tag>) { self.tags.insert(name.to_owned(), tag); } } /// Parses a liquid template, returning a Template object. /// # Examples /// /// ## Minimal Template /// /// ``` /// use liquid::{Renderable, LiquidOptions, Context}; /// /// let template = liquid::parse("Liquid!", LiquidOptions::default()).unwrap(); /// let mut data = Context::new(); /// let output = template.render(&mut data); /// assert_eq!(output.unwrap(), Some("Liquid!".to_owned())); /// ``` /// pub fn parse(text: &str, options: LiquidOptions) -> Result<Template> { let mut options = options; options.register_known_blocks(); let tokens = try!(lexer::tokenize(&text)); parser::parse(&tokens, &options).map(Template::new) } /// Parse a liquid template from a file, returning a `Result<Template, Error>`. /// # Examples /// /// ## Minimal Template /// /// `template.txt`: /// /// ```text /// "Liquid {{data}}" /// ``` /// /// Your rust code: /// /// ```rust,no_run /// use liquid::{Renderable, LiquidOptions, Context, Value}; /// /// let template = liquid::parse_file("path/to/template.txt", /// LiquidOptions::default()).unwrap(); /// let mut data = Context::new(); /// data.set_val("data", Value::Num(4f32)); /// let output = template.render(&mut data); /// assert_eq!(output.unwrap(), Some("Liquid 4\n".to_string())); /// ``` /// pub fn parse_file<P: AsRef<Path>>(fp: P, options: LiquidOptions) -> Result<Template> { let mut options = options; options.register_known_blocks(); let mut f = try!(File::open(fp)); let mut buf = String::new(); try!(f.read_to_string(&mut buf)); let tokens = try!(lexer::tokenize(&buf)); parser::parse(&tokens, &options).map(Template::new) }