feat(quick-261115-cha): let a mail template use another plugin's layout by full code

- resolveLayoutLocked: after the plugin's own alias and the built-in
  aliases, a full layout name already in the catalog resolves to itself;
  an unregistered full name fails with a require-the-owner hint
- another plugin's short alias and the short-alias error are unchanged
- TestCrossPluginLayout covers register, send, errors and precedence
- postcard README and docs/services/mail.md describe the rule
This commit is contained in:
Jakub Zych
2026-11-15 09:08:21 +01:00
parent 42ab223e79
commit 1fb4254291
5 changed files with 214 additions and 7 deletions

View File

@@ -10,9 +10,9 @@ WinterCMS plugins ship mail templates in `views/mail` and send them with `Mail::
## Templates and layouts
A plugin implements `pact.HasMailTemplates`: it returns its embedded `views/mail` files, the template names it ships and short aliases for its layouts. A template named `acme.blog::mail.welcome` lives in `views/mail/welcome.htm` (dots in the name become directories), and a plugin may only register names in its own namespace. A missing file, a duplicate name or an unknown layout alias fails the start-up.
A plugin implements `pact.HasMailTemplates`: it returns its embedded `views/mail` files, the template names it ships and short aliases for its layouts. A template named `acme.blog::mail.welcome` lives in `views/mail/welcome.htm` (dots in the name become directories), and a plugin may only register names in its own namespace. A missing file, a duplicate name or a layout the template names that is not registered fails the start-up.
The file format is WinterCMS's: an INI header with the `subject`, the `layout` alias and a `description`, a `==` line, then a Markdown body with Go template variables such as `{{ .name }}`. A layout has a header, a text wrapper and an HTML wrapper, separated by `==` lines, each with `{{ .Content }}` where the message goes. A template without a `layout` uses the built-in `default` layout; see [Built-in layouts](#built-in-layouts).
The file format is WinterCMS's: an INI header with the `subject`, the `layout` (an alias or a full layout name) and a `description`, a `==` line, then a Markdown body with Go template variables such as `{{ .name }}`. A layout has a header, a text wrapper and an HTML wrapper, separated by `==` lines, each with `{{ .Content }}` where the message goes. A template without a `layout` uses the built-in `default` layout; see [Built-in layouts](#built-in-layouts).
Each message gets an HTML part, rendered from the Markdown, and a plain-text part. `mail.css` and the brand CSS go into the layout's style block; see [Branding](#branding).
@@ -71,6 +71,19 @@ A plugin's own alias wins over `system` and `minimal`; `default` cannot be redef
Every layout gets these values besides `{{ .Content }}`: `{{ .Subject }}`, the CSS slots `{{ .brandCss }}` and `{{ .css }}`, `{{ .logoUrl }}` (see [Branding](#branding)), `{{ .siteName }}`, the site name, and `{{ .year }}`, the current year. The default and system layouts use the `header` and `footer` partials with them; the footer reads `© <year> <site name>`, or `© <year>` when there is no name, passed as the footer's `text`, so the site name is printed as typed, never as Markdown, and the header row is left out when there is neither a logo nor a name.
### Another plugin's layout
A template can use a layout another plugin ships by naming its full name. Here a template of `acme.shop` uses the layout of `acme.blog`:
```text
subject = "Your order"
layout = "acme.blog::mail.layouts.blog"
==
Thanks for your order.
```
The plugin that owns the layout must be registered first: list it in the template plugin's `Requires()`, and it boots first. A full name that no registered plugin declares fails the start-up with `postcard: unknown layout`, naming the layout and the template. Another plugin's short alias does not work (`layout = "blog"` in `acme.shop` is an unknown layout); only its full name does. The layout picker in the admin already lists every layout, so a customized template can keep the borrowed layout or change it, and a customized version of the owner's layout applies to every template that uses it.
## Branding
A layout's style block has a brand slot, `{{ .brandCss }}`, before `{{ .css }}`. Until the branding settings are saved for the first time, the brand slot holds `mail.brandCss` from the configuration. From the first save on, it holds CSS that postcard compiles from the saved colours, and `mail.brandCss` is no longer used. `mail.css` is applied either way.

View File

@@ -22,9 +22,9 @@ Use cases:
## Features
- Templates named `<plugin>::mail.<name>` and loaded from `views/mail/<name>.htm` (dots become directories). A plugin may only register names in its own namespace; missing files, duplicates and unknown layout aliases fail at boot.
- Templates named `<plugin>::mail.<name>` and loaded from `views/mail/<name>.htm` (dots become directories). A plugin may only register names in its own namespace; missing files, duplicates and unknown layouts fail at boot.
- WinterCMS file format: an INI header (`subject`, `layout`, `description`), a `==` separator, then a Markdown body rendered with Go `html/template` variables such as `{{ .name }}`.
- Layouts with a header, a text wrapper and an HTML wrapper, referenced from templates by a short alias (`pact.HasMailTemplates` maps aliases to full names). Three layouts are built in and usable from any plugin's templates: `default`, `system` and `minimal`.
- Layouts with a header, a text wrapper and an HTML wrapper, referenced from templates by a short alias (`pact.HasMailTemplates` maps aliases to full names). Three layouts are built in and usable from any plugin's templates: `default`, `system` and `minimal`. A template may also name a layout another plugin registered by its full name.
- Partials: reusable blocks named `<plugin>::mail.partials.<name>`, loaded from `views/mail/partials/<name>.htm` and declared through `pact.HasMailPartials`. Bodies and layouts call them with `{{ partial "<name>" "key" value }}`. The partials `button`, `panel`, `table` and `subcopy` are built in.
- Every message gets an HTML part (Markdown converted with goldmark) and a plain-text part. The brand CSS (`mail.brandCss`, or the saved Branding) and `mail.css` go into the layout's style block, and the rendered HTML is then inlined: each CSS rule is copied into the `style` attribute of the elements it matches (go-premailer), so mail clients that drop style blocks still show the design. A layout opts out with `disable_auto_inline_css`.
- Safety checks: rendered HTML with script, iframe, object or embed tags, inline event handlers (any attribute whose name starts with `on`) or `javascript:`/`vbscript:`/`data:` URLs is rejected. Schemes are looked for in URL-bearing attributes, `style` attributes, style elements, comments and `meta` content, after character references are decoded and whitespace and control characters removed (`javascript&#58;` and `java&#9;script:` are `javascript:`). The content of `noscript`, `title`, `textarea`, `style`, `xmp` and the other raw-text elements, and of comments, is checked as markup too, because a mail client may read it so (scripting off, `svg` content, Outlook conditional comments); such elements nested more than eight deep are refused. Every tag is also read with attribute quoting alone deciding where it ends, so an end tag or `-->` inside a quoted attribute (`<a title="</style>" href="javascript:...">`) does not hide the rest of the tag. Text is neither markup nor a URL: it is not checked for schemes, and text shaped like an event handler (`buy one = get one free`, `online = yes`) is sent. CR/LF in the subject or address headers is rejected; addresses are parsed with `net/mail`.
@@ -181,6 +181,15 @@ Markdown drops raw HTML, so a call in a body does not insert the partial's HTML
A template selects one with `layout = "system"`. A plugin's own alias of the same name wins, except `default`, which plugins cannot redefine. Every built-in layout has the `{{ .brandCss }}{{ .css }}` style block.
A template's `layout` value is resolved in this order: empty or `default` is the default layout; then the plugin's own alias; then a built-in alias; then the full name of any layout already registered, another plugin's or a built-in one (`postcard::mail.layouts.minimal`). Another plugin's short alias is not visible. A full name must belong to a plugin that is already registered: list the owner in `Requires()`, and party boots it first. Otherwise start-up fails with `postcard: unknown layout`, naming the layout and the template. A template of `acme.shop`, which requires `acme.blog`, uses the blog's layout like this:
```text
subject = "Your order"
layout = "acme.blog::mail.layouts.blog"
==
Thanks for your order.
```
### CSS inlining
After a layout's HTML wrapper has rendered and passed the safety checks, postcard inlines it, as WinterCMS's `MailManager` does with CssToInlineStyles: `github.com/vanng822/go-premailer` with its default options reads the rules of every style element, writes them into the `style` attributes of the matching elements by specificity, mirrors CSS `width` and `height` to the attributes of the same name, keeps `class` attributes, and puts the rules it cannot inline (media queries, pseudo-classes such as `:hover`, selectors with `*`) back in one style element, marked `!important`. The safety checks run on the decoded markup before inlining, whether or not the layout opts out, so CSS in a style element with a `javascript:`, `vbscript:` or `data:` address is refused there. The inlined HTML is checked again, and an inlined result that fails the check is sent as its style-block version, with the same warning as an inliner error. HTML with no style element is left as it is. Preview, test send and sends run the same code; the text part is never changed.
@@ -396,7 +405,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `postcard.Options` | Mailer settings: sender address, CSS, brand CSS and, in `postcard.Options.Overrides`, the source of database overrides (nil sends the file versions). |
| `postcard.Catalog` | Registered templates, layouts and partials, including the built-in ones. |
| `postcard.NewCatalog` | Returns a catalog holding the built-in layouts and partials and no template. |
| `postcard.Catalog.Register` | Loads a plugin's templates and layout aliases from an `fs.FS`. |
| `postcard.Catalog.Register` | Loads a plugin's templates and layout aliases from an `fs.FS`. A template's `layout` may be one of the plugin's aliases, a built-in alias, or the full name of a layout already in the catalog. |
| `postcard.Catalog.RegisterPartials` | Loads a plugin's partials from an `fs.FS`. |
| `postcard.Driver` | Delivers a `postcard.RenderedMessage`. |
| `postcard.RenderedMessage` | The validated payload a driver transmits: headers, HTML part and text part. |

