Поиск по блогу

воскресенье, 22 июня 2014 г.

Начинаем изучать Sphinx HTML theming support

Этот пост - классический конспект. Я читал страницу документации "HTML theming support" и разбирался с тем, где находятся "встроенные темы", каковы структура папок для тем... Потом я решил поискать варианты готовых тем, сначла, просто примеры, а потом и пакеты, нашел sphinx-bootstrap theme...

Тема bootstrap оказалась довольно сложной. Прежде, чем устанавливать ее под windows, я решил понять механизм работы скриптов.

Это абзац я вставил "задним числом" после того, как начал понимать последовательность:
1. Spinx Quick-start запускается из папки, в которой планируется разместить сайт (проект)..., но файл conf.py определяет все настройки проекта... и тему в том числе, не путать с conf.py в папке sphinx (с этим будем разбираться в другом месте!), а здесь только распечатаем пример конфигурационного файла встроенной темы theme.conf
2. После этого переходим в папку созданного проекта и запускаем оттуда **make html**. Именно этот скрипт создает подпапку **html** со всеми подпапками и файлами для статичного сайта (с отдельной подпапкой static для файов изображений, Css, jscript)
3. Понятие **template** используется для (задания блоков) макетирования страниц (о шаблонах поговорим в следующих постах), а **"HTML theming "** - это именно CSS.
HTML theming support - здесь есть описания встроеных тем, инструкции по созданию своих
Templating
sphinx-bootstrap-theme
Themes for Python Sphinx Documentation Projects
vkvn/sphinx-themes

Ниже примеры сайтов с интересными темами
Welcome to CodePy’s documentation! - главный кандидат на мой стиль
Documentation using the default theme
Темная полоса Меню наверху - открывающийся список
Светлая полоса Меню наверху - открывающийся список
Меню наверху, справа sidebar RSS
heapkeeper.org - примеры картинок и фреймворк для загрузки страниц
calibre is an ebook library manager
А вот рекомендации на другие темы:
Good examples of Python docstrings for Sphinx

Встроенные темы

Их довольно много, расположены они в отдельной папке ***. Именно из этих папок скрипт make html берет файлы из которых компонует файлы проекта.
In [3]:
!dir C:\Users\kiss\Anaconda\Lib\site-packages\sphinx\themes
 Volume in drive C has no label.
 Volume Serial Number is 6017-2A0B

 Directory of C:\Users\kiss\Anaconda\Lib\site-packages\sphinx\themes

16.02.2014  20:15    <DIR>          .
16.02.2014  20:15    <DIR>          ..
16.02.2014  20:15    <DIR>          agogo
16.02.2014  20:15    <DIR>          basic
16.02.2014  20:15    <DIR>          default
16.02.2014  20:15    <DIR>          epub
16.02.2014  20:15    <DIR>          haiku
16.02.2014  20:15    <DIR>          nature
16.02.2014  20:15    <DIR>          pyramid
16.02.2014  20:15    <DIR>          scrolls
16.02.2014  20:15    <DIR>          sphinxdoc
16.02.2014  20:15    <DIR>          traditional
               0 File(s)              0 bytes
              12 Dir(s)  396В 767В 879В 168 bytes free

In [2]:
!dir C:\Users\kiss\Anaconda\Lib\site-packages\sphinx\themes\default
 Volume in drive C has no label.
 Volume Serial Number is 6017-2A0B

 Directory of C:\Users\kiss\Anaconda\Lib\site-packages\sphinx\themes\default

16.02.2014  20:15    <DIR>          .
16.02.2014  20:15    <DIR>          ..
24.01.2014  19:52               371 layout.html
16.02.2014  20:15    <DIR>          static
24.01.2014  19:52               723 theme.conf
               2 File(s)          1В 094 bytes
               3 Dir(s)  396В 772В 978В 688 bytes free

