[ Prev ] [ Index ] [ Next ]

Templates

Attachments

Template Editor Dialog



The Template Editor Dialog can be accessed with the menu item "Edit" -> "Templates". It will show a list of templates that are available, and allows you to view and edit them.

Templates can either be system defaults, or custom templates in your home folder. When you edit them, a copy is made of the default to your home folder, and this copy is than edited. The remove function again deletes this custom version, but does not touch the default template.

Note: if you try to edit for example a HTML template, and it opens in the web browser instead of in your default text editor, the cause is most likely that you did not explicitly configure a text editor in the preferences. Go to the Preferences Dialog and specify your text editor.

Templates for export



For a list of templates for exporting see Export and subpages.

Template options



Templates can also set template options that influence the generated output, by setting key-value pairs like in the example below. A list of available template options for a output format can be found at Export and subpages.

Special templates

wiki/Default.txt
This template is used to initialize new pages. The default contains a header with the page name and the date at which the page was created.

wiki/Journal.txt
This template is used to initialize new pages in the Journal namespace.

Customizing



Templates are located in /usr/share/zim/templates/ and ~/.local/share/zim/templates by default. You can add templates you use more often there. To modify a template copy it to the ~/.local/... directory and edit it.

Template syntax:

[% var %]	# interpolates a variable
[%- var %]	# + strip line break before the expression
[% var -%]	# + strip line break after the expression
[%- var -%]	# + strip line breaks on both sides

[% IF expr %] ... [% END %]	# conditionals

[% IF expr %]
	...
[% ELSIF expr %]
	...
[% ELSE %]
	...
[% END %]

[% FOREACH name = var ]		# loop
... [% name %] ...
[% END %]

[% strftime("%c") %]		# current time stamp
[% strftime("%c", var) %]	# date from variable


[% options.option_name = value %] # set the template option option_name to value

[% page.properties["Creation-Date"] %] # access dict


For the IF and ELIF statements the expression can be either just a variable, in which case it is evaluated boolean, or an equality expression with "==". For example "[% IF page.name == 'foo' %]" is understood. More complex expressions are not supported.

Available variables:

zim.version		# version of zim
notebook.name		# name of the notebook
notebook.interwiki	# interwiki key of the notebook if any

page.name		# complete page name
page.namespace		# namespace
page.basename		# last part of the page name
page.properties		# dict with page properties
page.title		# first heading in the page or the basename
page.heading		# first heading in the page
page.body		# content of the page without the leading heading
page.content	# content of the page including the leading heading
page.has_links	# True if the page has links to other pages
page.links		# list of page objects for pages linked in this page
page.has_backlinks	# True if the page is linked by other pages
page.backlinks		# list of page objects for pages linking to this page
page.has_attachments	# True if the page has attachments
page.attachments	# list of file objects for attachments

# These special pages have the same properties as the 'page' object
pages.index		# the index page generated when exporting
pages.home		# the home page
pages.next		# the next page in the index (if any)
pages.previous		# the previous page in the index (if any)

options			# dict where format specific options can be set


File objects returned by page.attachments have the following attributes:

file.path		# (relative) path as a string
file.basename	# file basename
file.mtime		# file mtime, to be used with strftime()
file.size		# file size as human readable string


Functions available:

url(link)
Turns a zim link or file object into an URL
resource(filename)
Returns an URL for a template resource (see below)
strftime(template, date)
Format a date, see standard library for codes
strfcal(template, date)
Format a week number, accepts:
%w for day of week according to locale
%W for weeknumber according to locale
%Y for the year to which the week belongs
pageindex(namespace, collapse, ignore_empty)
Creates a page index of a given namespace or the whole notebook
namespace: the starting root - defaults to the top level (":")
collapse: if TRUE only branches related to the current page are visible, if FALSE all branches are visible - defaults to TRUE
ignore_empty: if TRUE empty pages are ignored — defaults to TRUE.
Example: menu(page.namespace, TRUE, FALSE)


See also the Journal Plugin for some properties available for journal pages

Template Resources


To add additional files to the template, create a folder of the same name as the template. Any files in the folder (like style sheets, images, javascript files, etc.) will be copied along when this template is used to export data in zim. There is a function "resource(filename)" to refer to these files in the template.

Zim always includes some images when exporting for the checkboxes used in checkbox lists. To customize these there should be template resources named "checked-box.png", "unchecked-box.png" and "xchecked-box.png" in this folder.

For the web interface the resources can also contain a "favicon.ico" to serve as the favicon of the website.




Шаблоны
=========

Zim использует шаблоны при экспорте страниц. Таким образом, вы можете, например, написать свой веб-сайт в zim и экспортировать его в HTML, используя определение макета и стиля по вашему выбору.

Шаблоны также используются для инициализации новых страниц.

Если вы ищете информацию для шаблонов файлов для вложений, см. Вложения

Диалог редактора шаблонов
----------------------

Доступ к диалогу редактора шаблонов можно получить с помощью пункта меню «Редактировать» -> «Шаблоны». Он покажет список доступных шаблонов и позволит вам просматривать и редактировать их.

Шаблоны могут быть либо системными настройками по умолчанию, либо пользовательскими шаблонами в вашей домашней папке. Когда вы их редактируете, по умолчанию создается копия вашей домашней папки, и эта копия затем редактируется. Функция удаления снова удаляет эту пользовательскую версию, но не затрагивает шаблон по умолчанию.

