"""Template filters for tarot card rendering."""
from django import template
from django.utils.html import escape
from django.utils.safestring import mark_safe

register = template.Library()


@register.filter(name='italicize')
def italicize(text, word):
    """Wrap every occurrence of `word` in `text` with <em>...</em>.

    Both `text` and `word` are escape()d before splicing the <em> in, so the
    output is safe to mark `mark_safe` regardless of input.
    """
    if not text or not word:
        return text
    text = str(text)
    word = str(word)
    if word not in text:
        return text
    safe_text = escape(text)
    safe_word = escape(word)
    return mark_safe(safe_text.replace(safe_word, '<em>{}</em>'.format(safe_word)))