View File

@@ -0,0 +1,170 @@
package postcard
import (
"strings"
"testing"
"testing/fstest"
)
// Cross-plugin layout fixtures: acme.lender owns the card layout, and
// acme.borrower (which ships no layouts) points its templates at it by full
// code.
const (
lenderID = "acme.lender"
borrowerID = "acme.borrower"
lenderCardLayout = "acme.lender::mail.layouts.card"
lenderNotice = "acme.lender::mail.notice"
borrowerCode = "acme.borrower::mail.code"
borrowerCodeEn = "acme.borrower::mail.code-en"
borrowerPlain = "acme.borrower::mail.plain"
lenderCardHTML = `<div class="lender-card">`
lenderCardFooter = "-- Lender card"
)
func lenderFS() fstest.MapFS {
return fstest.MapFS{
"views/mail/layouts/card.htm": {Data: []byte("name = \"Card\"\n==\n{{ .Content }}\n\n" + lenderCardFooter + "\n==\n" + lenderCardHTML + "{{ .Content }}</div>\n")},
"views/mail/notice.htm": {Data: []byte("subject = \"Notice\"\nlayout = \"card\"\n==\nA notice.\n")},
}
}
// borrowerFS returns the borrower's code templates with the given header
// lines (for example a layout key) and a plain template with no layout key.
func borrowerFS(header string) fstest.MapFS {
code := []byte("subject = \"Code {{ .code }}\"\n" + header + "==\nYour code is **{{ .code }}**.\n")
return fstest.MapFS{
"views/mail/code.htm": {Data: code},
"views/mail/code-en.htm": {Data: code},
"views/mail/plain.htm": {Data: []byte("subject = \"Plain\"\n==\nPlain body.\n")},
}
}
func registerLender(t *testing.T, cat *Catalog) {
t.Helper()
if err := cat.Register(lenderID, lenderFS(), []string{lenderNotice}, map[string]string{"card": lenderCardLayout}); err != nil {
t.Fatalf("Register lender: %v", err)
}
}
func registerBorrower(cat *Catalog, header string) error {
return cat.Register(borrowerID, borrowerFS(header), []string{borrowerCode, borrowerCodeEn, borrowerPlain}, nil)
}
// borrowerCatalog is a catalog with the lender registered, then the borrower
// whose code templates use the lender's card layout by full code.
func borrowerCatalog(t *testing.T) *Catalog {
t.Helper()
cat := NewCatalog()
registerLender(t, cat)
if err := registerBorrower(cat, "layout = \""+lenderCardLayout+"\"\n"); err != nil {
t.Fatalf("Register borrower: %v", err)
}
return cat
}
func templateLayout(t *testing.T, cat *Catalog, name string) string {
t.Helper()
tf, ok := cat.Template(name)
if !ok {
t.Fatalf("Template(%s) not found", name)
}
return tf.Layout
}
// TestCrossPluginLayout covers a template naming another plugin's layout by
// its full code: registration, the send, the boot errors and the unchanged
// alias precedence.
func TestCrossPluginLayout(t *testing.T) {
t.Parallel()
t.Run("file_layout_by_full_code", func(t *testing.T) {
t.Parallel()
cat := borrowerCatalog(t)
for _, name := range []string{borrowerCode, borrowerCodeEn} {
if got := templateLayout(t, cat, name); got != lenderCardLayout {
t.Errorf("%s Layout = %q, want %q", name, got, lenderCardLayout)
}
drv := NewMemoryDriver()
m := NewMailer(cat, drv, Options{})
msg := sendTemplate(t, m, drv, name, map[string]any{"code": "123456"})
i := strings.Index(msg.HTML, lenderCardHTML)
if i < 0 {
t.Fatalf("%s HTML has no lender card:\n%s", name, msg.HTML)
}
if !strings.Contains(msg.HTML[i:], "<strong>123456</strong>") {
t.Errorf("%s HTML has no strong code inside the card:\n%s", name, msg.HTML)
}
if !strings.Contains(msg.Text, lenderCardFooter) {
t.Errorf("%s Text has no lender footer:\n%s", name, msg.Text)
}
if msg.Subject != "Code 123456" {
t.Errorf("%s Subject = %q", name, msg.Subject)
}
}
})
t.Run("owner_registers_later", func(t *testing.T) {
t.Parallel()
err := registerBorrower(NewCatalog(), "layout = \""+lenderCardLayout+"\"\n")
if err == nil {
t.Fatal("Register borrower without the lender succeeded")
}
for _, want := range []string{"unknown layout " + lenderCardLayout, borrowerCode, "required"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q does not contain %q", err, want)
}
}
if !strings.HasPrefix(err.Error(), "postcard: unknown layout "+lenderCardLayout) {
t.Errorf("error %q does not start with the unknown layout prefix", err)
}
})
t.Run("unknown_full_code", func(t *testing.T) {
t.Parallel()
cat := NewCatalog()
registerLender(t, cat)
err := registerBorrower(cat, "layout = \"acme.lender::mail.layouts.nope\"\n")
if err == nil || !strings.Contains(err.Error(), "unknown layout acme.lender::mail.layouts.nope") {
t.Fatalf("err = %v, want unknown layout acme.lender::mail.layouts.nope", err)
}
})
t.Run("other_plugin_alias_refused", func(t *testing.T) {
t.Parallel()
cat := NewCatalog()
registerLender(t, cat)
err := registerBorrower(cat, "layout = \"card\"\n")
if err == nil || err.Error() != "postcard: unknown layout card" {
t.Fatalf("err = %v, want exactly postcard: unknown layout card", err)
}
})
t.Run("precedence_unchanged", func(t *testing.T) {
t.Parallel()
cat := NewCatalog()
registerLender(t, cat)
if got := templateLayout(t, cat, lenderNotice); got != lenderCardLayout {
t.Errorf("lender notice Layout = %q, want %q", got, lenderCardLayout)
}
if err := registerBorrower(cat, "layout = \"system\"\n"); err != nil {
t.Fatalf("Register borrower: %v", err)
}
if got := templateLayout(t, cat, borrowerCode); got != systemLayoutName {
t.Errorf("system Layout = %q, want %q", got, systemLayoutName)
}
if got := templateLayout(t, cat, borrowerPlain); got != defaultLayoutName {
t.Errorf("no-layout Layout = %q, want %q", got, defaultLayoutName)
}
})
t.Run("builtin_full_code", func(t *testing.T) {
t.Parallel()
cat := NewCatalog()
if err := registerBorrower(cat, "layout = \""+minimalLayoutName+"\"\n"); err != nil {
t.Fatalf("Register borrower: %v", err)
}
if got := templateLayout(t, cat, borrowerCode); got != minimalLayoutName {
t.Errorf("Layout = %q, want %q", got, minimalLayoutName)
}
})
}

