如何使用Twig检测屏幕大小或移动设备/桌面设备

7

我目前正在使用Twig作为我的模板引擎,我想在加载移动端和桌面端时加载不同的图像URL。有没有简单的方法可以实现这个功能?

所以我想要做类似于这样的事情:

{% if (mobile) %}
   <img src="{{ picture.getLowresimageurl() }}"/>
{% else %}
   <img src="{{ picture.getMedresimageurl() }}"/>
{% endif %}

有没有一种方法可以做到这一点?
1个回答

6
您可以使用MobileDetectBundle来检测移动设备,管理移动视图,并重定向到移动和平板电脑版本。 Twig助手
{% if is_mobile() %}
{% if is_tablet() %}
{% if is_device('iphone') %} # magic methods is[...]

Twig示例

{% if is_mobile_view() %}
    {% extends "MyBundle:Layout:mobile.html.twig" %}
{% else if is_tablet_view() %}
    {% extends "MyBundle:Layout:tablet.html.twig" %}
{% else if is_full_view() or is_not_mobile_view() %}
    {% extends "MyBundle:Layout:full.html.twig" %}
{% endif %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接