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

Рецепты · Глава 12 · Учебники

Китайская тетрадь: для ученика и учителя

练习册 по китайскому и математике: разделы 一、二、, скобки ( ), 田字格 и вычисления в столбик, собранные дважды из одного текста.

На этой странице
  • Образец на иностранном языке: русского издания пока нет
  • Обрезной формат 184 × 260 мм
  • 1 колонка
  • Noto Serif SC 10,5/21
  • LXGW WenKai TC
  • Noto Sans SC
  • 8 страниц
  • Уровень
  • Postext 1.63.0
  • Свёрстано за 93 мс
  • Строк кода: 162

Коротко

Тетрадь китайской начальной школы: два раздела заданий по языку и математике. Из одного текста выходит тетрадь ученика с пропусками и ключом и тетрадь учителя с ответами красным.

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

Два раздела 练习册 для второго класса на полосе 16开: языковой, 春天来了, и математический, на сложение и вычитание до 100. Каждый открывается акварельной полосой, ярлыком предмета и строкой для класса, имени и баллов, а дальше идут задания, какие печатают в китайской тетради: 看拼音写词语, чтения, которые надо обвести, 选择题 со скобкой ( ) после вопроса и вариантами A. B. C. D. в ряд, 判断题 со скобкой в конце строки, пропуски, 连线 между счётными словами и предметами, предложение на 田字格, 口算 в четыре столбца, 竖式 с клеткой на каждую цифру и текстовая задача. Баллы стоят в каждом задании, как их читает ученик. Один и тот же Markdown верстается дважды: тетрадь ученика с 参考答案 в конце каждого раздела и тетрадь учителя, где каждый ответ вписан красным шрифтом Кай на своё место.

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

  • Как набрать китайские тестовые вопросы: скобка ( ) после условия и варианты A. B. C. D. в ряд?
  • Как сделать издание для учителя с ответами на своих местах из книги ученика?
  • Как дать открытому вопросу место для письма: французскую линовку Seyès, клетку или квадраты 田字格?
  • Как набрать деление столбиком так, как его записывают в школах каждой страны?

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

script.js · строки 36–65в полном коде
// The exercise style is the form; the Markdown holds every word, the points included. The
// same text builds both editions: `edition: 'teacher'` writes each answer into its blank,
// bracket and square in red Kai, rings the right options and draws the matching lines.
const lianxi = {
  id: 'lianxi',
  number: { format: 'simp-chinese-informal', suffix: '、', fontFamily: HEI, color: col('green') },
  instruction: { fontFamily: HEI, bold: false }, // 黑体, not bold: the points stay quiet
  // 选择题: A. B. C. D. in a row, a ( ) after the stem for the letter.
  options: { labels: 'alpha-upper', suffix: '.', layout: 'row', bracket: true },
  trueFalse: { look: 'bracket' }, // 判断题: ( ) at the end of the line, √ or ×
  blank: { look: 'line', color: col('ink') },
  area: { kind: 'tianzige', color: col('rule') }, // 写话 on 田字格
  match: { color: col('green') },
  grid: { fontFamily: SONG, rule: col('rule') },
  answers: { color: col('red'), fontFamily: KAI },
  solutions: { box: 'daan' },
  marginTop: em(1.2), marginBottom: em(0.6),
};
const exerciseStyles = [
  lianxi,
  // 看拼音写词语: a box under each syllable, as wide as its word.
  { id: 'pinyin', extends: 'lianxi', blank: { look: 'box', width: 'answer', color: col('rule') } },
  // 在( )里填: the bracket is in the text, the blank inside it draws nothing.
  { id: 'kuohao', extends: 'lianxi', blank: { look: 'none', width: 'answer' } },
];
let edition = 'student'; // the second build below prints the teacher's book
// The pupil's book: 参考答案 where a :::solutions line stands, at the end of each unit.
// The teacher's book: every answer on the page, so no key at the end.
const exercises = () => ({ edition,
  solutions: { placement: edition === 'teacher' ? 'none' : 'directive' } });

Ингредиенты

