dnd/deadsands/site_tools/content_manager.py

49 lines
1.6 KiB
Python
Raw Normal View History

2022-08-02 18:20:45 -07:00
import datetime
from jinja2 import Environment, FileSystemLoader
from pathlib import Path
from pelican.writers import Writer
from pelican.utils import slugify, sanitised_join
2022-08-02 22:40:49 -07:00
from site_tools import SETTINGS
2022-08-02 18:20:45 -07:00
def create(content_type: str, title: str, template_dir: str,
2023-05-13 13:24:43 -07:00
category: str = None, source: str = None, template: str = None,
extra_context: dict = {}) -> str:
2022-08-02 18:20:45 -07:00
"""
Return the path to a new source file.
"""
2022-08-02 22:49:01 -07:00
base_path = Path.cwd()
2022-08-02 18:20:45 -07:00
def _slugify(s):
return slugify(s, regex_subs=SETTINGS['SLUG_REGEX_SUBSTITUTIONS'])
template_path = Path(template_dir)
2023-06-11 21:33:56 -07:00
template_name = f"{template or content_type}.md"
2022-08-02 18:20:45 -07:00
if not (template_path / template_name).exists():
2023-06-11 21:33:56 -07:00
print(f"Expected template {template_name} not found. Using default markdown template.")
2022-08-02 18:20:45 -07:00
template_name = 'default.md'
2022-08-06 21:22:47 -07:00
env = Environment(
2022-08-02 18:20:45 -07:00
loader=FileSystemLoader(template_path),
trim_blocks=True,
2022-08-06 21:22:47 -07:00
)
env.add_extension('site_tools.extensions.RollTable')
template_source = env.get_template(template_name)
2022-08-02 18:20:45 -07:00
target_filename = _slugify(title) + '.md'
relpath = Path(slugify(category)) if category else ''
target_path = base_path / SETTINGS['PATH'] / relpath
dest = sanitised_join(str(target_path / target_filename))
SETTINGS['WRITE_SELECTED'].append(dest)
writer = Writer(target_path, settings=SETTINGS)
writer.write_file(name=target_filename, template=template_source, context={
'title': title,
'tags': content_type,
'date': datetime.datetime.now(),
2023-05-13 13:24:43 -07:00
'filename': str(relpath / target_filename),
**extra_context
2022-08-02 18:20:45 -07:00
})
return dest