View File

@@ -368,7 +368,7 @@ func loggerFromApp(app *backpack.App) *slog.Logger {
// BootPlugin registers a plugin's declared mail partials (pact.HasMailPartials)
// and its templates and layouts (pact.HasMailTemplates). Either capability is
// optional. Missing files, duplicates, names outside the plugin's namespace
// and unknown layout aliases fail with the dotted name.
// and unknown layouts (aliases or full layout names) fail with the dotted name.
func BootPlugin[P interface{ ID() string }](app *backpack.App, p P) error {
hm, hasTemplates := any(p).(pact.HasMailTemplates)
hp, hasPartials := any(p).(pact.HasMailPartials)

View File

@@ -73,7 +73,7 @@ type parsedTemplate struct {
pluginID string
subject string
description string
layout string // short name from header; empty means default
layout string // the header's alias or full layout name; after resolveLayoutLocked the full name or the default alias
body string
samples map[string]string // sample.<path> header keys by path
source string // the file's text, CRLF normalized to LF
@@ -224,6 +224,14 @@ func (c *Catalog) Register(pluginID string, fsys fs.FS, templates []string, layo
return nil
}
// resolveLayoutLocked turns the template's layout header value into a full
// layout name. Empty and default give the default alias. Otherwise the value
// is looked up in this order: the registering plugin's own aliases, the
// built-in aliases (system, minimal), then, for a value holding "::", the
// full name of any layout already in the catalog, another plugin's or a
// built-in one. Another plugin's short alias is not visible. A full name no
// registered plugin declares fails: its owner must be in the template
// plugin's Requires(), so it registers first. The caller holds c.mu.
func (c *Catalog) resolveLayoutLocked(t *parsedTemplate) error {
short := strings.TrimSpace(t.layout)
if short == "" || short == defaultLayoutAlias {
@@ -235,6 +243,13 @@ func (c *Catalog) resolveLayoutLocked(t *parsedTemplate) error {
// Not one of the plugin's own aliases: a built-in layout.
full, ok = builtinLayoutAliases[short]
}
if !ok && strings.Contains(short, "::") {
// A full layout name, possibly another plugin's.
if _, registered := c.layouts[short]; !registered {
return fmt.Errorf("postcard: unknown layout %s in %s: no registered plugin declares it (the plugin that owns it must be required, so it registers first)", short, t.name)
}
full, ok = short, true
}
if !ok {
return fmt.Errorf("postcard: unknown layout %s", short)
}