Add Pico::substituteUrl() and url Twig filter

Allows theme developers and users to use URL placeholders like `%base_url%` in meta headers, e.g. to include images.
This commit is contained in:
Daniel Rudolf 2019-08-29 23:10:35 +02:00
parent 715cb83431
commit 6e6d80c044
No known key found for this signature in database
GPG key ID: A061F02CD8DE4538
2 changed files with 32 additions and 1 deletions

View file

@ -2240,6 +2240,36 @@ class Pico
return substr($path, $contentDirLength, -$contentExtLength) ?: null;
}
/**
* Substitutes URL placeholders (e.g. %base_url%)
*
* This method is registered as the `url` Twig filter and often used to
* allow users to specify absolute URLs in meta data utilizing the known
* URL placeholders `%base_url%`, `%plugins_url%`, `%themes_url%`,
* `%assets_url%` and `%theme_url%`.
*
* Don't confuse this with the `link` Twig filter, which takes a page ID as
* parameter. However, you can indeed use this method to create page URLs,
* e.g. `{{ "%base_url%?sub/page"|url }}`.
*
* @param string $url URL with placeholders
*
* @return string URL with replaced placeholders
*/
public function substituteUrl($url)
{
$variables = array(
'%base_url%?' => $this->getBaseUrl() . (!$this->isUrlRewritingEnabled() ? '?' : ''),
'%base_url%' => rtrim($this->getBaseUrl(), '/'),
'%plugins_url%' => rtrim($this->getConfig('plugins_url'), '/'),
'%themes_url%' => rtrim($this->getConfig('themes_url'), '/'),
'%assets_url%' => rtrim($this->getConfig('assets_url'), '/'),
'%theme_url%' => $this->getConfig('themes_url') . $this->getTheme()
);
return str_replace(array_keys($variables), $variables, $url);
}
/**
* Returns the URL of the themes folder of this Pico instance
*

View file

@ -75,7 +75,8 @@ class PicoTwigExtension extends Twig_Extension
'markdown' => new Twig_SimpleFilter('markdown', array($this, 'markdownFilter')),
'map' => new Twig_SimpleFilter('map', array($this, 'mapFilter')),
'sort_by' => new Twig_SimpleFilter('sort_by', array($this, 'sortByFilter')),
'link' => new Twig_SimpleFilter('link', array($this->pico, 'getPageUrl'))
'link' => new Twig_SimpleFilter('link', array($this->pico, 'getPageUrl')),
'url' => new Twig_SimpleFilter('url', array($this->pico, 'substituteUrl'))
);
}