【问题标题】:Slight issue parsing text into html将文本解析为 html 的小问题
【发布时间】:2017-11-28 14:58:51
【问题描述】:

嗯,这可能很简单,但也可能很复杂。我在 Django 框架中设置 SEO 友好的 Twitter 提要时遇到问题。大部分繁重的工作都是作为模板标签 blog_tags.py 文件完成的,如下所示:

@register.inclusion_tag('blog/frame/twitter.html')
def show_latest_tweets():
    tweets = []

    try:
        """The import error is here to catch any server migrations were the tweepy package not to be found in site_packages"""
        import tweepy
    except:
        tweets.append({'status': 'There was a problem referencing our tweets. Please inform our webmaster.', 'relative_date': 'Just now'})
        raise ImportError

    # OAuth process, using the keys and tokens
    auth = tweepy.OAuthHandler(settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_KEY'], settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_SECRET'])
    auth.set_access_token(settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_ACCESS_TOKEN'], settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_ACCESS_TOKEN_SECRET'])

    # Creation of the actual interface, using authentication
    api = tweepy.API(auth)

    user = 'FFXVEN'

    avatar_url = api.get_user(screen_name='@'+user).profile_image_url

    i = 0
    for tweet in tweepy.Cursor(api.user_timeline, screen_name='@'+user).items():
        if 'RT' not in tweet.text:
            if i <= 4:
                status = tweet.text
                hashtags = [word for word in status.split() if word[0] == "#"]

                #Find hashtags in tweet and create a string to contain <a href="https://twitter.com/search?q=" + hashtag>#hashtag</a>
                for hashtag in hashtags:
                    if hashtag.endswith((',',';','.')):
                        hashtag = hashtag[:-1]

                    status = status.replace(hashtag, '<a href="https://twitter.com/search?q={}">{}</a>'.format(hashtag[1:], hashtag))

                relative_date = tweet.created_at
                tweets.append({'user': user, 'avatar_url': avatar_url, 'status': html.unescape(status), 'relative_date': relative_date})
                i += 1
            else:
                break
        else:
            continue

    return { "tweets": tweets }

一切正常 - 它返回我想要的所有内容,目前它会删除主题标签并用 Twitter 友好的主题标签替换它们。但是,客户端显示的是:

我不知道如何工作,以便客户端将 html 元素呈现为 html 元素而不是预先格式化的文本?

【问题讨论】:

  • 在你展示的地方显示你的模板
  • 推文循环中的推文标准,其中 {{ tweet.status }} 变量显示在

    标记中。

标签: python html django twitter html-parsing


【解决方案1】:
{{ tweet.status|safe }

试试安全模板过滤器

【讨论】:

  • 太棒了 - 会试试这个。
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 2015-06-06
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
相关资源
最近更新 更多