【问题标题】:Can not set value of ace editor with template tags filters无法使用模板标签过滤器设置 ace 编辑器的值
【发布时间】:2019-12-15 09:20:48
【问题描述】:

我的 html 页面中有一个 ace 编辑器,我可以为此编写代码

editor.setValue( '//Your code here');

它完美地工作,我得到一个编辑器,里面写着“//你的代码”。 但是当我从 django 后端传递一个模板标签时,用这一行。

def func(request):
       context={"message":"hello there,write your code"}
       return render(request,'index.html',context)

并尝试使用带有此行的模板标记过滤器设置值

editor.setValue({{message}});

它不起作用,如果我用简单的 html 编写它,它可以工作,但不在 setValue() 函数中。

【问题讨论】:

  • 字符串没有用引号括起来。

标签: django django-templates ace-editor


【解决方案1】:

这不起作用的原因是消息不会用引号括起来。

您应该对传递给模板的字符串进行 JSON 转储:

from json import dumps as jdumps

def func(request):
    context={'message': jdumps('hello there,write your code')}
    return render(request,'index.html',context)

在模板中,您应该使用|safe template filter [Django-doc] 将字符串标记为安全,以防止对字符串进行 HTML 转义:

editor.setValue({{ message<b>|safe</b> }});

【讨论】:

  • 你解决了我的大量工作,我正在考虑更改 models.py 等。真的非常感谢你 :)
  • 我今天找到了一个替代解决方案, context={'message':'this is a message'} 并在 html 页面中使用:“{{message|escapejs}}”
猜你喜欢
  • 1970-01-01
  • 2019-11-30
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
相关资源
最近更新 更多