Php echo index URL if last

Hey there :wave:
In my template I can click trough an image gallery and if the last picture comes, there is a
<a href="http://linktoindex.com">

I use kirbytext to display images.
My workaround for localhost looks like this:

<?php 
$imgs = $page->imgs()->toStructure();
$last = $imgs->last();
foreach($imgs as $img): ?>
<div class="onclick">
    <?php if($img == $last) echo ' <a href="http://localhost:8888/website-name/"> ' ?>
        <?= $img->panels()->kirbytext() ?>
    <?php if($img == $last) echo ' </a> ' ?>
</div>
<?php endforeach ?>

What I want is to use this code <?= kirby()->urls()->index() ?>
so I get the index URL.
But it echoes
<?= kirby()->urls()->index() ?>
instead and not
http://linktoindex.com

Thanks in advance!
Erik

Ok i have found the solution :nerd_face:

I just put
<?php if($img == $last) echo ' onclick="goToURL();" ' ?>
into the div and a simple Script at the end of the HTML

function goToURL() {
    location.href = '<?= kirby()->urls()->index() ?>';
}

Hope this helps someone!

You don’t need a script, these problem come from an incorrect use of PHP within echoed HTML tags, so that the code is not executed but echoed literally:

    <?php 
    $imgs = $page->imgs()->toStructure();
    $last = $imgs->last();
    foreach($imgs as $img): ?>
    <div class="onclick">
      <?php if($img == $last): ?>
        <a href="<?= url() ?>">
      <?php endif ?>
      <?= $img->panels()->kirbytext() ?>
      <?php if($img == $last): ?>
        </a>
      <?php endif ?>
    </div>
    <?php endforeach ?>

or you have to do it like this:

echo ' <a href="' . $kirby->roots()->index(). ' "> ' ;
1 Like