【问题标题】:Add a newline after each closing html tag in web2py在 web2py 中的每个结束 html 标记后添加一个换行符
【发布时间】:2011-11-10 21:41:31
【问题描述】:

原创

我想解析一串 html 代码并在结束标记 + 初始表单标记之后添加换行符。这是到目前为止的代码。它在“re.sub”行中给了我一个错误。我不明白为什么正则表达式会失败。

def user(): 
    tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
    result = re.sub("(</.*?>)", "\1\n", tags)
    return dict(form_code=result)

PS。我觉得这可能不是最好的方法......但我仍然想学习如何做到这一点。


编辑

我的 default.py 中缺少“import re”。感谢 ruak。

import re


现在我的页面源代码显示如下(在客户端浏览器中检查)。实际页面将表单代码显示为文本,而不是 UI 元素。

&lt;form&gt;&lt;label for=&quot;email_field&quot;&gt;Email:&lt;/label&gt;
&lt;input type=&quot;email&quot; name=&quot;email_field&quot;/&gt;&lt;label     
for=&quot;password_field&quot;&gt;Password:&lt;/label&gt;
&lt;input type=&quot;password&quot; name=&quot;password_field&quot;/&gt;&lt;input   
type=&quot;submit&quot; value=&quot;Login&quot;/&gt;&lt;/form&gt;


编辑 2

将 XML() 助手添加到 default.py 后,表单代码呈现为 UI 元素。感谢安东尼的帮助。更正以下行:

return dict(form_code=XML(result))


最终编辑

修复我自己想出的正则表达式。这不是最佳解决方案,但至少它有效。最终代码:

import re
def user(): 
    tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
    tags = re.sub(r"(<form>)", r"<form>\n  ", tags)
    tags = re.sub(r"(</.*?>)", r"\1\n  ", tags)
    tags = re.sub(r"(/>)", r"/>\n  ", tags)
    tags = re.sub(r"(  </form>)", r"</form>\n", tags)
    return dict(form_code=XML(tags))

【问题讨论】:

    标签: regex web2py


    【解决方案1】:

    我看到的唯一问题是您需要将"\1\n" 更改为r"\1\n"(使用“原始”字符串表示法);否则\1 被解释为八进制转义(表示字符 U+0001)。但这本身不应该给你一个错误。您收到什么错误消息?

    【讨论】:

    • 它给出:(未定义全局名称're')
    • 应用 r 的结果相同,顺便说一句
    • 我认为这只是意味着您需要import re。 (免责声明:这就是您在常规 Python 中所需要的。我从未使用过 web2py,而且我有一种模糊的感觉,即导入在那里的工作方式可能会有所不同。参见例如stackoverflow.com/questions/6557000/…。但作为第一步,我会尝试只需将import re 放在您的函数定义之上,看看它是否能解决问题。)
    • 非常感谢!现在页面出现了。但是,输出的格式仍然不正确。我会用我的发现更新原来的问题。
    • 不,导入在 web2py 中照常工作。过去,应用程序的“模块”文件夹中的模块存在一个问题,需要特殊的导入方法,但现在不再如此。 sys.path 中的模块(例如标准库)的导入在 web2py 中总是像往常一样工作。
    【解决方案2】:

    出于安全原因,默认情况下,web2py 会转义视图中插入的所有文本。为避免这种情况,只需在控制器中使用 XML() 帮助器:

    return dict(form_code=XML(result))
    

    或在视图中:

    {{=XML(form_code)}}
    

    除非代码来自受信任的来源,否则不要这样做——否则它可能包含恶意 Javascript。

    【讨论】:

    • 谢谢!我的表单现在可以正确显示。 XML() 创造了奇迹。最后一期:正则表达式模式只是部分没问题。
    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多