Best way to display only domain url using jinja2

I have URLs stored in a Django model that I would like to display on a template, but I would like to display this domain like this:

original_url:

https://wikipedia.org/wiki/List_of_chemical_process_simulators

      

:

wikipedia.org/...

      

Would it be better to handle this entirely in the back-end, font-end, or custom function using jinja2?

+3


source to share


2 answers


If this is something that you will later reuse in templates throughout the project and given that there is some pretty simple logic defining a custom template filter would be perfectly fine here.

Use urlparse.urlparse()

to get your domain name:



>>> 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/...'

      

This is a simple example, you should additionally provide an error handling mechanism in case urlparse()

it cannot parse the passed URL.

+3


source


The best way would probably be the custom templates filter that @alecxe answered, but in case you don't, this is a counterintuitive way for future reference.

{{ 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



Get only domain name (hostname):

{{ original_url.rpartition("//")[-1].partition("/")[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

+2


source







All Articles