我有使用纯php(没有模板引擎)创建html模板的工作代码。代码正确地将<select>
呈现给页面。我要求进行代码审核here
它导致我的代码无法编译。我看到一个明显的错误,static $template = 'select_template.php';
被完全删除导致$template
未定义,所以我已经修复了。
现在CountrySelect
模板根本不会向页面呈现任何html,我不确定为什么,因为php错误日志中没有php错误。我不能说RegionSelect
模板是否会呈现,因为我还没有使用它,但我认为它不是因为它是相同的,除了$viewData
问题:如何让CountrySelect模板再次渲染?
加分:我希望我的$template
和$templatePath
在接口或抽象类中都是常量,如果可能的话。可以这样做吗?
这是我的代码:
country_select.php
<?php
interface iSelect {
public static function display();
}
abstract class AreaSelect implements iSelect {
static $template = 'select_template.php';
public static function displayData($viewData) {
if ( class_exists( 'View' ) ) {
// Get the full path to the template file.
$templatePath = dirname( __FILE__ ) . '/' . static::$template;
// Return the rendered HTML
return View::render( $templatePath, $viewData );
}
else {
return "You are trying to render a template, but we can't find the View Class";
}
}
}
class CountrySelect extends AreaSelect {
public static function display() {
$viewData = array(
"options" => '_countries',
"optionsText" => 'name',
"optionsValue" => 'geonameId',
"value" => 'selectedCountry',
"caption" => 'Country'
);
parent::displayData($viewData);
}
}
class RegionSelect extends AreaSelect {
public static function display() {
$viewData = array(
"options" => '_regions',
"optionsText" => 'name',
"optionsValue" => 'name',
"value" => 'selectedCity',
"caption" => 'Region'
);
parent::displayData($viewData);
}
}
view.php:
<?php
/** View.php **/
class View {
/**
* -------------------------------------
* Render a Template.
* -------------------------------------
*
* @param $filePath - include path to the template.
* @param null $viewData - any data to be used within the template.
* @return string -
*
*/
public static function render( $filePath, $viewData = null ) {
// Was any data sent through?
( $viewData ) ? extract( $viewData ) : null;
ob_start();
include ( $filePath );
$template = ob_get_contents();
ob_end_clean();
return $template;
}
}
?>
select_template.php:
<div class="form-group col-sm-6">
<div class="select">
<span class="arr"></span>
<select data-bind="options: <? echo $options ?>,
optionsText: '<? echo $optionsText ?>',
optionsValue: '<? echo $optionsValue ?>',
value: <? echo $value ?>,
optionsCaption: '<? echo $caption ?>'">
</select>
</div>
</div>
这是确实输出到php页面的文字HTML(当使用my version on code review时),现在在index.php页面的html输出中完全丢失了:
<div class="form-group col-sm-6">
<div class="select">
<span class="arr"></span>
<select data-bind="options: _countries,
optionsText: 'name',
optionsValue: 'geonameId',
value: selectedCountry,
optionsCaption: 'Country'">
</select>
</div>
</div>
调用index.php中的模板来实际呈现它(由于我的代码审查中没有包含它,所以没有改变):
<?php
require 'scripts/back_end/views/country_select.php';
require 'scripts/back_end/views/view.php';
//echo View::render('select_template.php');
echo CountrySelect::display();
?>