laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! Templates for emails, documents and notifications that your team edits, stored in the
//! database, for [Laravel Rust](https://crates.io/crates/laravel-rust).
//!
//! The code declares a template type, its variables and an example; everything else (the text,
//! the subject, the sender, who gets the email, the language) lives in the database and is
//! changed by people without a deploy:
//!
//! ```no_run
//! use laravel_template_engine::{Recipient, TemplateData};
//! use serde::Serialize;
//!
//! #[derive(Serialize, TemplateData)]
//! #[template(key = "order.placed", description = "An order was placed", example = OrderPlaced::example)]
//! pub struct OrderPlaced {
//!     #[template(description = "The customer")]
//!     pub customer: Recipient,
//!     #[template(description = "The order")]
//!     pub order: Order,
//! }
//!
//! #[derive(Serialize, TemplateData)]
//! pub struct Order {
//!     #[template(description = "Order number")]
//!     pub number: String,
//!     #[template(description = "Total")]
//!     pub total: f64,
//! }
//!
//! impl OrderPlaced {
//!     fn example() -> Self {
//!         Self {
//!             customer: Recipient::new("olena@example.com").name("Olena").locale("uk"),
//!             order: Order { number: "1042".into(), total: 1250.0 },
//!         }
//!     }
//! }
//!
//! # async fn place(order: OrderPlaced) -> laravel::Result<()> {
//! laravel_template_engine::send(order).await?;
//! # Ok(())
//! # }
//! ```
//!
//! Register [`TemplateEngineServiceProvider`] and run `laravel migrate`. See the README for a
//! walkthrough.

mod assets;
mod commands;
mod config;
mod defaults;
mod document;
pub mod editor;
mod error;
pub mod events;
mod filters;
mod mail;
mod notification;
mod recipient;
mod render;
mod sandbox;
mod schema;
mod template;
pub mod templates;
pub mod transfer;
mod validate;

use std::sync::Arc;

use laravel::config::{Config, Env};
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

pub use laravel_template_engine_macros::TemplateData;
pub use minijinja::Value;

pub use crate::assets::{Font, Image, Layout};
pub use crate::config::TemplateEngineConfig;
pub use crate::defaults::DefaultTemplate;
pub use crate::document::{PendingDocument, document};
pub use crate::error::TemplateError;
pub use crate::mail::{MailAttachment, PendingTemplateMail, SendTemplateMail, mail, send};
pub use crate::notification::{Channel, NotificationTexts, RenderedText, notification};
pub use crate::recipient::Recipient;
pub use crate::render::{Document, RenderedMail};
pub use crate::sandbox::{Arg, ArgKind, Filter, FilterSpec, InputKind};
pub use crate::schema::{Describe, Field, Node, TemplateType, TypeInfo, find_type, type_of, types};
pub use crate::template::{
    Content, DocumentFormat, DocumentSettings, Kind, MailSettings, Margins, NotificationSettings, Orientation,
    Settings, Template, TemplateInput,
};
pub use crate::validate::Issue;

use crate::assets::Assets;

#[doc(hidden)]
pub mod __private {
    pub use crate::schema::Registration;
    pub use inventory;
}

/// Adds the package's settings, its migration, its command and the application's filters.
#[derive(Clone, Default)]
pub struct TemplateEngineServiceProvider {
    filters: Vec<Filter>,
    images: Vec<Image>,
    fonts: Vec<Font>,
    layouts: Vec<Layout>,
    channels: Vec<Channel>,
}

impl TemplateEngineServiceProvider {
    /// The provider with the built-in filters only.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Lets templates use `filter` too.
    #[must_use]
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Lets templates show the picture `bytes` with `<img src="name">`: in PDFs, in HTML
    /// documents, in previews, and in emails as an attached picture.
    ///
    /// ```no_run
    /// # use laravel_template_engine::TemplateEngineServiceProvider;
    /// # let logo: &[u8] = &[];
    /// let provider = TemplateEngineServiceProvider::new().image("logo", logo);
    /// ```
    ///
    /// # Panics
    ///
    /// When `name` has characters other than letters, digits, `.`, `-` and `_`, or `bytes`
    /// aren't a PNG, JPEG or GIF.
    #[must_use]
    pub fn image(mut self, name: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
        self.images.push(Image::new(name, bytes));
        self
    }

    /// Adds a layout templates can choose: shared HTML, such as a header, a footer and styles,
    /// with `{{ content }}` where a template's text goes. It also sees `subject` and `locale`.
    ///
    /// ```no_run
    /// # use laravel_template_engine::TemplateEngineServiceProvider;
    /// let provider = TemplateEngineServiceProvider::new().layout(
    ///     "brand",
    ///     r#"<style>h1 { color: #0a6 }</style><img src="logo">{{ content }}<p>Acme Ltd.</p>"#,
    /// );
    /// ```
    ///
    /// # Panics
    ///
    /// When `source` isn't a valid template or doesn't use `content`.
    #[must_use]
    pub fn layout(mut self, name: impl Into<String>, source: impl Into<String>) -> Self {
        self.layouts.push(Layout::new(name, source));
        self
    }

    /// Lets notification templates write for `name`, such as `telegram`, on top of Laravel's
    /// `sms` and `slack`. `description` is what the editor shows.
    #[must_use]
    pub fn channel(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
        self.channels.push(Channel {
            name: name.into(),
            description: description.into(),
        });
        self
    }

    /// Lets PDF documents use the TrueType or OpenType font `bytes` with `font-family: family`.
    #[must_use]
    pub fn font(mut self, family: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
        self.fonts.push(Font {
            family: family.into(),
            bytes: Arc::new(bytes.into()),
        });
        self
    }
}

laravel::db::migrations!(fn migrations = "database/migrations");

impl ServiceProvider for TemplateEngineServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    fn register(&self, app: &mut Registrar) {
        app.discover(env!("CARGO_CRATE_NAME"));
        app.migrations().add(migrations());
        app.instance(Assets {
            filters: Arc::new(self.filters.clone()),
            images: Arc::new(self.images.clone()),
            fonts: Arc::new(self.fonts.clone()),
            layouts: Arc::new(self.layouts.clone()),
            channels: Arc::new(self.channels.clone()),
        });
    }
}