2014-12-29 3 views
3
내가 템플릿에 표시하고 싶은 장고 모델에 저장된 URL이

을 사용하는 경우에만 URL 도메인을 표시합니다,하지만 난 단지 같은 도메인 표시 할 것 :가장 좋은 방법은 jinja2

ORIGINAL_URL :

https://wikipedia.org/wiki/List_of_chemical_process_simulators 

표시 :

wikipedia.org/... 

가 완전히 백엔드, 글꼴 엔드, 또는 jinja2와의 사용자 정의 기능을이에 처리하는 것이 더 있을까?

답변

3

나중에 프로젝트에서 템플릿에서 재사용 할 것이고 꽤 간단한 로직이 포함되어 있다고 가정하면 custom template filter을 정의하면 여기에서 완벽하게 괜찮습니다.

사용 urlparse.urlparse()는 도메인 이름을 얻을 수 있습니다 :.

>>> from urlparse import urlparse 
>>> from jinja2 import Environment, Template 
>>> 
>>> def get_domain(url): 
...  return "%s/..." % urlparse(url).netloc 
... 
>>> 
>>> env = Environment() 
>>> env.filters['domain'] = get_domain 
>>> 
>>> template = env.from_string('{{ url|domain }}') 
>>> template.render(url='https://wikipedia.org/wiki/List_of_chemical_process_simulators') 
u'wikipedia.org/...' 

이 간단한 예입니다, 당신은 추가로 전달 된 URL을 구문 분석 실패 할 경우 urlparse()의 오류 처리 메커니즘을 제공한다을

2

을 가장 좋은 방법은 아마도 @alecxe에 의해 답변 된 사용자 정의 템플릿 필터 일 것이지만, 할 수없는 경우에는 나중에 참조 할 수있는 바보 같은 방법이 아닙니다.

{{ original_url.rpartition("//")[-1] }} 
  • https://wikipedia.org/wiki/List_of_chemical_process_simulators → wikipedia.org/wiki/List_of_chemical_process_simulators
  • //example.net/path/to/file → example.net/path/to/file
  • ftp://example.net/pub → example.net/pub

바로 도메인 이름 (호스트 이름) 가져 오기 :

{{ original_url.rpartition("//")[-1].partition("/")[0] }} 
    을 0
  • https://wikipedia.org/wiki/List_of_chemical_process_simulators → wikipedia.org
  • //example.net/path/to/file → example.net
  • ftp://example.net/pub → example.net