Перейти к основному содержанию
Рецепт номер 93

Рецепты · Глава 5 · Структура книги

Один текст в четырёх стилях ссылок

Одно короткое эссе с шестью ссылками собрано в APA 7, Chicago author-date, IEEE и ISO 690: меняется только настройка стиля.

На этой странице
Вывод
Canvas
Уровень
Средний
Postext
Проверено с Postext 1.65.0
Требуется ≥ 1.34.0
Лицензия
Обновлено 16 окт. 2026 г.
Код: MIT · Текст: CC BY 4.0

с. 1–1 · 1–2 из 4

  • Образец на английском: русского издания пока нет
  • Обрезной формат 155 × 235 мм
  • 1 колонка
  • Source Serif 4 10/14
  • Source Sans 3
  • 4 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 271 мс
  • Строк кода: 116

Коротко

Те же два абзаца о типографике с теми же источниками напечатаны четырежды. На каждой странице свой способ ссылаться, и ссылки со списком меняются вместе с ним, хотя текст написан один раз.

Что получится

Эссе в два абзаца о том, почему хорошая типографика остаётся незамеченной, с шестью источниками: ссылка в тексте, ссылка со страницей, ссылка без автора, потому что его называет фраза, и две работы, процитированные вместе. Текст набран четыре раза на странице 155 × 235 мм, и между четырьмя сборками меняется только citations.style: APA 7, Chicago author-date, IEEE и ISO 690. На каждой странице название стиля стоит на поле своего цвета, и рядом страницы читаются как сравнительная таблица. Меняются вид, порядок и пунктуация ссылок, сортировка и имена в списке, а само эссе — один и тот же файл.

Рецепт отвечает на вопросы

  • Как сменить в книге стиль библиографических ссылок, не трогая текст?
  • Как ссылаться на источники и собирать список литературы в APA, IEEE или другом стиле?

Короткий ответ

script.js · строки 28–47в полном коде
// Citations are written once, Pandoc's way: [@key], [@a; @b], [-@key] without the author,
// @key [p. 17] inside the sentence. citeproc-js writes them, and the list, in the style named.
registerCitationEngine(createCiteprocEngine({ styles: STYLES, locales: LOCALES }));
const SHOWN = [ // the same text, built once per entry
  { style: 'apa', band: 'apa', name: 'APA 7', system: t({ en: 'author-date', es: 'autor-año' }) },
  { style: 'chicago-author-date', band: 'chicago', name: 'Chicago',
    system: t({ en: 'author-date', es: 'autor-año' }) },
  { style: 'ieee', band: 'ieee', name: 'IEEE', system: t({ en: 'numbered', es: 'numérico' }) },
  { style: t({ en: 'iso690-author-date-en', es: 'iso690-author-date-es' }), band: 'iso',
    name: 'ISO 690', system: t({ en: 'author-date', es: 'autor-año' }) },
];
const citations = (style) => ({
  style, // 'apa' → '(Warde, 1955)'; 'ieee' → '[1]'; the list is sorted and set to match
  link: true,
  // The authors' names stay whole in the citations, the text and the list: the APA build
  // set '(Lup-' | 'ton, 2010)'.
  hyphenateNames: false,
  bibliography: { fontSize: em(0.85), lineHeight: pt(11.2), hangingIndent: mm(6),
    entrySpacing: pt(2), labelWidth: mm(6), doi: 'hide' },
});

Ингредиенты

Также применяет
Атрибуты заголовков
Шрифты
Source Serif 4, Source Sans 3 (SIL OFL 1.1)
Материалы
Нет: все иллюстрации рисует код

Порядок работы

#1 · Одна настройка

Код приведён выше, в разделе «Короткий ответ». Ссылки записаны в содержимом один раз, в синтаксисе Pandoc, а источники стоят в блоке BibTeX в конце. citations.style называет стиль CSL, и citeproc-js пишет по нему каждую ссылку и каждую запись: APA ставит запятую перед годом и сортирует две работы по авторам, Chicago сохраняет порядок записи, IEEE превращает ссылки в номера в порядке первой ссылки, ISO 690 набирает фамилии в списке прописными. Для книги в работе это вся правка: одно значение в конфигурации, текст не меняется.

#2 · Четыре сборки, два разворота

script.js · строки 150–157в полном коде
// The style is set for the whole document, so each style is a build of its own.
const docs = [];
for (at = 0; at < SHOWN.length; at++) {
  // pageIndexOffset makes each page the next one of a book, so the desk pairs them:
  // APA beside Chicago, IEEE beside ISO 690.
  const content = { markdown, continuation: { pageIndexOffset: at + 1 } };
  docs.push(await buildDocumentWithFonts(content, config(), kitFonts(FONTS)));
}

Стиль действует на весь документ, поэтому четыре варианта — это четыре сборки одного Markdown. У каждой pageIndexOffset на единицу больше, чем у предыдущей, и её страница становится следующей страницей воображаемой книги; стол раскладывает их на два разворота, и рядом стоят два стиля «автор — год», которые различаются меньше всего.

#3 · Название стиля на поле

script.js · строки 51–74в полном коде
// The kicker names the build's citation style: a label of the design (#849).
const kicker = (s, i) => `${t({ en: 'Citation style', es: 'Estilo de cita' })}`
  + ` · ${i + 1} / ${SHOWN.length} · ${s.system}`;
