add twig function to build urls with query strings

This commit is contained in:
sheepish
2025-01-01 21:44:43 +00:00
committed by Spine
parent 522e5d70ba
commit d00bfc6017
3 changed files with 36 additions and 3 deletions

View File

@@ -208,6 +208,15 @@ class Twig {
'UTF-8'
)));
$twig->addFunction(new \Twig\TwigFunction('build_url', function (string $base, array $args): string {
$delim = str_contains($base, '?') ? '&' : '?';
foreach ($args as $k => $v) {
$base .= $delim . $k . '=' . $v;
$delim = '&';
}
return $base;
}));
$twig->addFunction(new \Twig\TwigFunction('donor_icon', fn($icon) => new \Twig\Markup(image_cache_encode($icon), 'UTF-8')));
$twig->addFunction(new \Twig\TwigFunction('ipaddr', fn(string $ipaddr) => new \Twig\Markup(

View File

@@ -11,7 +11,7 @@
<p>Reports by type</p>
<ul>
{% for item in type_count %}
<li><a href="{{ base_uri }}&amp;type={{ item[0].id }}">{{ item[1] }} {{ item[0].name }}</a></li>
<li><a href="{{ build_url(base_uri, {'type': item[0].id}) }}">{{ item[1] }} {{ item[0].name }}</a></li>
{% endfor %}
</ul>
</td></tr></table>
@@ -21,7 +21,7 @@
<p>Reports by user</p>
<ul>
{% for item in user_count %}
<li><a href="{{ base_uri }}&amp;userid={{ item[0].id }}">{{ item[1] }} {{ item[0].username }}</a></li>
<li><a href="{{ build_url(base_uri, {'userid': item[0].id}) }}">{{ item[1] }} {{ item[0].username }}</a></li>
{% endfor %}
</ul>
</td></tr></table>

View File

@@ -214,9 +214,33 @@ END;
]);
global $SessionID;
$SessionID = $current['SessionID'];
$this->assertStringStartsWith('<!DOCTYPE html>', self::twig('{{ header("page") }}')->render(), 'twig-function-header');
$this->assertStringEndsWith("</body>\n</html>\n", self::twig('{{ footer() }}')->render(), 'twig-function-footer');
$this->assertEquals(
'http://localhost/?arg=abc',
self::twig('{{ build_url("http://localhost/", {"arg": arg}) }}')
->render(['arg' => 'abc']),
'twig-function-build-url-1'
);
$this->assertEquals(
'http://localhost/?arg=abc&amp;id=10',
self::twig('{{ build_url("http://localhost/", {"arg": arg, "id": id}) }}')
->render(['arg' => 'abc', 'id' => 10]),
'twig-function-build-url-2'
);
$this->assertEquals(
'http://localhost/index?x=123&amp;arg=def',
self::twig('{{ build_url("http://localhost/index?x=123", {"arg": arg}) }}')
->render(['arg' => 'def']),
'twig-function-build-url-3'
);
$this->assertEquals(
'http://localhost/index?x=123&amp;arg=def&amp;id=20',
self::twig('{{ build_url("http://localhost/index?x=123", {"arg": arg, "id": id}) }}')
->render(['arg' => 'def', 'id' => 20]),
'twig-function-build-url-4'
);
$this->assertEquals(
'127.0.0.1 <a href="user.php?action=search&amp;ip_history=on&amp;matchtype=strict&amp;ip=127.0.0.1" title="Search" class="brackets tooltip">S</a>',
self::twig('{{ ipaddr(ip) }}')->render(['ip' => '127.0.0.1']),