基本上,我正在为我的CMS编写模板系统,并且希望采用模块化结构,其中涉及人们放置标签,如:
这里有人指向了我DOMDocument,但我已经遇到了一个问题。
我试图在模板中查找所有的
现在,我遇到了致命错误
我查了一下,似乎是因为我的
如何独立地替换它们?
谢谢。
汤姆
编辑:
基本上,我有一个点子。如果我对我的PHP做这样的事情,我看到它正在尝试做我想要的事情:
然而,它似乎只更改了我HTML中中的1个出现...当我有3个:/
<module name="news" />
或<include name="anotherTemplateFile" />
,然后我想在php中查找它们并用动态html替换它们。这里有人指向了我DOMDocument,但我已经遇到了一个问题。
我试图在模板中查找所有的
<include />
标签,并将它们替换为一些简单的html。以下是我的模板代码:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>CMS</title>
<include name="head" />
</head>
<body>
<include name="header" />
<include name="content" />
<include name="footer" />
</body>
</html>
以下是我的PHP代码:
$template = new DOMDocument();
$template->load("template/template.tpl");
foreach( $template->getElementsByTagName("include") as $include ) {
$element = '<input type="text" value="'.print_r($include, true).'" />';
$output = $template->createTextNode($element);
$template->replaceChild($output, $include);
}
echo $template->saveHTML();
现在,我遇到了致命错误
Uncaught exception 'DOMException' with message 'Not Found Error'
。我查了一下,似乎是因为我的
<include />
标签不一定是$template
的直接子元素,所以没有替换它们。如何独立地替换它们?
谢谢。
汤姆
编辑:
基本上,我有一个点子。如果我对我的PHP做这样的事情,我看到它正在尝试做我想要的事情:
$template = new DOMDocument();
$template->load("template/template.tpl");
foreach( $template->getElementsByTagName("include") as $include ) {
$element = '<input type="text" value="'.print_r($include, true).'" />';
$output = $template->createTextNode($element);
// this line is different:
$include->parentNode->replaceChild($output, $include);
}
echo $template->saveHTML();
然而,它似乎只更改了我HTML中中的1个出现...当我有3个:/
createTextNode()
会转义任何尖括号。请改用appendXML()
。 - Gordon