const opener = (s, i) => ({
  enabled: true,
  minHeight: mm(41), // from the top margin to under the title, 63 mm from the trim
  slot: { elements: [
    { kind: 'box', id: 'band', style: { backgroundColor: col(s.band) },
      placement: { anchor: { to: 'page', edge: 'top-left' },
        size: { width: 'fill', height: mm(44) } } },
    { kind: 'text', id: 'kicker', content: kicker(s, i), fontFamily: SANS, fontSize: pt(8),
    fontWeight: 600, letterSpacing: pt(1.4), textTransform: 'uppercase', color: col('paper'),
    align: 'left',
    placement: { anchor: { to: 'page', edge: 'top-left' }, offset: { x: mm(18), y: mm(12) } } },
    { kind: 'text', id: 'name', content: s.name, fontFamily: SERIF, fontSize: pt(54),
      fontWeight: 600, lineHeight: 1, color: col('paper'), align: 'left', overflow: 'clip',
      placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { x: mm(0), y: mm(5) },
        size: { width: mm(119), height: 'auto' } } },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: SERIF, fontSize: pt(20),
      fontWeight: 600, lineHeight: 1.15, color: col('ink'), align: 'left', overflow: 'wrap',
      placement: { anchor: { to: 'page', edge: 'top-left' }, offset: { x: mm(18), y: mm(52) },
        size: { width: mm(119), height: 'auto' } } },
  ] },
});

Оформление заголовка рисует поле от обрезного края, надзаголовок с номером и системой стиля и название, 54 пт. Название и система берутся из скрипта, а не из Markdown, потому что текст во всех четырёх документах один.

script.js · строки 15–22в полном коде
const palette = {
  ink: '#1d1b19', muted: '#66605a', rule: '#cfc8bf', paper: '#ffffff',
  apa: '#2f5d8a', chicago: '#8c2f2b', ieee: '#24476b', iso: '#3c6b4f', // the four bands
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// Each document points main-color at its own band, so any default left follows it.
const colorPalette = (band) => Object.entries({ ...palette, 'main-color': palette[band] })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));

Каждый документ указывает main-color на собственное поле, поэтому четыре цвета — связанные записи палитры, и всё, что конфигурация не задаёт, следует цвету поля своей страницы.

Рецепт целиком

Sandbox
// ═══ Postext Cookbook · Nº 093 · One text in four citation styles ════════════════
// https://postext.dev/en/cookbook/one-text-four-citation-styles
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.34.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerCitationEngine,
} from 'https://esm.sh/postext';
import { createCiteprocEngine, STYLES, LOCALES } from 'https://esm.sh/postext-citeproc';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'one-text-four-citation-styles';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: one ink, and a colour for each style's band
const palette = {
  ink: '#1d1b19', muted: '#66605a', rule: '#cfc8bf', paper: '#ffffff',
  apa: '#2f5d8a', chicago: '#8c2f2b', ieee: '#24476b', iso: '#3c6b4f', // the four bands
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// Each document points main-color at its own band, so any default left follows it.
const colorPalette = (band) => Object.entries({ ...palette, 'main-color': palette[band] })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const [SERIF, SANS] = ['Source Serif 4', 'Source Sans 3'];
const LEAD = 14; // pt

// #region answer: the style is one setting; everything else stays the same
// Citations are written once, Pandoc's way: [@key], [@a; @b], [-@key] without the author,
// @key [p. 17] inside the sentence. citeproc-js writes them, and the list, in the style named.
registerCitationEngine(createCiteprocEngine({ styles: STYLES, locales: LOCALES }));
const SHOWN = [ // the same text, built once per entry
  { style: 'apa', band: 'apa', name: 'APA 7', system: t({ en: 'author-date', es: 'autor-año' }) },
  { style: 'chicago-author-date', band: 'chicago', name: 'Chicago',
    system: t({ en: 'author-date', es: 'autor-año' }) },
  { style: 'ieee', band: 'ieee', name: 'IEEE', system: t({ en: 'numbered', es: 'numérico' }) },
  { style: t({ en: 'iso690-author-date-en', es: 'iso690-author-date-es' }), band: 'iso',
    name: 'ISO 690', system: t({ en: 'author-date', es: 'autor-año' }) },
];
const citations = (style) => ({
  style, // 'apa' → '(Warde, 1955)'; 'ieee' → '[1]'; the list is sorted and set to match
  link: true,
  // The authors' names stay whole in the citations, the text and the list: the APA build
  // set '(Lup-' | 'ton, 2010)'.
  hyphenateNames: false,
  bibliography: { fontSize: em(0.85), lineHeight: pt(11.2), hangingIndent: mm(6),
    entrySpacing: pt(2), labelWidth: mm(6), doi: 'hide' },
});
// #endregion

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Попробуйте стиль со сносками

С Chicago notes and bibliography каждая ссылка становится сноской, а список библиографией; текст по-прежнему не меняется.

-  { style: 'apa', band: 'apa', name: 'APA 7', system: t({ en: 'author-date', es: 'autor-año' }) },
+  { style: 'chicago-notes-bibliography', band: 'apa', name: 'Chicago', system: 'notes' },

#Ставьте номера верхним индексом

Стиль с номерами может сохранить список, а ссылки печатать верхним индексом, как в Nature и Vancouver.

-  link: true,
+  link: true, marker: 'superscript',

Частые ошибки

  • Указатель места записан один раз, а каждый стиль печатает своё слово: здесь во всех четырёх «p. 17». Встроенный испанский стиль ISO 690 печатает «p.» для любого места, включая раздел и главу, поэтому этот текст ссылается на страницу.
  • Номер издания в BibTeX пишут числом (edition = {3}): тогда каждый стиль печатает по-своему «3rd ed.», «3.ª ed.» или «3.». Если написать «3rd», слово напечатается как есть, и форма стиля пропадёт.

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Шрифты
Source Serif 4 (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
Sandbox