Я хочу прочитать последние темы от Invison Power Board с REST API.
Я нашел работающий код PHP, проверенный на моей системе с PHP 7.3.6, но я не знаю, как использовать этот код в Twig v2.10.0.
function getRecentForumTopics() {
$communityUrl = 'https://domain.tld/';
$apiKey = '123';
$endpoint = '/forums/topics';
$vars = '?sortDir=desc&perPage=4';
$curl = curl_init( $communityUrl . 'api' . $endpoint.$vars );
curl_setopt_array( $curl, array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => "{$apiKey}:"
) );
$response = curl_exec( $curl );
$values = json_decode($response, true);
$data = [];
foreach($values['results'] as $value) {
$data[] = [
'title' => $value['title'],
'url' => $value['firstPost']['url']
];
}
return $data;
}
echo '<h2>Recent Topics</h2>';
$array = getRecentForumTopics();
echo '<ol>';
foreach($array as $key => $item) {
echo '<li><a href = "'.$item['url'].'" target = "_blank">'.$item['title'].'</a></li>';
if ($key == 4) {
break;
}
}
echo '</ol>';
Это существующий PHP-код в Twig.
<?php
session_start();
require_once 'vendor/autoload.php';
require_once 'libs/user.php';
require_once 'config.php';
$data = array(
"WebTitle" => "name",
//"User" => User::GetData($_SESSION['user_id'])
);
$loader = new Twig_Loader_Filesystem('templates/');
$twig = new Twig_Environment($loader, array(
'cache' => 'c_cache',
'debug' => 'false'
));
echo $twig->render('test.html', $data);
Что мне нужно изменить, чтобы этот код работал в Twig?
Я могу добавить php-код в php-код twig, тогда последние темы будут показаны в конце страницы. Ошибок нет, но я не знаю, как это написать в twig.
Итак, что внутри test.html
{{ include('includes/head.html') }} <body> {{ include('includes/nav.html') }} <section class = "container mt-3"> <div class = "row"> </div> </section> {{ include('includes/footer.html') }} </body> </html>






Twig — это язык шаблонов, поэтому ваш HTML-код входит в ваши шаблоны. Как и ваш test.html. Затем в PHP вы получаете все данные, необходимые вашему шаблону, и передаете их.
<?php
session_start();
require_once 'vendor/autoload.php';
require_once 'libs/user.php';
require_once 'config.php';
function getRecentForumTopics()
{
$communityUrl = 'https://domain.tld/';
$apiKey = '123';
$endpoint = '/forums/topics';
$vars = '?sortDir=desc&perPage=4';
$curl = curl_init($communityUrl.'api'.$endpoint.$vars);
curl_setopt_array(
$curl,
[
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => "{$apiKey}:",
]
);
$response = curl_exec($curl);
$values = json_decode($response, true);
$data = [];
foreach ($values['results'] as $value) {
$data[] = [
'title' => $value['title'],
'url' => $value['firstPost']['url'],
];
}
return $data;
}
$data = array(
"WebTitle" => "name",
//"User" => User::GetData($_SESSION['user_id'])
"recentFormTopics" => getRecentForumTopics() // <- This is where you are getting the data that is going to be available in twig
);
$loader = new Twig_Loader_Filesystem('templates/');
$twig = new Twig_Environment($loader, array(
'cache' => 'c_cache',
'debug' => 'false'
));
echo $twig->render('test.html', $data);
Итак, теперь, когда вы передаете data в test.html, обновите свой шаблон ветки, чтобы использовать его.
{{ include('includes/head.html') }}
<body>
{{ include('includes/nav.html') }}
<section class = "container mt-3">
<div class = "row">
<div class = "col-12">
<h2>Recent Topics</h2>
{# This is where you will use the data being passed in #}
<ol>
{% for recentFormTopic in recentFormTopics %}
<li>
<a href = "{{ recentFormTopic.url }}" target = "_blank">{{ recentFormTopic.title }}</a>
</li>
{% endfor %}
</ol>
</div>
</div>
</section>
{{ include('includes/footer.html') }}
</body>
</html>
что ты уже испробовал? Вы получаете какие-либо ошибки?