Коротко
Журнальный очерк на четыре страницы по шаблону: текст сам переходит из колонки в колонку и на новые страницы, обтекая цитату и контур фотографии.
Что получится
Страницы 46–49 вымышленного ежеквартальника о городской жизни Patio: очерк о наборщице на пенсии, которая держит четырнадцать ульев на крыше типографии, где проработала тридцать лет. Левая полоса начального разворота — фотография, с заголовком поверх гравия и тонированной врезкой цифр на небе. На правой лид и первые две колонки, цитата через средник и соломенный улей, вырезанный из фона: строки второй колонки повторяют его купол. Дальше текст идёт на столько страниц, сколько нужно, по три колонки на каждой, и кончается там, где кончается. Испанское, английское и немецкое издания используют один шаблон с другими словами, а немецкое проводит длинные составные слова через колонки в 60 мм.
Рецепт отвечает на вопросы
- Как провести журнальную статью через связанные фреймы на нескольких страницах?
- Как сверстать журнал по рубрикам, чтобы каждая статья открывалась разворотом с главным фото на соседней полосе?
- Можно ли в Postext набрать три и более колонок или обтекание изображения текстом?
Короткий ответ
const opening = {
id: 'apertura',
spread: true,
header: false,
frames: [
{ name: 'titulo', takes: 'h1', layer: 2, width: mm(150),
placement: at('container', 'bottom-left', 4, -14) },
{ name: 'datos', style: 'datos', layer: 2, width: mm(64),
placement: at('container', 'top-left', 4, 6) },
{ name: 'entradilla', width: mm(2 * COLUMN + GAP),
placement: at('container', 'top-left', RECTO) },
// The story names no slot, so it goes to the flow frame, then on down the chain.
{ name: 'col-1', flow: true, next: 'col-2', width: mm(COLUMN), height: 'fill',
placement: at('#entradilla', 'below', 0, 7) },
// What the last column cannot hold goes on to a page added after the spread.
{ name: 'col-2', width: mm(COLUMN), height: 'fill',
placement: at('#col-1', 'right-of', GAP),
overflow: { continueIn: 'template:seguido' } },
...pushers,
],
decoration: { elements: [
{ kind: 'image', id: 'foto', resourceId: '{attr.foto}',
fit: 'cover',
placement: { ...at('bleed', 'top-left'), size: { width: mm(W), height: 'fill' } } },
{ kind: 'text', id: 'seccion', content: '{attr.seccion}', fontFamily: SANS, fontSize: pt(9),
fontWeight: 700, letterSpacing: pt(2), textTransform: 'uppercase', color: col('paper'),
placement: at('#titulo', 'above', 0, -3) },
] },
};
Ингредиенты
- Возможности
- Связанные текстовые фреймыФреймы, которые отодвигают текст: по рамке или контуруМакетные страницыЗеркальные поляИллюстрации в дизайне страницыПеренос слов и язык документаКолонтитулы и колонцифрыСтили абзацевБуквицы на начальных полосахВрезкиСемантическая палитраРисунки и таблицы как ресурсыСтраницы на холстеЭкспорт в PDF
- Также применяет
- Буквицы в абзацах текстаШаблоны разворотовФреймы с продолжением на следующей страницеОформление, привязанное к фреймамРисунки точно здесьШрифты, встроенные в PDFСобственные типы ресурсов
- Шрифты
- Literata, Fraunces, Instrument Sans (SIL OFL 1.1)
- Материалы
rooftop-1400.jpgskep-720.png- Painted hives on a factory roof at sunrise (the opening spread) (Generated With Diffusion Models, оригинал)
- A straw bee skep on a transparent ground (the cut-out the text runs round) (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Один шаблон, одна статья
Код приведён выше, в разделе «Короткий ответ». Весь очерк — один блок ::::page{template="apertura" spread}: заголовок идёт во фрейм с takes: 'h1', цифры и лид в свои слоты, а всё остальное, что не называет слота, во фрейм потока col-1. Когда col-1 заполнен, текст продолжается в col-2, заново разбитый по его ширине, а что не вместил col-2, уходит на страницу, добавленную после разворота (overflow.continueIn: 'template:seguido'), после слова Continued на языке читателя. Текст не называет ни колонки, ни страницы: вырежьте абзац, и все следующие строки поднимутся.
#2 · Страницы, которые добавляет статья
// The third column continues into this same template: the story goes on in the frame its
// chain starts in, so every added page fills all three columns.
const seguido = {
id: 'seguido',
frames: [
{ name: 'seguido-1', flow: true, next: 'seguido-2', height: 'fill', width: mm(60.3) },
{ name: 'seguido-2', next: 'seguido-3', height: 'fill', width: mm(60.3),
placement: at('#seguido-1', 'right-of', 5) },
{ name: 'seguido-3', height: 'fill', width: mm(60.3),
placement: at('#seguido-2', 'right-of', 5),
overflow: { continueIn: 'template:seguido' } },
],
};
Каждая добавленная страница — три связанные колонки по 60,3 мм, и один шаблон служит им всем. Третья колонка продолжается в этом же шаблоне, и статья идёт дальше во фрейме, с которого начинается его цепочка, seguido-1: каждая добавленная страница заполняет все три колонки, сколько бы страниц ни потребовалось. Кегль тоже ничем закреплять не надо: фрейм, которому есть куда продолжаться, продолжается раньше, чем текст уменьшится, и статья, длиннее на пять строк, получает новую страницу, а не 92,5 % на последней.
#3 · Два фрейма, которые отодвигают колонки
const pushers = [
// The pull quote straddles the gutter: each column loses the side it covers.
{ name: 'cita', style: 'cita', exclude: 'push', width: mm(62),
placement: at('#entradilla', 'below', COLUMN - 27.5, 82) },
// The skep's frame pushes with the shape of its picture, read from the PNG's alpha.
{ name: 'recorte', exclude: 'push', wrap: 'contour', layer: 2, width: mm(58),
placement: at('container', 'bottom-right', 9, -8) },
];
Ни один из этих фреймов в статье не участвует: каждый отодвигает строки колонок, на которые заходит. Цитата привязана к лиду, на 82 мм вниз, и стоит поперёк средника, поэтому первая колонка теряет правую сторону, а вторая левую. У фрейма улья wrap: 'contour': строки рядом с ним короче на ширину картинки на их высоте плюс 2,5 мм отступа, поэтому вторая колонка повторяет купол и под его основанием снова идёт полной шириной.
#4 · Контур, который едет вместе с картинкой
const photo = { id: 'azotea', typeId: 'foto', kind: 'bitmap', createdAt: 0, updatedAt: 0,
caption: '', altText: t({
es: 'Seis colmenas de colores en la azotea de una fábrica, con la ciudad al amanecer',
en: 'Six painted hives on a factory roof, with the city behind them at sunrise',
de: 'Sechs bunte Bienenkästen auf einem Fabrikdach, dahinter die Stadt im Morgenlicht' }),
bitmap: { fileId: 'rooftop-1400.jpg', format: 'jpeg', width: 1400, height: 1848 } };
let skep = { id: 'cesto', typeId: 'foto', kind: 'bitmap', createdAt: 0, updatedAt: 0,
caption: '', altText: t({ es: 'Un cesto de paja para abejas', en: 'A straw bee skep',
de: 'Ein Bienenkorb aus Stroh' }),
contour: { threshold: 0.5, margin: mm(2.5) },
bitmap: { fileId: 'skep-720.png', format: 'png', width: 720, height: 828 } };
await loadImage('rooftop-1400.jpg', asset('rooftop-1400.jpg'));
await loadImage('skep-720.png', asset('skep-720.png'));
// The layout reads pictures by size, never by pixels: the outline travels as a trace.
const trace = await traceResourceContour(skep, imageBytes('skep-720.png'), 'image/png');
skep = withContourTrace(skep, trace);
const resources = [photo, skep];
Вёрстка читает размер картинки, но никогда её пиксели, поэтому контур один раз снимается с альфа-канала PNG через traceResourceContour и хранится в ресурсе как contour.traced. Улей — PNG шириной 720 px в 200 цветов на прозрачном фоне (225 КБ). Фотография на левой полосе — изображение оформления, resourceId: '{attr.foto}': картинку выбирает блок, а место шаблон. Она стоит с fit: 'cover': каковы бы ни были пропорции, снимок заполняет левую полосу, а рамка обрезает лишнее.
#5 · Колонтитулы, которые читают блок
const head = (id, content, parity, edge, x, extra = {}) => ({
kind: 'text', id, content, parity, fontFamily: SANS, fontSize: pt(7.5), fontWeight: 600,
letterSpacing: pt(1.2), textTransform: 'uppercase', color: col('muted'),
placement: at('page', edge, x, 11), ...extra,
});
const folio = { fontWeight: 700, color: col('honey') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', 'top-left', OUT, folio),
head('verso-title', '{title}', 'even', 'top-left', OUT + 9),
head('recto-title', '{attr.seccion}', 'odd', 'top-right', -(OUT + 9)),
head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUT, folio),
] };
Начальный разворот скрывает колонтитулы (header: false); добавленные страницы печатают название журнала на левой полосе и рубрику на правой. Рубрика берётся из блока, seccion="City", а {attr.seccion} читает её на добавленных страницах так же, как на самом развороте.
Рецепт целиком
// ═══ Postext Cookbook · Nº 160 · A magazine feature threaded through frames ═════
// https://postext.dev/en/cookbook/magazine-threaded-frames
// Code: MIT · Text: original (CC BY 4.0) · Pictures: Generated With Diffusion Models
// Fonts: Literata, Fraunces, Instrument Sans (SIL OFL 1.1) · Needs postext ≥ 1.65.0
//
// A six-page feature of an invented city magazine, set as one composed page: an opening
// spread whose frames are drawn in the config, and pages the text adds as it runs on.
// Every word, the photo's id and the section name are in content.<lang>.md.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
traceResourceContour, withContourTrace,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('es' | 'en' | 'de')
const RECIPE = 'magazine-threaded-frames';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: honey on warm paper, every colour linked by id
const palette = {
ink: '#211c18', // text
honey: '#a65a12', // the accent: kickers, rules, the drop cap, the pull quote
tint: '#f5ecdc', // the fact box
rule: '#d8c6a6', // hairlines
muted: '#6b6158', // running heads, credits
paper: '#ffffff',
shade: '#1a1612', // the plate under the headline on the photo
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
{ id: 'main-color', name: 'honey (defaults)', value: { hex: palette.honey, model: 'hex' } },
];
// #endregion
const SERIF = 'Literata';
const DISPLAY = 'Fraunces';
const SANS = 'Instrument Sans';
const W = 225; // trim width in mm; the spread's sheet is twice as wide
const IN = 16; // inner margin
const OUT = 18; // outer margin
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
// The spread's content area runs from the verso's outer margin to the recto's: a frame
// on the recto starts RECTO mm in from its left edge.
const RECTO = W - OUT + IN;
const COLUMN = 92; // the two columns of the recto
const GAP = 7;
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Обтекайте улей по рамке
Без wrap: 'contour' фрейм отодвигает текст своим прямоугольником, и строки рядом с куполом останавливаются у прямого края.
- { name: 'recorte', exclude: 'push', wrap: 'contour', layer: 2, width: mm(58),
+ { name: 'recorte', exclude: 'push', layer: 2, width: mm(58),#Уберите пометку о продолжении
mark: false кончает отрезок на его последней строке, без слова Continued: колонка вмещает на строку больше.
- overflow: { continueIn: 'template:seguido' } },
+ overflow: { continueIn: 'template:seguido', mark: false } },Частые ошибки
- Заголовок, который шаблон отправляет в отдельный фрейм, не открывает буквицы в текстовых фреймах. Первый абзац статьи заключён в
:::paragraphs{style="inicio"}, иdropCapнесёт этот стиль.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, CC BY 4.0
- Изображения
- Painted hives on a factory roof at sunrise (the opening spread) · Generated With Diffusion Models · оригинал
- A straw bee skep on a transparent ground (the cut-out the text runs round) · Generated With Diffusion Models · оригинал
- Шрифты
- Literata (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


