在HTML中将HTML代码注入模板。

时间:2011-07-29 18:24:19

标签: html shell ksh

我有一个模板代码:

<html>
<head>
<title> My page </title>
</head>
<body>
CODEWOULDCOMEHERE
</BODY>
</HTML>

我有一个shell脚本(ksh),可以生成更多代码(放在CODEWOULDCOMEHERE目录中)。

我只是不知道如何在那里放置代码......我尝试了sed,但它没有用......最有效的方法是什么?

值得一提的是,生成的代码很长......

谢谢!

[编辑]

到目前为止我尝试过:

HTMLCODE=$(genReportStatCellHtml)
HTMLOUT=$(cat report_template.html|sed -e "s/CODEWOULDCOMEHERE/\'$HTMLCODE\'/g")

产生:sed: 0602-404 Function s/GENERATEDHTMLCODE/\'a lot of html'/g cannot be parsed.

HTMLCODE=$(genReportStatCellHtml)
HTMLOUT=$(cat report_template.html)
    echo ${HTMLOUT/CODEWOULDCOMEHERE/$HTMLCODE}

产生:./test.sh[8]: ${HTMLOUT/CODEWOULDCOMEHERE/$HTMLCODE}: 0403-011 The specified substitution is not valid for this command.

2 个答案:

答案 0 :(得分:1)

这样做的一个简单方法就是使用docs。这是交互式输入时的样子:

$ cat <<EOF
> Some literal content
> You can do parameter expansion:
> $PWD
> as well as command expansion:
> `date`
> 
> EOF
Some literal content
You can do parameter expansion:
/tmp
as well as command expansion:
Fri Jul 29 13:36:10 CDT 2011
$

执行它的shell脚本

#! /bin/sh
cat <<EOF >output.txt
Some literal content
You can do parameter expansion:
$PWD
as well as command expansion:
`date`

EOF

编辑:使用外部模板文件的好方法并不仅仅是shell的基本功能,但在其他语言中使用它很容易。这是一个python one liner,它会做到。

我们需要为单行使用特定的模板键,因此CODEWOULDCOMEHERE会被{0}取代。

$ cat report_template.html 
<html>
<head>
<title> My page </title>
</head>
<body>
{0}
</BODY>
</HTML>

$ echo "Heres the part that gets inserted" | python -c 'import sys; sys.stdout.write(file(sys.argv[1]).read().format(sys.stdin.read()))' report_template.html 
<html>
<head>
<title> My page </title>
</head>
<body>
Heres the part that gets inserted

</BODY>
</HTML>

总之,你的脚本看起来像这样

subst_template () {
    python -c 'import sys; sys.stdout.write(file(sys.argv[1]).read().format(sys.stdin.read()))' $1
}

genReportStatCellHtml | subst_template report_template.html > report.html

答案 1 :(得分:0)

parse_file() 
{ # works just like HEREdoc
    eval echo  "\"$(cat $1 | sed 's+\"+\\"+g'   )\""
}

parse_file templatefile