Str::slug to open a file in a new tab

How can I go about opening a pdf in a new tab when a link is clicked. I need convert the title into a safe string I guess using str::slug but how can I use within the href.

My code is:

<a href="<?= $article->files()->get('myfile.pdf')->url() ?>" target="_blank">

Did you try this plugin : http://getkirby-plugins.com/download-tag
Is it what you want ?

1 Like

What does not work as expected with this code?

sorry I wasn’t very clear. I want to convert the title field into a safe string.

so like

<a href="<?= $article->files()->get(<?php echo str::slug($project->title()->value)?>)->url()" target="_blank">

But that clearly doesn’t work. What is the right way to go about achieving this?

There’s a syntax error (missing parenthesis after value), should be:

str::slug($project->title()->value())

i’ve added the parenthesis. I also realised my variable was wrong.

my current code is

<a href="<?= $article->files()->get(<?= str::slug($article->title()->value())?>)->url() ?>" target="_blank">

in the kirby debugger is comes up with “syntax error, unexpected ‘<’”

Oh, yes, you are using php tags inside php tags, which is not possible:

<a href="<?= $article->files()->get(str::slug($article->title()->value()))->url() ?>" target="_blank">

I thought so but I got the error ‘Call to a member function url() on null’ with that solution

Then the file probably does not exist. As always with this kind of stuff, it doesn’t really make sense to call a method on an object (in this case url()) without prior testing if the object exists at all. So the correct way of doing that would be:

<?php
$file = $article->file(str::slug($article-title()->value()));
if($file): ?>
  <a href="<?= $file->url() ?>" target="_blank">
<?php endif ?>

I believe the file does exist though, as you can see in the picture. I’m attempting to do this on a one-page website, do you think maybe it’s something to do with the page hierarchy?

The file() method expects an extension

<?php
$file = $article->file(str::slug($article-title()->value() . '.pdf'));
if($file): ?>
  <a href="<?= $file->url() ?>" target="_blank">
<?php endif ?>

Otherwise you have to use findBy:

<?php echo $page->files()->findBy('name', 'myfile')->url() ?>
1 Like