Search code examples
django-cms

django-cms string replacement on output


For some django-cms site, I want to replace each occurrence of a fixed string (namely two stars in a row: "**") by another fixed string on output. When editing, it must remain the original string. The idea is, to have a very short tag for frequent use.

How can I achieve this?


Solution

  • This can be done with a Middleware:

    pattern = "**"
    replacement = """<span class="gender" title="some explanation">*</span>"""
    
    class SubstituteMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            response = self.get_response(request)
            if hasattr(response,"content"):
                response.content = response.content.replace(pattern,replacement)
            return response
    
    • Modify pattern and replacement according to your needs.
    • Place this code into <yoursite>/middleware/sub.py (add directory middleware with empty __init__.py if not yet present)
    • Add <yoursite>.middleware.sub.SubstituteMiddleware to the MIDDLEWARE-list in settings.py

    Note that this approach is deficient in that it replaces not only content, but also accidentally matching parts of the HTML-code.