Files
postbot/app/bots/editor/template.py

50 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Модуль для работы с шаблонами."""
from __future__ import annotations
from typing import Dict, Any
from app.db.session import async_session_maker
from app.models.templates import Template
async def render_template_by_name(
name: str,
template_vars: Dict[str, Any],
context: Dict[str, Any],
) -> Dict[str, Any]:
"""Рендеринг шаблона по имени.
Args:
name: Имя шаблона
template_vars: Переменные для подстановки
context: Дополнительный контекст
Returns:
Отрендеренные данные для поста
Raises:
ValueError: Если шаблон не найден
"""
async with async_session_maker() as session:
stmt = Template.__table__.select().where(Template.__table__.c.name == name)
result = await session.execute(stmt)
template = result.scalar_one_or_none()
if not template:
raise ValueError(f"Шаблон {name} не найден")
text = template.content
keyboard = template.keyboard_tpl
# Подстановка переменных
for key, value in template_vars.items():
text = text.replace(f"{{${key}}}", str(value))
# Подготовка данных для отправки
return {
"type": template.type,
"text": text,
"keyboard": keyboard,
"parse_mode": template.parse_mode
}