Skip to content

Instantly share code, notes, and snippets.

@flug
Created March 16, 2016 14:13
Show Gist options
  • Save flug/08498c4c315ae8d1e7ea to your computer and use it in GitHub Desktop.
Save flug/08498c4c315ae8d1e7ea to your computer and use it in GitHub Desktop.
<?php
namespace MyBundle\Bundle\FrontendBundle\Twig\Loader;
use MyBundle\Bundle\FrontendBundle\Twig\MobileDetect;
use Symfony\Bundle\FrameworkBundle\Templating\Loader\FilesystemLoader;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Templating\TemplateReferenceInterface;
class MobileFilesystemLoader extends FilesystemLoader
{
protected $detect;
protected $fs;
public function __construct(FileLocatorInterface $locator, MobileDetect $detect, Filesystem $filesystem)
{
parent::__construct($locator);
$this->locator = $locator;
$this->detect = $detect;
$this->fs = $filesystem;
}
public function load(TemplateReferenceInterface $template)
{
$defaultFormat = $template->get('format');
$template->set('format', $this->setExtensionForTemplate($template));
$file = $this->locator->locate($template);
if ($this->fs->exists($file)) {
return parent::load($template);
}
$template->set('format', $defaultFormat);
return parent::load($template);
}
private function isMobile()
{
return $this->detect->isMobile();
}
private function isTablet()
{
return $this->detect->isTablet();
}
private function setExtensionForTemplate(TemplateReferenceInterface $template)
{
$ext = $template->get('format');
if ($this->isTablet()) {
$ext = "tablet.html";
}
if ($this->isMobile()) {
$ext = "mobile.html";
}
return $ext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment