Browse Source

Глобальные функции превращены в фильтры jinja2 [closes #40]

master
Касимов 1 year ago
parent
commit
b390539eac
6 changed files with 34 additions and 41 deletions
  1. +3
    -1
      flatfilecms/__init__.py
  2. +4
    -20
      flatfilecms/events.py
  3. +23
    -7
      flatfilecms/filters.py
  4. +2
    -2
      flatfilecms/templates/blogposts.jinja2
  5. +2
    -2
      flatfilecms/templates/header.jinja2
  6. +0
    -9
      tests/test_events.py

+ 3
- 1
flatfilecms/__init__.py View File

@@ -11,7 +11,9 @@ def main(global_config, **settings):
default_jinja2_filters = """markdown = flatfilecms.filters:markdown2html
fileglob = flatfilecms.filters:fileglob
merge_dict = flatfilecms.filters.merge_dict
join_url = flatfilecms.filters.join_url"""
join_url = flatfilecms.filters.join_url
format_date = flatfilecms.filters.format_date
format_datetime = flatfilecms.filters.format_datetime"""
settings['jinja2.filters'] = default_jinja2_filters + settings.get(
'jinja2.filters', '')



+ 4
- 20
flatfilecms/events.py View File

@@ -1,36 +1,20 @@
from babel import dates
from datetime import date
from functools import partial

from pyramid.events import subscriber
from pyramid.events import BeforeRender

from .models import load_yaml


@subscriber(BeforeRender)
def add_global(event):
event['globals'] = {
'format_date':
partial(dates.format_date, locale=event['request'].locale_name),
'format_datetime':
partial(dates.format_datetime, locale=event['request'].locale_name),
'today':
date.today(),
}


@subscriber(BeforeRender)
def add_data(event):
try:
event['data'] = load_yaml('globals.yaml', True)
event["data"] = load_yaml("globals.yaml", True)
except FileNotFoundError:
event['data'] = {}
event["data"] = {}


@subscriber(BeforeRender)
def add_menu(event):
try:
event['menu'] = load_yaml('menu/default.yaml', True)
event["menu"] = load_yaml("menu/default.yaml", True)
except FileNotFoundError:
event['menu'] = []
event["menu"] = []

+ 23
- 7
flatfilecms/filters.py View File

@@ -1,3 +1,5 @@
from babel import dates

from jinja2 import contextfilter, Markup
import markdown
from pathlib import Path
@@ -7,7 +9,7 @@ from markdown.blockprocessors import BlockProcessor

class Jinja2Processor(BlockProcessor):
def test(self, parent, block):
return block.startswith('{%') or block.startswith('{{')
return block.startswith("{%") or block.startswith("{{")

def run(self, parent, blocks):
block = blocks.pop(0)
@@ -27,17 +29,19 @@ class Jinja2Processor(BlockProcessor):

class IgnoreExtension(Extension):
def extendMarkdown(self, md, md_globals):
md.parser.blockprocessors.add('jinja2', Jinja2Processor(md.parser),
">hashheader")
md.parser.blockprocessors.add(
"jinja2", Jinja2Processor(md.parser), ">hashheader"
)


@contextfilter
def markdown2html(context, text, render=True):
result = markdown.markdown(
text,
extensions=[IgnoreExtension(), 'markdown.extensions.extra'],
output_format='html5',
tab_length=2)
extensions=[IgnoreExtension(), "markdown.extensions.extra"],
output_format="html5",
tab_length=2,
)
if render:
result = context.environment.from_string(result).render(context)
if context.eval_ctx.autoescape:
@@ -56,4 +60,16 @@ def fileglob(path, root):


def join_url(a, b):
return a.rstrip('/') + '/' + b.lstrip('/')
return a.rstrip("/") + "/" + b.lstrip("/")


@contextfilter
def format_date(context, *args, **kwargs):
kwargs.setdefault("locale", context["request"].locale_name)
return dates.format_date(*args, **kwargs)


@contextfilter
def format_datetime(context, *args, **kwargs):
kwargs.setdefault("locale", context["request"].locale_name)
return dates.format_datetime(*args, **kwargs)

+ 2
- 2
flatfilecms/templates/blogposts.jinja2 View File

@@ -11,8 +11,8 @@
<a href="{{item[0]}}" class="btn btn-primary">Читать</a>
</div>
<div class="card-footer"><small class=text-muted">
Опубликовано {{globals.format_date(item[1].page['published'], format='long')}}
{%- if item[1].page['updated'] %}, обновлено {{globals.format_date(item[1].page['updated'], format='long')}}{% endif %}
Опубликовано {{item[1].page['published']|format_date('long')}}
{%- if item[1].page['updated'] %}, обновлено {{item[1].page['updated']|format_date('long')}}{% endif %}
</small></div>
</div>
{% endfor %}


+ 2
- 2
flatfilecms/templates/header.jinja2 View File

@@ -56,8 +56,8 @@
<h1 class="page-title">{{title}}</h1>
{%- if description %}<p class="page-lead">{{description}}</p>{% endif %}
<div class="row">
{%- if published %}<p class="col-6 col-sm-4 col-md-3"><i class="fas fa-calendar-day"></i> {{globals.format_date(published, format='long')}}</p>{% endif %}
{%- if updated %}<p class="col-6 col-sm-4 col-md-3"><i class="fas fa-edit"></i> {{globals.format_date(updated, format='long')}}</p>{% endif %}
{%- if published %}<p class="col-6 col-sm-4 col-md-3"><i class="fas fa-calendar-day"></i> {{published|format_date('long')}}</p>{% endif %}
{%- if updated %}<p class="col-6 col-sm-4 col-md-3"><i class="fas fa-edit"></i> {{updated|format_date('long')}}</p>{% endif %}
</div>
</div>
</div>

+ 0
- 9
tests/test_events.py View File

@@ -1,12 +1,3 @@
def test_globals(fake_request):
from flatfilecms.events import add_global
event = {'request': fake_request}
add_global(event)
assert 'globals' in event
assert 'format_date' in event['globals']
assert 'format_datetime' in event['globals']


def test_data(config):
from flatfilecms.events import add_data
event = {}