在 Django 项目中,需要在模板中添加元关键字(meta keywords),但使用以下代码却未能成功:
@template_render("mysite/category.html")
def category(request, slug):
slug = slug.lower()
product_type = local_settings.CATEGORY_NAME_TO_ID.get(slug, False)
if not product_type:
raise Http404
products = models.Product.objects.active().filter(product_type = product_type).all()
return { 'products' : products, 'slug' : slug, 'key':'wholesale ipad, ipad with retina display, ipad mini, ipad 3, ipad 2',}
在模板文件中,使用以下代码:
{% extends "base.html"%}
{%load appletrade_tags%}
{% block key %}siteTrade - {{key}}{% endblock %}
{%block title%}site Trade - {{slug}}{%endblock%}
在查看页面源代码时,发现并没有添加元关键字,但标题却可以正常显示。
2、解决方案
方法一:使用 render_to_response
函数
在视图函数中,使用 render_to_response
函数来传递上下文数据给模板,如下所示:
from django.shortcuts import render_to_response
def category(request, slug):
slug = slug.lower()
product_type = local_settings.CATEGORY_NAME_TO_ID.get(slug, False)
if not product_type:
raise Http404
products = models.Product.objects.active().filter(product_type = product_type)
context = {
'slug': slug,
'products': products,
'key': 'wholesale ipad, ipad with retina display, ipad mini, ipad 3, ipad 2',
}
return render_to_response('appletrade/category.html', context, context_instance=RequestContext(request))
方法二:使用自动生成元关键字的函数
为了方便地为页面生成元关键字,可以编写一个函数来从模板文件中提取关键词,并返回关键词列表,如下所示:
# meta_gen.py
# create meta keywords for webpage automagically
# MIT License
# Author: Daniel P. Clark 6ftdan@gmail.com
import collections, string, StringIO, re
from django.utils.html import strip_tags
# Counts words in template files and insert keywords into page
word_count_min = 2
word_length_min = 4
nogo_list = [] # Optional list of words you may not want as meta tags.
# meta_keywords ( html string ) =>
# returns non html keyword list, as a comma seperated string,
# for words fitting qualifications as chosen above.
def meta_keywords(str_file):
c = collections.Counter()
strIO_Obj = StringIO.StringIO(str_file)
for line in strIO_Obj.readlines():
c.update(re.findall(r"[\w']+", strip_tags(line).lower()))
wordlist = []
for word, count in c.most_common():
if len(word) > (word_length_min-1) and count > (word_count_min-1) and word not in nogo_list: wordlist.append(word)
return string.join(wordlist, ',')
在每个视图函数中,添加以下代码:
from project.meta_gen import meta_keywords
this_template = "apptemplate.html"
def tabs(request):
return render_to_response(this_template, { 'title' : "Page Name", 'keys' : meta_keywords(render_to_string(this_template)) })
在主模板 base.html
中,添加以下代码:
<head>
<title>Site Name - {{ title }}</title>
<meta name="keywords" content="{{ keys }}" />
</head>
这样,就可以自动为每个页面生成并添加元关键字了。