Reputation: 6745
I have the following Symfony 5 based PHP web application structure:
.
├── LICENSE
├── bin
├── composer.json
├── composer.lock
├── config
├── migrations
├── phpunit.xml.dist
├── public
│ ├── images
│ │ ├── 3e28ae7b9f72cb1958e532161709f559.jpg
│ │ ├── f16b8e3277415e2783d076177aee8f7e.jpg
│ │ └── fe0920ac3d2b89f1cd4d787cedc3daf4.jpg
│ └── index.php
├── src
│ ├── Controller
│ │ └── CatController.php
├── symfony.lock
├── templates
├── tests
├── translations
├── var
└── vendor
CatController.php
:
<?php
namespace App\Controller;
use App\Entity\Cat;
use App\Repository\CatRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/cat")
*/
class CatController extends AbstractController
{
/**
* @Route("/{id}", name="cat_show", methods={"GET"})
*/
public function show(Cat $cat): Response
{
return $this->render('cat/show.html.twig', [
'cat' => $cat,
]);
}
}
Cat.php
(Entity):
<?php
namespace App\Entity;
use App\Repository\CatRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=CatRepository::class)
*/
class Cat
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $image;
public function getId(): ?int
{
return $this->id;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
}
cat/show.html.twig
:
{{ cat.image }}
<img src="{{ cat.image }}"/ >
This template produces HTML, which looks correct:
images/3e28ae7b9f72cb1958e532161709f559.jpg
<img src="images/3e28ae7b9f72cb1958e532161709f559.jpg">
But the image does not actually render, and when I right click on where the image should be and select 'Open in new tab'.
A new tab opens and the URL is set to:
http://localhost:8000/cat/images/3e28ae7b9f72cb1958e532161709f559.jpg
Is there a way to prevent /cat
prefix on the rendered URL? Which is preventing the image url from resolving correctly.
Upvotes: 0
Views: 222
Reputation: 1646
<img src="{{ absolute_url(asset(cat.image)) }}"/ >
https://symfony.com/doc/current/templates.html#linking-to-css-javascript-and-image-assets
Upvotes: 1
Reputation: 1253
Did you try this?
<img src="/{{ cat.image }}"/ >
In this way you don't have to change it if you decide to move to another folder ...
Upvotes: 0
Reputation: 6745
All I needed was:
<img src="../{{ house.image }}"/ >
to access the parent directory and append the image url.
Upvotes: 0