~homeworkprod/byceps

cbe76f8b7c222fa26b883c143300b064fd8ee668 — Jochen Kupperschmidt 1 year, 8 months ago ba269fc
Render news item body in view function, not in template

This provides a chance to add clean handling of errors that occur while
rendering the body.

Replacing the raw body with the rendered one is not very clean, but
somewhat nicely saves from introducing a custom sub-dataclass with an
additional field.
M byceps/blueprints/admin/news/templates/admin/news/item_view_version.html => byceps/blueprints/admin/news/templates/admin/news/item_view_version.html +1 -1
@@ 80,7 80,7 @@

  <h1>{{ version.title }}</h1>

{{ render_body(version.body)|safe }}
{{ rendered_body|safe }}

{%- endblock %}


M byceps/blueprints/admin/news/views.py => byceps/blueprints/admin/news/views.py +3 -1
@@ 130,10 130,12 @@ def item_view_version(version_id):
    channel = version.item.channel
    brand = brand_service.find_brand(channel.brand_id)

    rendered_body = news_item_service.render_body(version.body)

    return {
        'version': version,
        'brand': brand,
        'render_body': news_item_service.render_body,
        'rendered_body': rendered_body,
    }



M byceps/blueprints/news/templates/news/_item.html => byceps/blueprints/news/templates/news/_item.html +1 -1
@@ 11,6 11,6 @@
    {%- endif %}
  </footer>
  <div class="body">
{{ render_body(item.body)|safe }}
{{ item.body|safe }}
  </div>
</article>

M byceps/blueprints/news/views.py => byceps/blueprints/news/views.py +12 -4
@@ 6,6 6,8 @@ byceps.blueprints.news.views
:License: Modified BSD, see LICENSE for details.
"""

import dataclasses

from flask import abort, g

from ...services.news import service as news_service


@@ 39,10 41,14 @@ def index(page):
        channel_id, page, items_per_page, published_only=published_only
    )

    replacement_items = [
        _replace_body_with_rendered_body(item) for item in items.items
    ]
    items.items = replacement_items

    return {
        'items': items,
        'page': page,
        'render_body': _render_body,
    }




@@ 60,9 66,10 @@ def view(slug):
    if item is None:
        abort(404)

    item = _replace_body_with_rendered_body(item)

    return {
        'item': item,
        'render_body': _render_body,
    }




@@ 92,5 99,6 @@ def _may_view_drafts(user):
    return user.has_permission(NewsItemPermission.view_draft)


def _render_body(raw_body):
    return news_service.render_body(raw_body)
def _replace_body_with_rendered_body(item):
    rendered_body = news_service.render_body(item.body)
    return dataclasses.replace(item, body=rendered_body)