Возможности
Стили упражненийИздание для учителяВыбор ответа, «верно/неверно»УпражненияПропуски и банки словСоединение и сортировкаОткрытые вопросы и место для ответаДействия в столбикОтветыКитайские числаКитайские, японские и корейские шрифтыСетка знаковТочки выделения, линии имён и названийПлашки в строкеТри колонки и большеОформленные начальные полосыАтрибуты заголовковИллюстрации в дизайне страницыСемантическая палитраЭкспорт в PDF
Шрифты
Noto Serif SC, Noto Sans SC, LXGW WenKai TC (SIL OFL 1.1)
Материалы
  • market-1600.jpg
  • spring-1600.jpg
  • A Chinese village in early spring: willows, swallows, peach blossom and two children on a path between rice fields. (Generated With Diffusion Models, оригинал)
  • Two children count oranges, apples and pears at a grandmother's fruit stall, a cat on a stool beside them. (Generated With Diffusion Models, оригинал)

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

#1 · Один стиль для всех заданий

Код — в разделе «Короткий ответ» выше. Задания считаются китайскими числительными с полноширинным 、 после них, поэтому пробела за номером нет; формулировка набрана шрифтом Хэй без полужирного, и баллы в скобках читаются её частью. options.bracket пишет ( ) после каждого вопроса, а в тетради учителя туда попадает верная буква. Два малых стиля расширяют основной: pinyin рисует каждый пропуск клеткой шириной в слово и печатает над ней чтение из [[{春天|chūn tiān}]], в тетради ученика тоже; kuohao ничего не рисует, потому что скобка в 在( )里填 есть в тексте.

#2 · Тетради ученика и учителя из одного текста

script.js · строки 320–324в полном коде
const build = () => withLoadedFonts(() => buildDocument({ markdown, resources }, config()),
  { ...kitFonts(FONTS), text: markdown });
const pupil = await build();
edition = 'teacher';
const docs = [pupil, await build()];

Конфигурация — функция, поэтому каждая сборка получает свой объект, а пакет для Sandbox хранит ученическую. edition: 'teacher' вписывает ответы цветом и шрифтом из answers: слова в клетки, буквы в скобки, √ и × в 判断题, цифры в клетки 竖式, образцовое предложение по знаку на квадрат. Тетрадь ученика копит ключ для строки :::solutions в конце каждого раздела; тетради учителя он не нужен.

#3 · Начало раздела с акварелью

script.js · строки 69–87в полном коде
const BAND = 184 / 2.4; // mm: the painting's height at the page's width
const opener = { enabled: true, minHeight: mm(BAND - 22 + 23), slot: { elements: [
  { kind: 'image', id: 'picture', resourceId: '{attr.pic}', decorative: true, reserve: false,
    placement: { anchor: { to: 'page', edge: 'top-left' },
      size: { width: mm(184), height: mm(BAND) } } },
  { kind: 'text', id: 'subject', content: '{attr.kicker}', fontFamily: HEI, fontSize: pt(11),
    fontWeight: 700, color: col('paper'), letterSpacing: pt(2), align: 'center',
    box: { backgroundColor: col('green'), borderRadius: mm(1.5),
      padding: { top: mm(0.8), bottom: mm(0.8), left: mm(2.4), right: mm(2) } },
    placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(0), y: mm(BAND - 22 + 6) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: HEI, fontSize: pt(24),
    fontWeight: 700, color: col('ink'), align: 'left',
    placement: { anchor: { to: '#subject', edge: 'right-of' },
      offset: { x: mm(4), y: mm(-2.6) } } },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.2), color: col('green'),
    placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(0), y: mm(BAND - 22 + 19) }, size: { width: 'fill' } } },
] } };

Акварель привязана к странице, поэтому доходит до верхнего края и на правой, и на левой полосе; ярлык предмета и заголовок отмеряются от верха полосы набора, ниже конца акварели. У обоих разделов общий дизайн, а различаются атрибуты заголовка, kicker и pic.

#4 · Колонцифры внизу

script.js · строки 91–101в полном коде
const foot = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
  parity, fontFamily: HEI, fontSize: pt(8), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(-10) } }, ...extra });
const footer = { elements: [
  foot('folio-v', '{pageNumber}', 'even', 'bottom-left', 16,
    { fontWeight: 700, color: col('green') }),
  foot('series', '{title}', 'even', 'bottom-left', 24),
  foot('unit', '{chapterTitle}', 'odd', 'bottom-right', -24, { align: 'right' }),
  foot('folio-r', '{pageNumber}', 'odd', 'bottom-right', -16,
    { fontWeight: 700, color: col('green'), align: 'right' }),
] };

В китайских тетрадях колонцифра стоит внизу. Название серии берётся из метаданных Markdown ({title}), раздела — из его заголовка ({chapterTitle}).

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

