from django import template
from django.utils.safestring import mark_safe

register = template.Library()


@register.simple_tag
def render_field(field, **attrs):
    """Render a bound field with temporary widget attributes.

    Usage in template:
      {% render_field form.username class="form-control" placeholder="Email" %}

    This updates the widget attrs just for the duration of rendering and
    restores the original attrs afterwards to avoid side effects.
    """
    try:
        widget = field.field.widget
    except Exception:
        return ""

    # preserve original attrs and update temporarily
    original_attrs = widget.attrs.copy()
    # Convert all attr values to strings (template passes them as strings)
    for k, v in attrs.items():
        widget.attrs[str(k)] = str(v)

    rendered = field.as_widget()

    # restore original attrs
    widget.attrs = original_attrs

    return mark_safe(rendered)
