Django搜索框placeholder翻译异常:仅显示首个单词如何解决?
问题描述
搜索栏的placeholder需要根据用户所选语言翻译,使用{% translate %}模板标签时仅显示第一个单词,通过context传递也无效。
用户原模板代码:
<form class="form_search"> {% csrf_token %} <div class="form-group input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-search" style="color:black"></i></span> <input type="search" class="form-control home_search rounded-end" placeholder= {% translate "placeholder text here nicely..." %} name='keyword' id='inputsearch'> </div> </form>
原视图代码:
def search_home(request): return render(request, 'search_home.html',context)
尝试context传递的错误代码:
from django.utils.translation import gettext_lazy as lazy_ def search_home(request): context = {'placeholder_search':lazy_('some placeholder here to be translated...')} return render(request, 'search_home.html',context)
<form class="form_search"> {% csrf_token %} <div class="form-group input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-search" style="color:black"></i></span> <input type="search" class="form-control home_search rounded-end" placeholder={{context.placeholder_search}} name={{context.placeholder_search}} id='inputsearch'> </div> </form>
正确实现方式
方法一:直接使用模板标签(修复引号问题)
核心问题是placeholder属性值未加引号,当翻译文本包含空格时,浏览器会将第一个空格后的内容识别为其他属性,导致仅显示第一个单词。只需给{% translate %}的结果添加引号:
<form class="form_search"> {% csrf_token %} <div class="form-group input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-search" style="color:black"></i></span> <input type="search" class="form-control home_search rounded-end" placeholder="{% translate 'placeholder text here nicely...' %}" name='keyword' id='inputsearch'> </div> </form>
方法二:通过context传递(修复变量调用方式)
模板中错误地使用了{{context.placeholder_search}},Django模板里直接写变量名即可,无需加context.前缀,同时也要给属性值加引号:
视图代码:
from django.utils.translation import gettext_lazy as lazy_ def search_home(request): context = {'placeholder_search': lazy_('some placeholder here to be translated...')} return render(request, 'search_home.html', context)
模板代码:
<form class="form_search"> {% csrf_token %} <div class="form-group input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-search" style="color:black"></i></span> <input type="search" class="form-control home_search rounded-end" placeholder="{{ placeholder_search }}" name='keyword' id='inputsearch'> </div> </form>
额外说明
- 确保已正确配置Django国际化:
settings.py中设置USE_I18N = True,配置LANGUAGES列表,生成并编译对应语言的翻译文件。 - 视图中若无需延迟翻译,可直接使用
gettext替代gettext_lazy:
from django.utils.translation import gettext as _ def search_home(request): context = {'placeholder_search': _('some placeholder here to be translated...')} return render(request, 'search_home.html', context)
内容的提问来源于stack exchange,提问作者User981636
相关产品推荐
相关产品推荐

