I am using a dynamic HTML template system (like PHP) and I'm wondering if this problem/solution has a name or has been accomplished somewhere already.
The problem relates to controlling content dynamically, but after the fact when content and code are intertwined. Think of two pages, one that uses a lot of fancy styles and frameworks and another that doesn't, but share the same "outer wrapper" template.
<!DOCTYPE html>
<html>
<head>
<title>Both pages share a static title</title>
<script src="..." type="text/javascript">
<script src="..." type="text/javascript">
<script src="..." type="text/javascript">
</head>
<body>
<!-- only this part is dynamic, the top and bottom parts are shared among all pages -->
...
</body>
</html>
The plan was to leave a token where the header would be, modify a placeholder object in the body, and then substitute the placeholder contents where the token was after the page was done rendering (but before being sent to the client).
<!DOCTYPE html>
<html>
<head>
__HEAD__
</head>
<body>
<?
$head->title('my very own title');
$head->script('jquery 1.5.2');
?>
...
</body>
</html>
The __HEAD__
token would expand to actual HTML.
<!DOCTYPE html>
<html>
<head>
<title>my very own title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript">
开发者_如何学运维</head>
<body>
...
</body>
</html>
Has anyone seen this before?
Edit: Here's someone talking about the same problem, but with a slightly different solution.
http://iamcam.wordpress.com/2007/07/15/smarty-assigning-variables-to-the-header-from-the-body/
Edit^2: The accepted answer below was that this is something a templating engine does, which is true. The difficulty in this particular scenario was that the execution and templating engines intertwined (like old school PHP), so it was difficult to see the delineation. Easily solved with proper templates.
This is called a template engine. In addition to simply using PHP as your template engine, other solutions have been made available such as Smarty. Also, many frameworks such as CakePHP and symfony separate their code into layouts and views to afford this as well.
The biggest example for perl is the Template Toolkit. For other languages, you have ASP, JSP, EJS, Jade, mustaches, etc., etc.
Dependency injection
The OP was not clear on the original problem. The body of the page to be rendered should have been sequestered to a separate file. And it is this body file that should have final say about what goes in the header of the HTML, which is controlled by a different file.
So yes, the actual functionality of outputting specific scripts could be provided by a fancy templating engine, but the more important idea being expressed here is dependency injection, wherein the header file does not need to know about dependencies to be determined at some faraway place and time.
With Smarty V3 inheritance you can do this. Take a look : http://www.smarty.net/inheritance
精彩评论