Sandbox
// ═══ Postext Cookbook · Nº 171 · A Chinese exercise book, pupil's and teacher's ═══
// https://postext.dev/en/cookbook/chinese-exercise-book
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Noto Serif SC, Noto Sans SC, LXGW WenKai TC (SIL OFL 1.1) · Needs postext ≥ 1.63.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'zh'; // @lang: the language of the frame; the exercise book is Chinese in all
const RECIPE = 'chinese-exercise-book';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a green exercise book, and the red of the teacher's pen
const palette = {
  ink: '#1f2523', // text: a green-tinted near-black
  green: '#2c7350', // the one accent: section numbers, the subject tab, the squares
  red: '#d0352c', // the teacher's answers
  tint: '#e6f2ea', // the subject tab's ground, the answers box
  rule: '#8fb9a2', // 田字格, the matching dots' lines
  muted: '#68736d', // folios, the series line
  paper: '#ffffff',
};
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: 'accent (defaults)', value: { hex: palette.green, model: 'hex' } },
];
// #endregion
// 宋 for the text, 黑 for the instructions and labels, 楷 for what the teacher writes.
const [SONG, HEI, KAI] = ['Noto Serif SC', 'Noto Sans SC', 'LXGW WenKai TC'];
const CHARS = 40; // characters per line: 40 × 10.5 pt = 148 mm
const SIZE = 10.5; // pt: 五号, the size of a school book's text

// #region answer: sections 一、二、 that print the pupil's book or the teacher's
// The exercise style is the form; the Markdown holds every word, the points included. The
// same text builds both editions: `edition: 'teacher'` writes each answer into its blank,
// bracket and square in red Kai, rings the right options and draws the matching lines.
const lianxi = {
  id: 'lianxi',
  number: { format: 'simp-chinese-informal', suffix: '、', fontFamily: HEI, color: col('green') },
  instruction: { fontFamily: HEI, bold: false }, // 黑体, not bold: the points stay quiet
  // 选择题: A. B. C. D. in a row, a ( ) after the stem for the letter.
  options: { labels: 'alpha-upper', suffix: '.', layout: 'row', bracket: true },
  trueFalse: { look: 'bracket' }, // 判断题: ( ) at the end of the line, √ or ×
  blank: { look: 'line', color: col('ink') },
  area: { kind: 'tianzige', color: col('rule') }, // 写话 on 田字格
  match: { color: col('green') },

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

Варианты

#Печатать ключ в конце главы

Без строк :::solutions chapterEnd собирает ключ каждого раздела перед следующим заголовком первого уровня.

-  solutions: { placement: edition === 'teacher' ? 'none' : 'directive' } });
+  solutions: { placement: edition === 'teacher' ? 'none' : 'chapterEnd' } });

#Дать каждому слову свою 田字格

Открытый вопрос с cells="2 2 2 2" ставит группу квадратов для каждого слова под строкой пиньиня, как заканчивается китайское издание листа о десяти традициях.

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

Подводный камень

Китайские шрифты загружаются частями через блок cjk

Fontsource отдаёт китайскую, японскую или корейскую гарнитуру примерно сотней файлов на насыщенность, каждый со своим диапазоном знаков. loadFonts загружает только файл latin, поэтому на экране иероглифы берутся из системного шрифта и измеряются неверно, а fontsourceProvider отдаёт PDF тот же файл latin, и они печатаются пустыми квадратами. Укажите блок cjk набора kit, вызовите loadCjkFonts(FONTS, markdown) после loadFonts (по разу на каждый шрифт, с текстом, который он набирает, если в книге несколько шрифтов CJK) и передайте renderToPdf fontProvider: cjkPdfProvider: оба берут файлы, в которых есть знаки текста. Китайские, японские и корейские шрифты →

  • Шрифт Кай набирает только ответы, поэтому загружает лишь знаки пропусков и образцовых ответов; знак, который он набирает где-то ещё, нужно добавить в этот текст.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • A Chinese village in early spring: willows, swallows, peach blossom and two children on a path between rice fields. · Generated With Diffusion Models · оригинал
  • Two children count oranges, apples and pears at a grandmother's fruit stall, a cat on a stool beside them. · Generated With Diffusion Models · оригинал
Шрифты
Noto Serif SC (SIL OFL 1.1) · Noto Sans SC (SIL OFL 1.1) · LXGW WenKai TC (SIL OFL 1.1)
Sandbox