python - mentions/internal links in Django -
i have bunch of models. these models has method get_absolute_url
, field text
. want create internal links in text
field wikipedia does.
wikipedia's internal links in pages refer other pages. need link models.
i create pattern internal links , replacing pattern hardcoded url url it's not thought because links can change. best if refer get_absolute_url
.
another alternative utilize template tag alter specific pattern links.
how should done? there open source projects in has been done?
i wanted reply same problem few days ago, , did template filter. links relative urls, not absolute, tweak pretty easily, , tweak regex pattern match whatever link markup prefer.
using filter, link looked @ display time, if view's url has changed, should automatically update reverse()
lookup.
i utilize markdown process description fields, create link homecoming markdown-formatted link instead of html, tweak too. if utilize markdown, you'd want set filter first.
so display description textfield internal links, in template this:
{{ entity.description|internal_links|markdown }}
(see django docs on writing own custom filters more details on writing , registering filters.)
as specific filter itself, did this:
from django import template django.core.urlresolvers import reverse my.views import * register = template.library() @register.filter def internal_links(value): """ takes markdown textfield, , filters internal links in format: {{film:alien-1979}} ...where "film" designation link type (model), , "alien-1979" slug given object note: process before markdown, resolve markdown-formatted linked name: [alien](http://opticalpodcast.com/cinedex/film/alien-1979/) :param value: :return: """ try: import re pattern = '{{\s+:\s+}}' p = re.compile(pattern) #replace captured pattern(s) markdown link homecoming p.sub(localurl, value) except: # if link lookup fails, display original text homecoming value def localurl(match): string = match.group() # strip off {{ , }} string = string[2:-2] # separate link type , slug link_type, link_slug = string.split(":") link_view = '' # figure out view need display # link type if(link_type == 'film'): link_view = 'film_detail' elif(link_type == 'person'): link_view = 'person_detail' else: raise exception("unknown link type.") link_url = reverse(link_view, args=(link_slug,)) entity = get_object_or_404(entity, slug=link_slug) markdown_link = "[" + entity.name + "](" + link_url + ")" homecoming markdown_link
python django django-templates django-views
No comments:
Post a Comment