使用“路径"和“资产"用于非模板数据 [英] Using "path" and "asset" for non-template data

查看:101
本文介绍了使用“路径"和“资产"用于非模板数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Twig创建模板时,很容易使用pathasset函数.

When creating templates with Twig, it's easy to use the path and asset functions.

<a href="{{ path('my_route') }}"><img src="{{ asset('bundles/acmedemo/my_image.png') }}" /></a>

但是,我的某些数据来自非树枝文件或数据库.从那里解决这些功能的正确方法是什么?

However, some of my data come from non-twig files or from database. What would be the right way to address these functions from there?

到目前为止,我将正则表达式替换(preg_replace_callback)用于路径功能.但是没有更好的方法吗?

So far, I'm using regex replace (preg_replace_callback) for the path function. But isn't there a nicer way?

推荐答案

我很自豪地展示我的第一个公共小型项目

I am proud to present my first public mini-project, the StaticBundle. It pretty much lets you include any file in a bundle straight into a template.

编辑现在可以使用composer安装该软件包,请参见自述文件.

EDIT The bundle can now be installed using composer, please see the instructions on readme.

将以下内容添加到deps:

[KGStaticBundle]
    git=git://github.com/kgilden/KGStaticBundle.git
    target=bundles/KG/StaticBundle

运行bin/vendors install.

app/autoload.php中注册名称空间:

'KG' => __DIR__.'/../vendor/bundles',

app/AppKernel.php中注册捆绑软件:

new KG\StaticBundle\KGStaticBUndle(),

基本用法

假设我们已经准备好将文件src/Acme/Bundle/DemoBundle/Static/hello.txt包含在模板中.我们必须使用file函数:

Basic usage

Suppose we have a file src/Acme/Bundle/DemoBundle/Static/hello.txt ready to be included in a template. We'd have to use a file function:

{# src/Acme/Bundle/DemoBundle/Resources/views/Demo/index.html.twig #}

{{ file('@AcmeDemoBundle/Static/hello.txt') }}

逻辑名称被解析为实际路径,并且简单的file_get_contents检索数据.

The logical name gets resolved into the actual path and a simple file_get_contents retrieves the data.

这篇关于使用“路径"和“资产"用于非模板数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