laravel_template_engine/lib.rs
1//! Templates for emails, documents and notifications that your team edits, stored in the
2//! database, for [Laravel Rust](https://crates.io/crates/laravel-rust).
3//!
4//! The code declares a template type, its variables and an example; everything else (the text,
5//! the subject, the sender, who gets the email, the language) lives in the database and is
6//! changed by people without a deploy:
7//!
8//! ```no_run
9//! use laravel_template_engine::{Recipient, TemplateData};
10//! use serde::Serialize;
11//!
12//! #[derive(Serialize, TemplateData)]
13//! #[template(key = "order.placed", description = "An order was placed", example = OrderPlaced::example)]
14//! pub struct OrderPlaced {
15//! #[template(description = "The customer")]
16//! pub customer: Recipient,
17//! #[template(description = "The order")]
18//! pub order: Order,
19//! }
20//!
21//! #[derive(Serialize, TemplateData)]
22//! pub struct Order {
23//! #[template(description = "Order number")]
24//! pub number: String,
25//! #[template(description = "Total")]
26//! pub total: f64,
27//! }
28//!
29//! impl OrderPlaced {
30//! fn example() -> Self {
31//! Self {
32//! customer: Recipient::new("olena@example.com").name("Olena").locale("uk"),
33//! order: Order { number: "1042".into(), total: 1250.0 },
34//! }
35//! }
36//! }
37//!
38//! # async fn place(order: OrderPlaced) -> laravel::Result<()> {
39//! laravel_template_engine::send(order).await?;
40//! # Ok(())
41//! # }
42//! ```
43//!
44//! Register [`TemplateEngineServiceProvider`] and run `laravel migrate`. See the README for a
45//! walkthrough.
46
47mod assets;
48mod commands;
49mod config;
50mod defaults;
51mod document;
52pub mod editor;
53mod error;
54pub mod events;
55mod filters;
56mod mail;
57mod notification;
58mod recipient;
59mod render;
60mod sandbox;
61mod schema;
62mod template;
63pub mod templates;
64pub mod transfer;
65mod validate;
66
67use std::sync::Arc;
68
69use laravel::config::{Config, Env};
70use laravel::container::Registrar;
71use laravel::foundation::ServiceProvider;
72
73pub use laravel_template_engine_macros::TemplateData;
74pub use minijinja::Value;
75
76pub use crate::assets::{Font, Image, Layout};
77pub use crate::config::TemplateEngineConfig;
78pub use crate::defaults::DefaultTemplate;
79pub use crate::document::{PendingDocument, document};
80pub use crate::error::TemplateError;
81pub use crate::mail::{MailAttachment, PendingTemplateMail, SendTemplateMail, mail, send};
82pub use crate::notification::{Channel, NotificationTexts, RenderedText, notification};
83pub use crate::recipient::Recipient;
84pub use crate::render::{Document, RenderedMail};
85pub use crate::sandbox::{Arg, ArgKind, Filter, FilterSpec, InputKind};
86pub use crate::schema::{Describe, Field, Node, TemplateType, TypeInfo, find_type, type_of, types};
87pub use crate::template::{
88 Content, DocumentFormat, DocumentSettings, Kind, MailSettings, Margins, NotificationSettings, Orientation,
89 Settings, Template, TemplateInput,
90};
91pub use crate::validate::Issue;
92
93use crate::assets::Assets;
94
95#[doc(hidden)]
96pub mod __private {
97 pub use crate::schema::Registration;
98 pub use inventory;
99}
100
101/// Adds the package's settings, its migration, its command and the application's filters.
102#[derive(Clone, Default)]
103pub struct TemplateEngineServiceProvider {
104 filters: Vec<Filter>,
105 images: Vec<Image>,
106 fonts: Vec<Font>,
107 layouts: Vec<Layout>,
108 channels: Vec<Channel>,
109}
110
111impl TemplateEngineServiceProvider {
112 /// The provider with the built-in filters only.
113 #[must_use]
114 pub fn new() -> Self {
115 Self::default()
116 }
117
118 /// Lets templates use `filter` too.
119 #[must_use]
120 pub fn filter(mut self, filter: Filter) -> Self {
121 self.filters.push(filter);
122 self
123 }
124
125 /// Lets templates show the picture `bytes` with `<img src="name">`: in PDFs, in HTML
126 /// documents, in previews, and in emails as an attached picture.
127 ///
128 /// ```no_run
129 /// # use laravel_template_engine::TemplateEngineServiceProvider;
130 /// # let logo: &[u8] = &[];
131 /// let provider = TemplateEngineServiceProvider::new().image("logo", logo);
132 /// ```
133 ///
134 /// # Panics
135 ///
136 /// When `name` has characters other than letters, digits, `.`, `-` and `_`, or `bytes`
137 /// aren't a PNG, JPEG or GIF.
138 #[must_use]
139 pub fn image(mut self, name: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
140 self.images.push(Image::new(name, bytes));
141 self
142 }
143
144 /// Adds a layout templates can choose: shared HTML, such as a header, a footer and styles,
145 /// with `{{ content }}` where a template's text goes. It also sees `subject` and `locale`.
146 ///
147 /// ```no_run
148 /// # use laravel_template_engine::TemplateEngineServiceProvider;
149 /// let provider = TemplateEngineServiceProvider::new().layout(
150 /// "brand",
151 /// r#"<style>h1 { color: #0a6 }</style><img src="logo">{{ content }}<p>Acme Ltd.</p>"#,
152 /// );
153 /// ```
154 ///
155 /// # Panics
156 ///
157 /// When `source` isn't a valid template or doesn't use `content`.
158 #[must_use]
159 pub fn layout(mut self, name: impl Into<String>, source: impl Into<String>) -> Self {
160 self.layouts.push(Layout::new(name, source));
161 self
162 }
163
164 /// Lets notification templates write for `name`, such as `telegram`, on top of Laravel's
165 /// `sms` and `slack`. `description` is what the editor shows.
166 #[must_use]
167 pub fn channel(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
168 self.channels.push(Channel {
169 name: name.into(),
170 description: description.into(),
171 });
172 self
173 }
174
175 /// Lets PDF documents use the TrueType or OpenType font `bytes` with `font-family: family`.
176 #[must_use]
177 pub fn font(mut self, family: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
178 self.fonts.push(Font {
179 family: family.into(),
180 bytes: Arc::new(bytes.into()),
181 });
182 self
183 }
184}
185
186laravel::db::migrations!(fn migrations = "database/migrations");
187
188impl ServiceProvider for TemplateEngineServiceProvider {
189 fn config(&self, config: &mut Config, env: &Env) {
190 config.discover(env!("CARGO_CRATE_NAME"), env);
191 }
192
193 fn register(&self, app: &mut Registrar) {
194 app.discover(env!("CARGO_CRATE_NAME"));
195 app.migrations().add(migrations());
196 app.instance(Assets {
197 filters: Arc::new(self.filters.clone()),
198 images: Arc::new(self.images.clone()),
199 fonts: Arc::new(self.fonts.clone()),
200 layouts: Arc::new(self.layouts.clone()),
201 channels: Arc::new(self.channels.clone()),
202 });
203 }
204}