如何将 HTML 块(使用 python)插入当前正在工作的网站......?

发布于 2024-12-14 06:26:35 字数 461 浏览 3 评论 0原文

现在我有了一个可以通过查看一些示例来实现的解决方案。看起来这个

pagetemp = string.Template(open("index_template.html").read())
#print pagetemp.template

f = open("index.html","w")
f.write(pagetemp.substitute(sean_final_output=sean_final_output))
f.close()
return 1

sean_final_output是一个html代码块,我只是在该模板中使用$sean_final_output...有没有更合适的方法来做到这一点? IE 可以不用“模板”文件直接编辑index.html 吗?我想优点是我可以按照我现在的方式进行替代...我只是觉得我正在读取一个文件并输出到另一个文件,所以我不知道这是否是最有效的方法... (我想学习python方式)

Right now I have a solution that works from looking at some examples. It looks like this

pagetemp = string.Template(open("index_template.html").read())
#print pagetemp.template

f = open("index.html","w")
f.write(pagetemp.substitute(sean_final_output=sean_final_output))
f.close()
return 1

sean_final_output is an html block of code, and I just use a $sean_final_output in that template... is there a more proper way to do this? I.E. instead of having a 'template' file can I directly edit the index.html? I guess the advantage is I can just do a substitute the way I am doing it now... I just feel like I am reading in one file and outputting to another so I dont' know if its the most efficient way.... (I want to learn the python way)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

负佳期 2024-12-21 06:26:35

对于一个简单的替换来说,你所做的一切都很好。但是,如果您要做更复杂的事情,这种方法很快就会变得笨拙。

值得注意的是,有很多现有的解决方案可以从模板(尤其是 HTML)创建文本。 JinjaDjango Templates 是成熟且广泛使用的 Python 模板库的两个示例,还有其他几个示例。我强烈建议使用其中之一!

What you are doing is just fine, for a single simple replacement. However, if you're going to do anything more complex, this method will quickly become clumsy.

It is worth noting that there are quite a few existing solutions for creating text from templates, especially HTML. Jinja and Django Templates are two examples of mature and widely used Python templating libraries, and there are several others as well. I highly recommend using one of these!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文