How to add custom css file to Sphinx? - python

How can I add a custom css file? The following config does not work:
# conf.py
html_static_path = ['_static']
html_theme = 'default'
html_theme_options = {
'cssfiles': ['_static/style.css']
}
Result:
$ make html
Running Sphinx v1.2.2
loading pickled environment... not yet created
building [html]: targets for 2 source files that are out of date
updating environment: 2 added, 0 changed, 0 removed
reading sources... [ 50%] help
reading sources... [100%] index
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents...
Theme error:
unsupported theme option 'cssfiles' given

A simpler way is to add this to your conf.py:
def setup(app):
app.add_css_file('css/custom.css') # may also be an URL
Then put the file into the _static/css/ folder.

You should be able to include custom css by extending the default sphinx theme. In your conf.py you would specify where your extension to the theme would be, such as.
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
Then in _templates you would create a extension to the default theme named 'layout.html' that would include your cssfiles such as.
{# layout.html #}
{# Import the layout of the theme. #}
{% extends "!layout.html" %}
{% set css_files = css_files + ['_static/style.css'] %}
See sphinx's documentation on templating for more information.

The options that you can configure via html_theme_options are theme-dependent. Check out the [options] section of your theme’s theme.conf to find out what is available.
On a global basis, though, you can define html_context in your conf.py to override the settings for css_files (and, for that matter, script_files too):
html_context = {
'css_files': ['_static/custom.css'],
}
(For reference, have a look at Sphinx’s builders.html.StandaloneHTMLBuilder.prepare_writing() and see how self.globalcontext gets populated there.)

I'm using Sphinx 3.2.
I was able to add some simple custom CSS by doing the following:
add this line in conf.py right under html_static_path = ['_static']:
html_css_files = ['css/custom.css']
go to docs/_static/ and add css/custom.css
add custom css to your file then $ make html
Source

Related

Auto-generate title from filename in Pelican

1. Summary
I can’t automatically generate the correct title from filenames of articles/pages.
For example, I can’t automatically generate metadata key title Kira Goddess from article Kira-Goddess.md
2. Argumentation
DRY, automation. I don’t want to manually write the title every time for each article and page if I can do it automatically.
An exception — files with words, that contain hyphens — “well-known”, “English-speaking”. In this case, I must explicitly specify title in the metadata of my articles. But words with hyphens are rare in filenames of my articles.
3. MCVE
3.1. Data
You can see it in my KiraTitleFromFilename branch of my repository for Pelican debugging.
pelicanconf.py:
"""MCVE."""
AUTHOR = 'Sasha Chernykh'
SITENAME = 'SashaPelicanDebugging'
SITEURL = '.'
PATH = 'content'
TIMEZONE = 'Europe/Moscow'
DEFAULT_LANG = 'en'
# [INFO] Use article name when preserve the slug:
# https://docs.getpelican.com/en/stable/settings.html#url-settings
SLUGIFY_SOURCE = 'basename'
# [INFO] Preserve case of article filename
SLUGIFY_PRESERVE_CASE = True
# [INFO] Get title from article filename:
# https://docs.getpelican.com/en/stable/settings.html#metadata
# https://github.com/getpelican/pelican/issues/2107
# https://github.com/getpelican/pelican/commit/2e82a53cdf3f1f9d66557850cc2811479d5bb645
FILENAME_METADATA = '(?P<title>.*)'
Kira-Goddess.md:
Date: 2020-09-24 18:57:33
Kira Goddess!
Another Pelican files generated by pelican-quickstart.
Simplified part of base.html:
<title>{{ article.title }}</title>
3.2. Steps to reproduce
See .travis.yml:
Run Pelican build:
pelican content -s pelicanconf.py --fatal warnings --verbose
Finding content of <title> tag:
grep -E "<title>.*</title>" output/Kira-Goddess.html
3.3. Behavior
3.3.1. Current
See Travis build:
<title>Kira-Goddess</title>
3.3.2. Desired
It would be nice, if:
<title>{{ article.title }}</title>
will transform to:
<title>Kira Goddess</title>
4. Not helped
In the description of EXTRA_PATH_METADATA variable I read, that Pelican used Python group name notation syntax (?P<name>…). I couldn’t find, how I can make substitutions in Python <class 'str'> (print(type(FILENAME_METADATA)) → <class 'str'>). I tried variants as:
import re
KIRA_DEFAULT_FILENAME_REGEX = '(?P<title>.*)'
FILENAME_METADATA = re.sub(KIRA_DEFAULT_FILENAME_REGEX, "-", " ")
or
KIRA_DEFAULT_FILENAME_REGEX = '(?P<title>.*)'
FILENAME_METADATA = KIRA_DEFAULT_FILENAME_REGEX.replace("-", "")
It doesn’t work.
5. Don’t offer
5.1. Use Jinja2 filters in templates
5.1.1. Suggestion
Use replace() filter in your template files like this:
<title>{{ article.title|replace('-', " ") }}</title>
5.1.2. Why is it not good
Pelican plugins (e.g. Pelican Open Graph) still will use article.title. Unwanted data as Kira-Goddess, not Kira Goddess still will pass to plugins.
5.2. Use spaces in your Markdown
5.2.1. Suggestion
For example, name your file Kira Goddess.md, not Kira-Goddess.md.
5.2.2. Why is it not good
Whitespaces in filenames is a bad practice — 1, 2, 3, 4, 5.
It seems like pelican doesn't provide a way to implement what you want.
FILENAME_METADATA regex can only select a name from a filename, but you can't substitute - with whitespaces there.
So I think the current best way for you is to specify title tag manually in each file.

Remove the word "module" from Sphinx documentation

Using Sphinx for documenting my Python project. I want to remove the word "module" which follows the name of each python file (in the navbar, TOC, the page title, etc).
e.g. Details:
The project is composed of 2 files utils.py and main.py.
In my index.rst file, I use:
.. toctree::
:maxdepth: 2
utils
main
to import both files as "modules". From the docs/ folder, I then call:
sphinx-apidoc -f -o ./source/ ..
make html
to generate the static site. In the site, the word "module" follows every file name, and I would like to remove it.
Sphinx 2.2 adds templating for the reST files generated by sphinx-apidoc.
Use the --templatedir option to set the path to a dir containing module.rst_t, package.rst_t and toc.rst_t files. The files can be created from the corresponding files in site-packages/sphinx/templates/apidoc.
Then, in package.rst_treplace
{{- [submodule, "module"] | join(" ") | e | heading(2) }}
with
{{- submodule | e | heading(2) }}
Repeat for module.rst_t.
One possible solution uses JS to find & replace the word "module" after the page loads:
Create a file source/_templates/layout.html with the following content:
{% extends "!layout.html" %}
{% block extrahead %}
<script type="text/javascript">
window.onload = function() {
document.body.innerHTML = document.body.innerHTML.replace(/ module/g, '');
}
</script>
{% endblock %}
Make sure that conf.py has templates_path = ['_templates'] set, then Sphinx will append the script to the <head> of all documentation pages, and voila!

Generate HTML from HTML template in python?

I want to design my own HTML template with tags like JSP or Jade and then pass data from python to it and let it generate full html page.
I don't want to construct document at python side like with DOM. Only data goes to page and page tempalte decides, how data lays out.
I don't want to serve resulting pages with HTTP, only generate HTML files.
Is it possible?
UPDATE
I found Jinja2, but I has strange boilerplate requirements. For example, they want me to create environment with
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml'])
)
while saying that package yourapplication not found. If I remove loader parameter, it complains on line
template = env.get_template('mytemplate.html')
saying
no loader for this environment specified
Can I just read template from disk and populate it with variables, without extra things?
Just use the FileSystemLoader:
import os
import glob
from jinja2 import Environment, FileSystemLoader
# Create the jinja2 environment.
current_directory = os.path.dirname(os.path.abspath(__file__))
env = Environment(loader=FileSystemLoader(current_directory))
# Find all files with the j2 extension in the current directory
templates = glob.glob('*.j2')
def render_template(filename):
return env.get_template(filename).render(
foo='Hello',
bar='World'
)
for f in templates:
rendered_string = render_template(f)
print(rendered_string)
example.j2:
<html>
<head></head>
<body>
<p><i>{{ foo }}</i></p>
<p><b>{{ bar }}</b></p>
</body>
</html>

Disable rendering some md and html files in Pelican

1. Briefly
I don't find, how I can to disable rendering some files with md and html extensions.
2. Detail
I use Pelican and write my articles use Markdown markup. For example, I want to create custom 404 page in GitHub Pages. I need to have 2 files in root directory of my site: 404.md and 404.html. I create these files in my content folder → I run pelican content command → I get output.
D:\Kristinita>pelican content
WARNING: Meta tag in file D:\Kristinita\content\404.html does not have a 'name' attribute, skipping. Attributes: http-equiv="X-UA-Compatible", content="IE=edge"
ERROR: Skipping .\404.md: could not find information about 'title'
3. Example of expected behavior
I set in pelicanconf.py:
NOT_RENDERING = ['404.md', '404.html']
I run pelican content → 404.md and 404.html files don't have modifications in output.
4. Did not help
I set in pelicanconf.py file:
STATIC_PATHS = ['']
Files with other extension, exclude md and html, copy to the output directory without modification, warnings and errors, but it no work for md and html files.
I use “hack” — I write extensions in UPPERCASE. For example, I create files 404.MD and 404.HTML files instead of 404.md and 404.html. But I don't get custom 404 page in GitHub Pages with UPPERCASE extensions.
I find OUTPUT_SOURCE setting in documentation → I set in pelicanconf.py:
OUTPUT_SOURCES = True
OUTPUT_SOURCES_EXTENSION = '.md'
I run pelican content command → I get error and warning in output, I don't get original 404.md in output. It don't solve my problem.
I would suggest moving those files into a separate directory within the content directory, e.g.:
content/
static/
404.html
404.md
Then you can configure Pelican to treat that directory as a static source:
STATIC_PATHS = [
'static',
]
and move the two files to the root of the output directory on processing:
EXTRA_PATH_METADATA = {
'static/404.html': {'path': '404.html'},
'static/404.md': {'path': '404.md'},
}
To make the processor ignore those files, per this GitHub issue, you will also need to set:
ARTICLE_EXCLUDES = [
'static'
]

Is flask-assets putting minified files in right directory?

I'm working to modify a cookiecutter Flask app. I'm working locally on WIN7 .
I've set up bower to install the front end dependencies under the static root by using a .bowerrc file in the document root containing:
{ "directory" : "myflaskapp/static/bower_components" }
This cookiecutter uses flask-assets to manage the project assets. Following https://adambard.com/blog/fresh-flask-setup/ I've modified myflaskapp/assets.py file :
from flask_assets import Bundle, Environment
import os
css = Bundle(
"libs/bootstrap/dist/css/spacelab/bootstrap.css",
"bower_components/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css",
"css/style.css",
"css/home.css",
filters="cssmin",
output="public/css/common.css"
)
js = Bundle(
"libs/jQuery/dist/jquery.js",
"libs/bootstrap/dist/js/bootstrap.js",
"bower_components/moment/moment.js",
"bower_components/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js",
"js/plugins.js",
filters='jsmin',
output="public/js/common.js"
)
assets = Environment()
assets.register("js_all", js)
assets.register("css_all", css)
The debug setting is set to false, meaning the assets should be compressed and minified.
Before I send a request:
After:
shouldn't the files go in static/public/css and static/public/js
This particular cookiecutter recipe has a public Blueprint that declares that its static files go into the static directory. I'm not sure why the author included empty static/public/{css,js} directories; they are probably just leftovers from an earlier stage of development and were neglected. I've removed the static/public directory in my instantiation of this recipe (well, a similar one with a similar problem) to no harm.

Categories