开发者

django 'urlize' strings form text just like twitter

开发者 https://www.devze.com 2022-12-31 13:57 出处:网络
heyy there i want to parse a text,let\'s name it \'post\', and \'urlize\' some strings if they contain a particular character, in a particular position.

heyy there

i want to parse a text,let's name it 'post', and 'urlize' some strings if they contain a particular character, in a particular position.

my 'pseudocode' trial would look like that:

 def urlize(post)
      for string in开发者_运维问答 post
      if string icontains ('#')
      url=(r'^searchn/$',
                    searchn,
                    name='news_searchn'),
     then apply url to the string
     return urlize(post)

i want the function to return to me the post with the urlized strings, where necessary (just like twitter does).

i don't understand: how can i parse a text, and search for certain strings? is there ok to make a function especially for 'urlizing' some strings? The function should return the entire post, no matter if it has such kind of strings. is there another way Django offers? Thank you


First, I guess you mostly need this function in templates (you want to present the post "urlized").

There's the built-in template tag urlize, which is used like

{{ value|urlize }}

which takes a string value and returns it with links.

If you want to customize the logic, you can create your own template tag.

EDIT:
To find the # words you can use a simple regex search:

import re
a = "hello #world. foo #bar! #foo_bar"
re.findall("#(\w+)",a)

>> ['world', 'bar', 'foo_bar']
0

精彩评论

暂无评论...
验证码 换一张
取 消