我试图提出一个系统,其中foo
或faa
等可视组件将存储在/components
文件夹中,每个组件将在其文件夹中,其中包含该组件文件,例如/foo
,以及组件文件foo.component.css
和foo.component.php
。name.component.php
内部有一些HTML
和一个样式<link>
,引用name.component.css.
来设置组件的样式。组件包含在页面文件中,例如index.php
,它从root
外部的head.php
获取其<head>
标记。
文件层次结构如下所示:
├──* head.php
└──* /root
├──* index.php
└──* /components
├──* /foo
│ ├── foo.component.css
│ └── foo.component.php
└──* /faa
├── faa.component.css
└── faa.component.php
当index.php
包含一个组件时,它的CSS
将被添加到<head>
之外,这是我希望避免的。有没有办法在PHP
执行过程中将CSS
链接移动到文档<head>
,例如,使用自定义函数?CSS
需要从name.component.php
中移动出来。因此手动将CSS
添加到head.php
是行不通的。
文件:head.php
<head>
<!-- Other non-component stylesheets here; -->
<!-- Component stylesheets would be moved here during PHP execution; -->
</head>
<body>
文件:index.php
require_once("../head.php");
require_once("coponents/foo.component.php");
文件:foo.component.php
// Can this be moved to the head during execution from this folder?
echo('<link href="/components/foo/foo.component.css" rel="stylesheet">');
// Some HTML elements here...
// Trigger something here that moves the CSS link to the head.php
缓冲可以是一个选项吗?任何指针将不胜感激。
2条答案
按热度按时间8i9zcol21#
您的组件真的应该用echo定义css吗?
你的index.php可以插入它,如果你遵循一个命名惯例。问题是当你有更复杂的事情要做时,你会看到它。
我的做法是为你的组件创建一个清单。你会有一个类,列出所需的css文件、javascript文件(为什么不呢)和模板文件。你的index.php可以很容易地运行定义,并在适当的地方包含。
索引将加载该类,并循环遍历其样式表,以便在正确的位置回显它们。
你必须弄清楚如何处理路径,要么你的清单声明它们相对于index.php,要么你找到一种方法来知道清单类从哪里来的文件,这样你就可以从它来一个相对路径,不幸的是我不是很擅长PHP这方面...
2exbekwf2#
我现在在网站中所做的就是将一个 head.php 文件放入我网站上各个页面的PHP文件中。有时候某个页面的特定PHP文件可能需要一个不同的JS文件或CSS文件。因此,我在 head.php 中的head元素内有
<?= $headEls ?>
。现在,在页面的一个PHP文件中,我可以为
$headEls
赋值,这只是一个字符串,用于可能需要的任何 script 或 link 元素。上面的系统的一个问题是,你必须在每个PHP文件中给
$headEls
赋值(即使你只是让它成为一个空字符串),否则你会在访问一个未定义的变量时遇到错误。为了绕过这个问题,我在尝试访问$headEls
之前在 head.php 中放入了下面的行:这一行是$headEls = isset($headEls) ? $headEls : '';
,所以现在我只需要给$headEls
赋一个值,如果我真的有一个CSS或JS文件要放入其中的话。我相信可以想到更好的系统,但它确实工作,我不想使用一个框架,解决所有这些问题,加上我从来没有想到过,但涉及到我的服务器和我的本地机器上的1000个文件。