In [1]:
!dir C:\Users\kiss\Anaconda\Lib\site-packages\sphinx\themes\default\static
 Volume in drive C has no label.
 Volume Serial Number is 6017-2A0B

 Directory of C:\Users\kiss\Anaconda\Lib\site-packages\sphinx\themes\default\static

16.02.2014  20:15    <DIR>          .
16.02.2014  20:15    <DIR>          ..
24.01.2014  19:52             5В 650 default.css_t
24.01.2014  19:52             5В 248 sidebar.js_t
               2 File(s)         10В 898 bytes
               2 Dir(s)  396В 778В 700В 800 bytes free

In [5]:
%load C:\\Users\\kiss\Anaconda\\Lib\\site-packages\\sphinx\\themes\\default\\theme.conf
In []:
[theme]
inherit = basic
stylesheet = default.css
pygments_style = sphinx

[options]
rightsidebar = false
stickysidebar = false
collapsiblesidebar = false
externalrefs = false

footerbgcolor    = #11303d
footertextcolor  = #ffffff
sidebarbgcolor   = #1c4e63
sidebarbtncolor  = #3c6e83
sidebartextcolor = #ffffff
sidebarlinkcolor = #98dbcc
relbarbgcolor    = #133f52
relbartextcolor  = #ffffff
relbarlinkcolor  = #ffffff
bgcolor          = #ffffff
textcolor        = #000000
headbgcolor      = #f2f2f2
headtextcolor    = #20435c
headlinkcolor    = #c60f0f
linkcolor        = #355f7c
visitedlinkcolor = #355f7c
codebgcolor      = #eeffcc
codetextcolor    = #333333

bodyfont = sans-serif
headfont = 'Trebuchet MS', sans-serif
Параметр "options" у дефолтной темы самый мощный. Нас интересует collapsiblesidebar rightsidebar...

Как использовать "сторонние темы"

If the theme does not come with Sphinx, it can be in two static forms:
either a directory (containing theme.conf and other needed files), or a zip file with the same contents.
Either of them must be put where Sphinx can find it;
for this there is the config value html_theme_path.
It gives a list of directories, relative to the directory containing conf.py, that can contain theme directories or zip files.
For example, if you have a theme in the file blue.zip, you can put it right in the directory containing conf.py and use this configuration:
In []:
html_theme = "blue"
html_theme_path = ["."]

В конце страницы документации есть руководствоCreating themes

As said, themes are either a directory or a zipfile (whose name is the theme name), containing the following:
A theme.conf file, see below. HTML templates, if needed.
A static/ directory containing any static files that will be copied to the output static directory on build. These can be images, styles, script files.
The theme.conf file is in INI format [1] (readable by the standard Python ConfigParser module) and has the following structure:
In []:
[theme]
inherit = base theme
stylesheet = main CSS name
pygments_style = stylename

[options]
variable = default value

Static templates

Из папок тем static (C:-packages) берутся файлы, оканчивающиеся на ** _t**, парсятся и вставляются в папки конкретных сборок сайтов... как правило: build/html/static
Чем файл default.css_t отличается от обычного файла стилей? Как видно из фрагментоы ниже, в этом файле используется импорт (обычного CSS)вида @import url("basic.css"); ... кроме того встречаются "необычные" строки-условия типа {%- if theme_rightsidebar|tobool %}
In []:
/*
 * default.css_t
 * ~~~~~~~~~~~~~
 *
 * Sphinx stylesheet -- default theme.
 *
 * :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
 * :license: BSD, see LICENSE for details.
 *
 */

@import url("basic.css");

/* -- page layout ----------------------------------------------------------- */

body {....
....      
In []:
...
div.body {
    background-color: {{ theme_bgcolor }};
    color: {{ theme_textcolor }};
    padding: 0 20px 30px 20px;
}

{%- if theme_rightsidebar|tobool %}
div.bodywrapper {
    margin: 0 {{ theme_sidebarwidth|toint }}px 0 0;
}
{%- endif %}

div.footer {
...


Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий