Reputation: 5835
I have a site with a bunch of 'Projects' which often refer to each other in their descriptions (stored in a TextField). Rather than hard-coding the links between projects in their descriptions, I'd like to keep things DRY by referring to them using some sort of token, for example, in the description field:
Blabla text describing this project, this project was inspired by
{{ project "ProjectB"}} and lead to the development of {{ project "ProjectC" }}.
Which is then processed and turned in to:
Blabla text describing this project, this project was inspired by
<a href="/projects/ProjectB">ProjectB</a> and lead to the development
of <a href="/projects/ProjectC">ProjectC</a>.
To be clear: the description is free text which can contain none to many references to other items as hyperlinks at various points in the text. In a CMS this effect is usually achieved through some way to link to items by node/object ID - so that if the link changes, the reference can still be followed.
I've considered:
Has anyone done anything similar? What would you suggest?
Upvotes: 1
Views: 766
Reputation: 335
I just answered a similar question on SO, and it seems like it might solve your problem as well (if by chance you're still looking for an answer three years later).
I wrote a template filter to parse the custom internal link format in the Textfield before display. I'm using Markdown to parse my textfields, so I made the links return in Markdown format, but they could easily be written as HTML instead.
Update: I posted a revised version on djangosnippets.org that resolves internal links inside a markdown-formatted link, as well as on their own.
Upvotes: 2
Reputation: 1217
if I got your problem, you should use a custom template processor to pass a dictionary to your templates: in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"myapp.myprocessor.foo",
)
in myapp/myprocessor.py:
from django import template
def foo(request):
ProjectA = get_Project_from_database
t = template.Template(ProjectA.html)
c = template.Context({'name': ProjectA.name})
rendered_ProjectA = t.render(c)
return { 'rendered_ProjectA': rendered_ProjectA }
or if you don't wanna use Django template system you can use regular expressions (import re)
Upvotes: 0