diff --git a/src/turbo_helper/templatetags/turbo_helper.py b/src/turbo_helper/templatetags/turbo_helper.py index ab17f7e..5f68f79 100644 --- a/src/turbo_helper/templatetags/turbo_helper.py +++ b/src/turbo_helper/templatetags/turbo_helper.py @@ -1,9 +1,11 @@ from typing import Any, Optional from django import template +from django.core.exceptions import ValidationError from django.db.models.base import Model from django.template import Node, TemplateSyntaxError, engines from django.template.base import token_kwargs +from django.utils.html import format_html from django.utils.safestring import mark_safe register = template.Library() @@ -228,3 +230,19 @@ def turbo_stream_from_tag(parser, token): stream_name_array = [parser.compile_filter(bit) for bit in remaining_bits] return TurboStreamFromTagNode(stream_name_array) + + +@register.simple_tag +def turbo_refreshes_with(method='replace', scroll='reset') -> str: + valid_methods = ['replace', 'morph'] + valid_scrolls = ['reset', 'preserve'] + + if method not in valid_methods: + raise ValidationError(f"Invalid refresh option '{method}'") + if scroll not in valid_scrolls: + raise ValidationError(f"Invalid scroll option '{scroll}'") + + meta_tags = f'' + meta_tags += f'' + + return format_html(meta_tags) diff --git a/tests/test_tags.py b/tests/test_tags.py index b30713c..78b8035 100644 --- a/tests/test_tags.py +++ b/tests/test_tags.py @@ -1,4 +1,5 @@ import pytest +from django.core.exceptions import ValidationError from django.template import Context, Template from tests.testapp.models import TodoItem @@ -131,3 +132,37 @@ def test_dom_id_variable(self): output == '' ) + + +class TestRefreshesWith: + def test_turbo_refreshes_with_tag(self): + template = """ + {% load turbo_helper %} + + {% turbo_refreshes_with method='replace' scroll='reset' %} + """ + + output = render(template, {}).strip() + + expected_method_tag = '' + expected_scroll_tag = '' + + assert expected_method_tag in output + assert expected_scroll_tag in output + + def test_invalid_options(self): + with pytest.raises(ValidationError): + template = """ + {% load turbo_helper %} + + {% turbo_refreshes_with method='invalid' scroll='reset' %} + """ + output = render(template, {}).strip() + + with pytest.raises(ValidationError): + template = """ + {% load turbo_helper %} + + {% turbo_refreshes_with method='replace' scroll='invalid' %} + """ + output = render(template, {}).strip()