Skip to content

Commit

Permalink
Fix local asset twig function and allow url
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-schranz committed May 10, 2019
1 parent b315095 commit 9ad2fa0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ http://wkhtmltopdf.org/downloads.html
See [KnpSnappyBundle](https://github.com/KnpLabs/KnpSnappyBundle#configuration) for configuration.

## Usage
========

**Controller Trait**

Expand Down Expand Up @@ -100,4 +99,10 @@ The `local_asset` avoids doing a http request by using `file://` instead of `htt
<img src="{{ local_asset('/images/image.jpg') }}" alt="Local Asset">
```

This will only work when `$request->getRequestFormat()` will return `pdf`.
This will only work when `$request->getRequestFormat()` will return `pdf` and not `html`.

If you want to force using `file://` set the second parameter to true:

```twig
<img src="{{ local_asset('/images/image.jpg', true) }}" alt="Local Asset">
```
19 changes: 13 additions & 6 deletions Twig/LocalAssetTwigExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,26 +54,33 @@ public function getFunctions()
public function getFilters()
{
return [
new \Twig_SimpleFilter('abbr_class', [$this, 'getLocalAsset']),
new \Twig_SimpleFilter('local_asset', [$this, 'getLocalAsset']),
];
}

/**
* Get local asset path.
*
* @param string $assetUrl
* @param bool $force
*
* @return string
*/
public function getLocalAsset($assetUrl)
public function getLocalAsset($assetUrl, $force = false)
{
$request = $this->requestStack->getCurrentRequest();
$prefix = 'file://' . $this->publicDirectory;
$assetUrl = '/' . ltrim($assetUrl, '/');

if ('html' === $request->getRequestFormat()) {
return $assetUrl;
if ($force) {
return $prefix . $assetUrl;
}

$request = $this->requestStack->getCurrentRequest();

if ($request && 'html' === $request->getRequestFormat()) {
$prefix = $request->getSchemeAndHttpHost();
}

return 'file://' . $this->publicDirectory . $assetUrl;
return $prefix . $assetUrl;
}
}

0 comments on commit 9ad2fa0

Please sign in to comment.