【问题标题】:Append before closing body tag in python在python中关闭body标签之前附加
【发布时间】:2013-01-19 22:54:09
【问题描述】:

好吧,伙计们,我有一个这样的 template.html 文件:

<h1>Hello wolrd</h1>
<div>This is me</div>

我想在结束正文标记之前将它附加到我的索引文件中。就像这样:

<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title></title>
</head>
<body>

<script type="text/ng-template" id="templates/template.html">
<h1>Hello wolrd</h1>
<div>This is me</div> 
</script>

</body>
</html>

到目前为止,我已经阅读了文件并附加到文件的末尾,但我还没有将脚本标签添加到我正在阅读的文件中并附加到文件的正确位置。这是我目前拥有的:

#!/usr/bin/env python
import fileinput

to_readfile=open('index.html', "r")
try:
  reading_file=to_readfile.read()

  writefile=open('index2.html','a')
  try:
    writefile.write("\n")
    writefile.write(reading_file)
  finally:
    writefile.close()

finally:
  to_readfile.close()

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你不能使用jinja是有原因的吗?
  • 是的,基本上我想从使用 Yeoman.io 构建的 angularJS 应用程序过渡到运行 serverles 的应用程序。因此,如果我压缩应用程序并且有人打开 index.html 文件,该应用程序仍会运行。这可以通过不在模板中进行 ajaxing 而是将它们直接插入到索引文件中来实现。

标签: python template-engine


【解决方案1】:

最简单的方法是在布局模板中添加一个占位符,然后在处理布局时搜索占位符并将其替换为另一个模板的内容。

<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title></title>
</head>
<body>

<script type="text/ng-template" id="templates/template.html">
{{content}}
</script>

</body>
</html>

...
..
.
layout = open('layout.html', "r")
layout_contents = layout.read()

partial=open('partial_file.html','r')
result = layout_contents.replace("{{content}}", partial)

writefile = open("file_to_write.html", "w")
writefile.write("\n")
writefile.write(result)
.
..
....

您还可以使用更广泛的解决方案,例如 jinja http://jinja.pocoo.org/docs/templates/#template-inheritance 使用的解决方案。

【讨论】:

  • 如果我不使用占位符,而是使用“
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多