在PHP执行期间将样式表移动到文档头

llew8vvj  于 2022-12-02  发布在  PHP
关注(0)|答案(2)|浏览(151)

我试图提出一个系统,其中foofaa等可视组件将存储在/components文件夹中,每个组件将在其文件夹中,其中包含该组件文件,例如/foo,以及组件文件foo.component.cssfoo.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

缓冲可以是一个选项吗?任何指针将不胜感激。

8i9zcol2

8i9zcol21#

您的组件真的应该用echo定义css吗?
你的index.php可以插入它,如果你遵循一个命名惯例。问题是当你有更复杂的事情要做时,你会看到它。
我的做法是为你的组件创建一个清单。你会有一个类,列出所需的css文件、javascript文件(为什么不呢)和模板文件。你的index.php可以很容易地运行定义,并在适当的地方包含。

// File foo.manifest.php
class FooComponent implements Component{
    public $stylesheets = ['foo.component.css'];
    public $javascripts= ['foo.component.js'];
    public $dependsOn = []; // You could set dependencies here so other components are loaded if needed.
    public $template = 'foo.component.php';
}

索引将加载该类,并循环遍历其样式表,以便在正确的位置回显它们。

$components = [new Foo(),new Faa()];
foreach($components as $component){
   foreach($component->stylesheet as $stylesheet){
      echo ('<link href="'.$stylesheet.'" rel="stylesheet">');
   }
}
require_once("../head.php");

foreach($components as $component){
   require_once($component->template); 
}

你必须弄清楚如何处理路径,要么你的清单声明它们相对于index.php,要么你找到一种方法来知道清单类从哪里来的文件,这样你就可以从它来一个相对路径,不幸的是我不是很擅长PHP这方面...

2exbekwf

2exbekwf2#

我现在在网站中所做的就是将一个 head.php 文件放入我网站上各个页面的PHP文件中。有时候某个页面的特定PHP文件可能需要一个不同的JS文件或CSS文件。因此,我在 head.php 中的head元素内有<?= $headEls ?>
现在,在页面的一个PHP文件中,我可以为$headEls赋值,这只是一个字符串,用于可能需要的任何 scriptlink 元素。
上面的系统的一个问题是,你必须在每个PHP文件中给$headEls赋值(即使你只是让它成为一个空字符串),否则你会在访问一个未定义的变量时遇到错误。为了绕过这个问题,我在尝试访问$headEls之前在 head.php 中放入了下面的行:这一行是$headEls = isset($headEls) ? $headEls : '';,所以现在我只需要给$headEls赋一个值,如果我真的有一个CSS或JS文件要放入其中的话。
我相信可以想到更好的系统,但它确实工作,我不想使用一个框架,解决所有这些问题,加上我从来没有想到过,但涉及到我的服务器和我的本地机器上的1000个文件。

相关问题