是否可以在PHP中的include文件中包含文件



我在php中有一个基本的页面结构,其中包含页眉和页脚的包含文件。在页脚中,我想添加一个包含文件,该文件只有在页面作为数据表类时才会加载。类似于:

if ($class == 'data-table')
include(SHARED_PATH . '/load-datatables.php');

我的目标是只在需要时加载脚本。我是PHP的新手,所以我想从简单的事情开始。谢谢

如果要使用php在页面中搜索"数据表"类,那将很困难。尽管这是你可以做的。

添加一个php变量,指示数据表类"数据表"是否在页面中使用

// index.php
<?php $pageUsesDataTable = true; ?>
...
...
<table class="data-table">.....</table>
// Then load the script if depending on the variable
if ($pageUsesDataTable)
include(SHARED_PATH . '/load-datatables.php');

或者,您可以检查页面中是否存在"数据表"类,如果存在,则初始化数据表(如果它是通用(

// dTable.js or <script>
if($('.data-table').length != 0) {
// initialize the datatable
}

尽管总有一种更干净的方法,但还是要尝试更深入的搜索。祝好运

将此变量放在要包含php文件加载数据表的页面中:

$include_datatables_file = true;

然后在所有页面上包含一个名为checkinclude.php的通用文件:checkinclude.php:

if (!isset($include_datatable_file)) {$include_datatable_file = false;}
if ($include_datatable_file === true) {
include_once(SHARED_PATH . '/load-datatables.php');
}

Anurag评论后:你试过了吗…我当然试过了,但我没有找到正确的路径,所以它不起作用。更改了路径,它按预期工作。正如我所说,这可能不是最干净的方式或最佳实践。但它很有效,而且很容易设置。谢谢你的回答!

最新更新