我有点问题。我正在为一个篮球俱乐部建立一个网站,在这个网站上有一个每个团队的页面,在这个页面内有两个div(让我们说一个,我知道怎么做两次:))。这个div充满了我从JSON获得的信息并被放入表中。我有一个工作代码,但现在我的网站在PHP框架Twig。现在代码不再起作用了。我从老师那里听说我必须为树枝制作一个自定义控制器。这是什么,我该怎么做?
PHP代码:
<?php
function getTableC($link)
{
$json = file_get_contents($link);
$data = json_decode($json);
if (count($data->wedstrijden)) {
// Open the table
echo "<table class=\"table table-bordered\">
<tr>
<th>Datum</th>
<th>Tijd</th>
<th>Thuis</th>
<th>Uit</th>
<th>Uitslag</th>
</tr>";
//Cycle through the array
foreach ($data->wedstrijden as $idx => $wedstrijden) {
$arrDate = explode(' ', $wedstrijden->datum);
$arrTime = explode(':', $arrDate[1]);
// Output a row
echo "<tr>";
echo "<td>$arrDate[0]</td>";
echo "<td>$arrTime[0]:$arrTime[1]</td>";
echo "<td>$wedstrijden->thuis_ploeg</td>";
echo "<td>$wedstrijden->uit_ploeg</td>";
echo "<td>$wedstrijden->score_thuis - $wedstrijden->score_uit</td>";
echo "</tr>";
}
// Close the table
echo "</table>";
}
}
?>
编辑1: 我曾经用它来包含php代码:
<!-- Content Text-->
<div class="panel-box">
<div class="titles">
<h4>Aankomende Wedstrijden</h4>
</div>
<div class="row">
<div class="col-md-12" id="standtable">
<?php include("php/competitie.php"); echo getTableC("http://west.basketball.nl/db/json/wedstrijd.pl?cmp_ID=411&plg_ID=10845"); ?>
</div>
</div>
答案 0 :(得分:2)
如果您想了解更多关于使用树枝的背景信息,我可以给您一个更具体的答案。
Twig可让您放置功能,例如在模板内迭代你的数组。
当您的PHP代码执行时,基本上应该发生的是,您收集所有需要的数据并将其传递给您的树枝模板。然后twig渲染你的页面。
从你的代码开始,这可能在php端看起来像这样。具体取决于您是否使用symfony这样的框架。以下假设您使用的是没有框架的平面php(另请查看twig docs):
function renderPage($link)
{
// twig stuff
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
));
// get your data
$json = file_get_contents($link);
$data = json_decode($json);
echo $twig->render('table.html', array('tableData' => $data->wedstrijden));
}
模板table.html
:
...
<!-- Content Text-->
<div class="panel-box">
<div class="titles">
<h4>Aankomende Wedstrijden</h4>
</div>
<div class="row">
<div class="col-md-12" id="standtable">
{# here the table is built #}
{% if tableData is not empty %}
<table class="table table-bordered">
<tr>
<th>Datum</th>
<th>Tijd</th>
<th>Thuis</th>
<th>Uit</th>
<th>Uitslag</th>
</tr>
{% for row in tableData %}
{% set aDate = row.datum|split(' ') %}
{% set aTime = aDate[1]|split(':') %}
<tr>
<td>{{ aDate[0] }}</td>
<td>{{ aTime[0] }}:{{ aTime[1] }}</td>
<td>{{ row.thuis_ploeg }}</td>
<!-- ... and so on -->
</tr>
{% endfor %}
</table>
{% endif %}
</div>
</div>
...