如何使 django 的 markdown 过滤器将回车符转换为
?
如何更改 markdown 过滤器中的默认行为,以便将换行符转换为 br 标记?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不认为搞乱换行语法是一个好主意......
我同意 Henrik 的评论。来自 markdown 文档:
您是否看过其他 Django 标记选项、纺织和重组文本?它们的语法可能更适合您。
但如果你仍然想...
一个粗略且现成的方法是链接 markdown 和 linebreaksbr 过滤器。
这会运行 markdown 过滤器,然后运行 linebreaksbr 过滤器,它将
\n
替换为
。您可能会遇到太多的换行符,但这可能比太少的换行符对您更好。如果您有更好的解决方案,您可以
编写一个自定义过滤器,正如约翰在他的回答中建议的那样。
深入了解 Django 使用的 python-markdown 库,以及< a href="http://www.freewisdom.org/projects/python-markdown/Writing_Extensions" rel="nofollow noreferrer">编写一个扩展来实现您所需的换行语法。然后,您可以将扩展与过滤器一起使用
{{ value|markdown:"linebreakextension" }}
I don't think messing around with the newline syntax is a good idea ...
I agree with Henrik's comment. From the markdown docs:
Have you looked at the other Django markup options, textile and restructuredtext? Their syntax might suit you better.
but if you still want to ...
A rough and ready method is to chain the markdown and linebreaksbr filters.
This runs the markdown filter, then the linebreaksbr filter, which replaces
\n
with<br />
. You'll probably end up with too many linebreaks, but that might be better for you than too few.If you a better solution than that, you could
Write a custom filter, as John suggests in his answer.
Dive into the the python-markdown library, which Django uses, and write an extension that implements your desired newline syntax. You would then use the extension with the filter
{{ value|markdown:"linebreakextension" }}
编辑:截至 2011 年 6 月底,以下扩展现已包含在 Python Markdown 中。
这是我编写的 Markdown 扩展,目前正在我的网站上进行测试,以完全满足您的需求:
我将其放入名为 mdx_nl2br.py 的文件中,并将其放在我的 PYTHONPATH 中。然后,您可以在 Django 模板中使用它,如下所示:
如果您想在常规代码中使用它,您可以执行如下操作:
这是文档中使用和编写扩展的起点。
EDIT: As of the end of June, 2011, the extension below is now included with Python Markdown.
Here is a Markdown extension that I wrote and am currently testing on my site to do exactly what you want:
I put this in a file called mdx_nl2br.py and put it on my PYTHONPATH. You can then use it in a Django template like this:
If you'd like to use it in regular code, you can do something like this:
Here is the starting point in the docs for using and writing extensions.
您可以通过在
extras
设置中添加"break-on-newline": True
来覆盖默认的 MARKDOWN_DEUX_STYLES:python-markdown2 的文档:
You can override default MARKDOWN_DEUX_STYLES with adding
"break-on-newline": True
inextras
settings :Documentation of python-markdown2:
您可以编写一个调用 markdown 的 自定义过滤器,然后对其输出进行替换。
You could write a custom filter that calls markdown, then does replace on its output.
似乎有一个
linebreaks
过滤器,可将\n
字符转换为
或>.
请参阅 换行 或 linebreaksbr。
There appears to be a
linebreaks
filter that converts\n
characters to either<br>
or<p>
.See linebreaks or linebreaksbr.