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.
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>
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'
]
I'm attempting to build a json document using Jinja2 and the document has a nested script. The script contains {{<variables>}} that I need to replace along with non-json characters. Therefore, the script needs to be json-escaped afterwards using json.dumps().
str = '{
"nestedScript" : {% include "scripts/sc.ps1" | json %}
}'
The escape function isn't enough, since the finished product contains characters that are valid HTML, but not JSON.
I'm thinking something along the lines of:
str = '{
"nestedScript" : {{ include("scripts/sc.ps1") | json}} %}
}'
using some a custom filter or something, but I can't seem to write the include function such that it also does variable replacement in the script. This is my script so far that I am including as a global:
Complete example
Folder structure:
.
└── templates
├── test.json
└── scripts
└── script.ps1
template-file:
test.json = '{
"nestedScript" : {{ include("scripts/script.ps1") | json}}
}'
Script:
loader = jinja2.FileSystemLoader("templates")
env = jinja2.Environment(loader=self.loader)
template = env.get_template("test.json")
template.render({
'service_name': 'worker',
'context_name': 'googlesellerratings',
})
result:
{
"nestedScript" : "echo {{service_name}}"
}
Solved this in a way that feels a little hackish, so I'd love some feedback. When instantiating my class, I defined a global function called include_script:
loader = jinja2.FileSystemLoader(templates_folder)
env = inja2.Environment(loader=self.loader)
env.globals['include_script'] = render_script_func(env)
the render_script_func returns a function that retrieves the context from the environment and uses it to render the file I referenced:
def render_script_func(env):
def render_script(name):
ctx = env.globals['context']
tmpl = env.get_template(name)
raw = tmpl.render(ctx)
return json.dumps(raw)
return render_script
Now, before rendering, all one has to do, is add the context for the rendering to the global context object:
template = env.get_template(template_name)
template.environment.globals["context"] = ctx
renderedData = template.render(ctx)
And when a template uses {{ include_script("path/to/script") }} the script is both rendered and then json encoded.
Still feels a bit wrong, but so be it.
Given the (incomplete) example it seems you are searching the filter tag.
First the script in a form that's actually runnable and defines a json filter in terms of json.dumps():
import json
import jinja2
loader = jinja2.FileSystemLoader('templates')
env = jinja2.Environment(loader=loader)
env.filters['json'] = json.dumps
template = env.get_template('test.json')
print(
template.render({
'service_name': 'worker',
'context_name': 'googlesellerratings',
})
)
The missing PowerShell script with characters that cause trouble if used as is in JSON ("):
echo "{{service_name}}"
Now the solution for the test.json template:
{
"nestedScript" : {% filter json %}{% include "scripts/script.ps1" %}{% endfilter %}
}
And finally the printed result:
{
"nestedScript" : "echo \"worker\""
}
In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a more elegant way of doing this?
You can use yattag to do this in an elegant way. FYI I'm the author of the library.
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('body'):
with tag('p', id = 'main'):
text('some text')
with tag('a', href='/my-url'):
text('some link')
result = doc.getvalue()
It reads like html, with the added benefit that you don't have to close tags.
I would suggest using one of the many template languages available for python, for example the one built into Django (you don't have to use the rest of Django to use its templating engine) - a google query should give you plenty of other alternative template implementations.
I find that learning a template library helps in so many ways - whenever you need to generate an e-mail, HTML page, text file or similar, you just write a template, load it with your template library, then let the template code create the finished product.
Here's some simple code to get you started:
#!/usr/bin/env python
from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django
# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""
t = Template(template)
c = Context({"title": "title from code",
"mystring":"string from code"})
print t.render(c)
It's even simpler if you have templates on disk - check out the render_to_string function for django 1.7 that can load templates from disk from a predefined list of search paths, fill with data from a dictory and render to a string - all in one function call. (removed from django 1.8 on, see Engine.from_string for comparable action)
If you're building HTML documents than I highly suggest using a template system (like jinja2) as others have suggested. If you're in need of some low level generation of html bits (perhaps as an input to one of your templates), then the xml.etree package is a standard python package and might fit the bill nicely.
import sys
from xml.etree import ElementTree as ET
html = ET.Element('html')
body = ET.Element('body')
html.append(body)
div = ET.Element('div', attrib={'class': 'foo'})
body.append(div)
span = ET.Element('span', attrib={'class': 'bar'})
div.append(span)
span.text = "Hello World"
if sys.version_info < (3, 0, 0):
# python 2
ET.ElementTree(html).write(sys.stdout, encoding='utf-8',
method='html')
else:
# python 3
ET.ElementTree(html).write(sys.stdout, encoding='unicode',
method='html')
Prints the following:
<html><body><div class="foo"><span class="bar">Hello World</span></div></body></html>
There is also a nice, modern alternative: airium: https://pypi.org/project/airium/
from airium import Airium
a = Airium()
a('<!DOCTYPE html>')
with a.html(lang="pl"):
with a.head():
a.meta(charset="utf-8")
a.title(_t="Airium example")
with a.body():
with a.h3(id="id23409231", klass='main_header'):
a("Hello World.")
html = str(a) # casting to string extracts the value
print(html)
Prints such a string:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8" />
<title>Airium example</title>
</head>
<body>
<h3 id="id23409231" class="main_header">
Hello World.
</h3>
</body>
</html>
The greatest advantage of airium is - it has also a reverse translator, that builds python code out of html string. If you wonder how to implement a given html snippet - the translator gives you the answer right away.
Its repository contains tests with example pages translated automatically with airium in: tests/documents. A good starting point (any existing tutorial) - is this one: tests/documents/w3_architects_example_original.html.py
I would recommend using xml.dom to do this.
http://docs.python.org/library/xml.dom.html
Read this manual page, it has methods for building up XML (and therefore XHTML). It makes all XML tasks far easier, including adding child nodes, document types, adding attributes, creating texts nodes. This should be able to assist you in the vast majority of things you will do to create HTML.
It is also very useful for analysing and processing existing xml documents.
Here is a tutorial that should help you with applying the syntax:
http://www.postneo.com/projects/pyxml/
I am using the code snippet known as throw_out_your_templates for some of my own projects:
https://github.com/tavisrudd/throw_out_your_templates
https://bitbucket.org/tavisrudd/throw-out-your-templates/src
Unfortunately, there is no pypi package for it and it's not part of any distribution as this is only meant as a proof-of-concept. I was also not able to find somebody who took the code and started maintaining it as an actual project. Nevertheless, I think it is worth a try even if it means that you have to ship your own copy of throw_out_your_templates.py with your code.
Similar to the suggestion to use yattag by John Smith Optional, this module does not require you to learn any templating language and also makes sure that you never forget to close tags or quote special characters. Everything stays written in Python. Here is an example of how to use it:
html(lang='en')[
head[title['An example'], meta(charset='UTF-8')],
body(onload='func_with_esc_args(1, "bar")')[
div['Escaped chars: ', '< ', u'>', '&'],
script(type='text/javascript')[
'var lt_not_escaped = (1 < 2);',
'\nvar escaped_cdata_close = "]]>";',
'\nvar unescaped_ampersand = "&";'
],
Comment('''
not escaped "< & >"
escaped: "-->"
'''),
div['some encoded bytes and the equivalent unicode:',
'你好', unicode('你好', 'utf-8')],
safe_unicode('<b>My surrounding b tags are not escaped</b>'),
]
]
I am attempting to make an easier solution called
PyperText
In Which you can do stuff like this:
from PyperText.html import Script
from PyperText.htmlButton import Button
#from PyperText.html{WIDGET} import WIDGET; ex from PyperText.htmlEntry import Entry; variations shared in file
myScript=Script("myfile.html")
myButton=Button()
myButton.setText("This is a button")
myScript.addWidget(myButton)
myScript.createAndWrite()
I wrote a simple wrapper for the lxml module (should work fine with xml as well) that makes tags for HTML/XML -esq documents.
Really, I liked the format of the answer by John Smith but I didn't want to install yet another module to accomplishing something that seemed so simple.
Example first, then the wrapper.
Example
from Tag import Tag
with Tag('html') as html:
with Tag('body'):
with Tag('div'):
with Tag('span', attrib={'id': 'foo'}) as span:
span.text = 'Hello, world!'
with Tag('span', attrib={'id': 'bar'}) as span:
span.text = 'This was an example!'
html.write('test_html.html')
Output:
<html><body><div><span id="foo">Hello, world!</span><span id="bar">This was an example!</span></div></body></html>
Output after some manual formatting:
<html>
<body>
<div>
<span id="foo">Hello, world!</span>
<span id="bar">This was an example!</span>
</div>
</body>
</html>
Wrapper
from dataclasses import dataclass, field
from lxml import etree
PARENT_TAG = None
#dataclass
class Tag:
tag: str
attrib: dict = field(default_factory=dict)
parent: object = None
_text: str = None
#property
def text(self):
return self._text
#text.setter
def text(self, value):
self._text = value
self.element.text = value
def __post_init__(self):
self._make_element()
self._append_to_parent()
def write(self, filename):
etree.ElementTree(self.element).write(filename)
def _make_element(self):
self.element = etree.Element(self.tag, attrib=self.attrib)
def _append_to_parent(self):
if self.parent is not None:
self.parent.element.append(self.element)
def __enter__(self):
global PARENT_TAG
if PARENT_TAG is not None:
self.parent = PARENT_TAG
self._append_to_parent()
PARENT_TAG = self
return self
def __exit__(self, typ, value, traceback):
global PARENT_TAG
if PARENT_TAG is self:
PARENT_TAG = self.parent