Примечание. Если вы попытаетесь отредактировать, например, шаблон HTML, и он откроется в веб-браузере, а не в текстовом редакторе по умолчанию, скорее всего, причина заключается в том, что вы не настроили явно текстовый редактор в настройках. Перейдите в диалог настроек и укажите свой текстовый редактор.

Шаблоны на экспорт
--------------------

Список шаблонов для экспорта см. В разделе Экспорт и подстраницы.

Варианты шаблона
----------------

Шаблоны также могут устанавливать параметры шаблона, которые влияют на сгенерированный вывод, устанавливая пары ключ-значение, как в примере ниже. Список доступных опций шаблона для выходного формата можно найти на Экспорт и подстраницы.

Специальные шаблоны
-----------------

вики / default.txt
Этот шаблон используется для инициализации новых страниц. По умолчанию содержит заголовок с именем страницы и датой создания страницы.

вики / Journal.txt
Этот шаблон используется для инициализации новых страниц в пространстве имен журнала.

Пользовательская настройка
-----------

Шаблоны по умолчанию находятся в / usr / share / zim / templates / и ~ / .local / share / zim / templates. Вы можете добавить шаблоны, которые вы используете чаще там. Чтобы изменить шаблон, скопируйте его в каталог ~ / .local / ... и отредактируйте его.

Синтаксис шаблона:

[% var%] # интерполирует переменную
[% - var%] # + разрыв строки перед выражением
[% var -%] # + разрыв строки после выражения
[% - var -%] # + разрывы строк с обеих сторон

[% IF expr%] ... [% END%] # условия

[% IF expr%]
...
[% ELSIF expr%]
...
[% ELSE%]
...
[% КОНЕЦ %]

[% FOREACH name = var] # цикл
... [% название %] ...
[% КОНЕЦ %]

[% strftime ("% c")%] # текущая отметка времени
[% strftime ("% c", var)%] # дата из переменной


[% options.option_name = value%] # установить значение параметра option_name для value

[% page.properties ["Creation-Date"]%] # access dict


Для операторов IF и ELIF выражение может быть либо просто переменной, в этом случае оно вычисляется как логическое, либо выражением равенства с "==". Например, "[% IF page.name == 'foo'%]" понимается. Более сложные выражения не поддерживаются.

Доступные переменные:

zim.version # версия Zim
notebook.name # имя записной книжки
notebook.interwiki # interwiki ключ ноутбука, если есть

page.name # полное имя страницы
page.namespace # namespace
page.basename # последняя часть имени страницы
page.properties # dict со свойствами страницы
page.title # первый заголовок на странице или базовое имя
page.heading # первый заголовок на странице
page.body # содержимое страницы без заголовка
page.content # содержимое страницы, включая ведущий заголовок
page.has_links # Истинно, если на странице есть ссылки на другие страницы
page.links # список объектов страницы для страниц, связанных на этой странице
page.has_backlinks # True, если страница связана с другими страницами
page.backlinks # список объектов страницы для страниц, ссылающихся на эту страницу
page.has_attachments # True, если на странице есть вложения
page.attachments # список файловых объектов для вложений

# Эти специальные страницы имеют те же свойства, что и объект 'page'
pages.index # страница индекса, сгенерированная при экспорте
pages.home # домашняя страница
pages.next # следующая страница в индексе (если есть)
pages.previous # предыдущая страница в индексе (если есть)

options # dict, где могут быть установлены специфичные для формата опции


Файловые объекты, возвращаемые page.attachments, имеют следующие атрибуты:

file.path # (относительный) путь в виде строки
file.basename # имя файла
file.mtime # file mtime, для использования с strftime ()
file.size # размер файла в виде читаемой человеком строки


Доступные функции:

URL (ссылка)
Превращает ссылку ZIM или объект файла в URL

ресурс (имя файла)
Возвращает URL для ресурса шаблона (см. Ниже)

strftime (шаблон, дата)
Формат даты, см. Стандартную библиотеку для кодов

strfcal (шаблон, дата)
Форматировать номер недели, принимает:

% w для дня недели в зависимости от локали
% W для номера недели в зависимости от локали
% Y за год, к которому относится неделя

индекс страницы (пространство имен, свертывание, ignore_empty)
Создает индекс страницы для данного пространства имен или всей записной книжки

Пространство имен: начальный корень - по умолчанию верхний уровень (":")
свернуть: если TRUE видны только ветви, относящиеся к текущей странице, если FALSE видны все ветви - по умолчанию TRUE
ignore_empty: если TRUE пустые страницы игнорируются - по умолчанию TRUE.

Пример: меню (page.namespace, TRUE, FALSE)


Смотрите также плагин журнала для некоторых свойств, доступных для страниц журнала

### Ресурсы шаблонов
Чтобы добавить дополнительные файлы в шаблон, создайте папку с тем же именем, что и шаблон. Любые файлы в папке (такие как таблицы стилей, изображения, файлы JavaScript и т. Д.) Будут скопированы вместе, когда этот шаблон используется для экспорта данных в zim. Существует функция «ресурс (имя файла)» для ссылки на эти файлы в шаблоне.

Zim всегда включает некоторые изображения при экспорте для флажков, используемых в списках флажков. Для их настройки в этой папке должны быть ресурсы шаблонов с именем «флажок-box.png», «unchecked-box.png» и «xchecked-box.png».

Для веб-интерфейса ресурсы также могут содержать "favicon.ico", который будет служить значком сайта.

Backlinks: Plugins:Journal Plugins:Print to Browser Help Help:Config Files Help:Export Usage:Publishing