Twig Extensions Defined by Symfony

Twig is the template engine used in Symfony applications. There are tens of default filters and functions defined by Twig, but Symfony also defines some filters, functions and tags to integrate the various Symfony components with Twig templates. This article explains them all.

Twig は、Symfony アプリケーションで使用されるテンプレート エンジンです。Twig によって定義されたデフォルトのフィルターと関数は数十ありますが、Symfony では、さまざまな Symfony コンポーネントを Twig テンプレートと統合するために、いくつかのフィルター、関数、およびタグも定義しています。この記事では、それらすべてについて説明します。

Tip

ヒント

If these extensions provided by Symfony are not enough, you can create a custom Twig extension to define even more filters and functions.

Symfony が提供するこれらの拡張機能では不十分な場合は、カスタムの Twig 拡張機能を作成して、さらに多くのフィルターと関数を定義できます。

Functions

render

1
{{ render(uri, options = []) }}
uri
type: string | ControllerReference
タイプ: 文字列 | ControllerReference
options (optional)
type: array default: []
タイプ: 配列 デフォルト: []

Makes a request to the given internal URI or controller and returns the result. The render strategy can be specified in the strategy key of the options. It's commonly used to embed controllers in templates.

指定された内部 URI またはコントローラーに要求を行い、結果を返します。レンダー戦略は、オプションの戦略キーで指定できます。これは、一般的に、テンプレートにコントローラーを埋め込むために使用されます。

render_esi

1
{{ render_esi(uri, options = []) }}
uri
type: string | ControllerReference
タイプ: 文字列 | ControllerReference
options (optional)
type: array default: []
タイプ: 配列 デフォルト: []

It's similar to the render function and defines the same arguments. However, it generates an ESI tag when ESI support is enabled or falls back to the behavior of render otherwise.

render 関数に似ており、同じ引数を定義します。ただし、ESI サポートが有効になっている場合は ESI タグを生成するか、それ以外の場合は render の動作に戻ります。

Tip

ヒント

The render_esi() function is an example of the shortcut functions of render. It automatically sets the strategy based on what's given in the function name, e.g. render_hinclude() will use the hinclude.js strategy. This works for all render_*() functions.

render_esi() 関数は、render のショートカット関数の例です。関数名で指定された内容に基づいて戦略を自動的に設定します。 render_hinclude() は hinclude.js 戦略を使用します。これは、すべての render_*() 関数で機能します。

fragment_uri

1
{{ fragment_uri(controller, absolute = false, strict = true, sign = true) }}
controller
type: ControllerReference
タイプ: ControllerReference
absolute (optional)
type: boolean default: false
タイプ: ブール デフォルト: false
strict (optional)
type: boolean default: true
タイプ: ブール デフォルト: true
sign (optional)
type: boolean default: true
タイプ: ブール デフォルト: true

Generates the URI of a fragment.

フラグメントの URI を生成します。

controller

1
{{ controller(controller, attributes = [], query = []) }}
controller
type: string
タイプ: 文字列
attributes (optional)
type: array default: []
タイプ: 配列 デフォルト: []
query (optional)
type: array default: []
タイプ: 配列 デフォルト: []

Returns an instance of ControllerReference to be used with functions like render() and render_esi().

render() や render_esi() などの関数で使用される ControllerReference のインスタンスを返します。

asset

1
{{ asset(path, packageName = null) }}
path
type: string
タイプ: 文字列
packageName (optional)
type: string | null default: null
タイプ: 文字列 | null デフォルト: null

Returns the public path of the given asset path (which can be a CSS file, a JavaScript file, an image path, etc.). This function takes into account where the application is installed (e.g. in case the project is accessed in a host subdirectory) and the optional asset package base path.

指定されたアセット パス (CSS ファイル、JavaScript ファイル、画像パスなど) のパブリック パスを返します。この関数は、アプリケーションがインストールされている場所 (プロジェクトがホスト サブディレクトリでアクセスされている場合など) と、オプションのアセット パッケージのベース パスを考慮します。

Symfony provides various cache busting implementations via the Framework Configuration Reference (FrameworkBundle), Framework Configuration Reference (FrameworkBundle), and Framework Configuration Reference (FrameworkBundle) configuration options.

Symfony は、フレームワーク構成リファレンス (FrameworkBundle)、フレームワーク構成リファレンス (FrameworkBundle)、およびフレームワーク構成リファレンス (FrameworkBundle) 構成オプションを介して、さまざまなキャッシュ無効化の実装を提供します。

See also

こちらもご覧ください

Read more about linking to web assets from templates.

テンプレートから Web アセットへのリンクについて詳しくは、こちらをご覧ください。

asset_version

1
{{ asset_version(packageName = null) }}
packageName (optional)
type: string | null default: null
タイプ: 文字列 | null デフォルト: null

Returns the current version of the package, more information in Creating and Using Templates.

パッケージの現在のバージョンを返します。詳細については、テンプレートの作成と使用を参照してください。

csrf_token

1
{{ csrf_token(intention) }}
intention
type: string - an arbitrary string used to identify the token.
type: string - トークンを識別するために使用される任意の文字列。

Renders a CSRF token. Use this function if you want CSRF protection in a regular HTML form not managed by the Symfony Form component.

CSRF トークンをレンダリングします。 Symfony フォーム コンポーネントによって管理されない通常の HTML フォームで CSRF 保護が必要な場合は、この関数を使用します。

is_granted

1
{{ is_granted(role, object = null, field = null) }}
role
type: string
タイプ: 文字列
object (optional)
type: object
タイプ: オブジェクト
field (optional)
type: string
タイプ: 文字列

Returns true if the current user has the given role.

現在のユーザーが指定された役割を持っている場合は true を返します。

Optionally, an object can be passed to be used by the voter. More information can be found in Security.

オプションで、投票者が使用するオブジェクトを渡すことができます。詳細については、セキュリティを参照してください。

logout_path

1
{{ logout_path(key = null) }}
key (optional)
type: string
タイプ: 文字列

Generates a relative logout URL for the given firewall. If no key is provided, the URL is generated for the current firewall the user is logged into.

指定されたファイアウォールの相対ログアウト URL を生成します。キーが指定されていない場合、ユーザーがログインしている現在のファイアウォールの URL が生成されます。

logout_url

1
{{ logout_url(key = null) }}
key (optional)
type: string
タイプ: 文字列

Equal to the logout_path function, but it'll generate an absolute URL instead of a relative one.

logout_path 関数と同等ですが、相対 URL ではなく絶対 URL を生成します。

path

1
{{ path(route_name, route_parameters = [], relative = false) }}
name
type: string
タイプ: 文字列
parameters (optional)
type: array default: []
タイプ: 配列 デフォルト: []
relative (optional)
type: boolean default: false
タイプ: ブール デフォルト: false

Returns the relative URL (without the scheme and host) for the given route. If relative is enabled, it'll create a path relative to the current path.

指定されたルートの相対 URL (スキームとホストなし) を返します。相対が有効になっている場合は、現在のパスに対する相対パスが作成されます。

See also

こちらもご覧ください

Read more about Symfony routing and about creating links in Twig templates.

Symfony のルーティングと Twig テンプレートでのリンクの作成についての詳細をお読みください。

url

1
{{ url(route_name, route_parameters = [], schemeRelative = false) }}
name
type: string
タイプ: 文字列
parameters (optional)
type: array default: []
タイプ: 配列 デフォルト: []
schemeRelative (optional)
type: boolean default: false
タイプ: ブール デフォルト: false

Returns the absolute URL (with scheme and host) for the given route. If schemeRelative is enabled, it'll create a scheme-relative URL.

指定されたルートの絶対 URL (スキームとホストを含​​む) を返します。スキーム相対が有効な場合、スキーム相対 URL が作成されます。

See also

こちらもご覧ください

Read more about Symfony routing and about creating links in Twig templates.

Symfony のルーティングと Twig テンプレートでのリンクの作成についての詳細をお読みください。

absolute_url

1
{{ absolute_url(path) }}
path
type: string
タイプ: 文字列

Returns the absolute URL (with scheme and host) from the passed relative path. Combine it with the asset() function to generate absolute URLs for web assets. Read more about Linking to CSS, JavaScript and Image Assets.

渡された相対パスから絶対 URL (スキームとホストを含​​む) を返します。これを asset() 関数と組み合わせて、Web アセットの絶対 URL を生成します。 CSS、JavaScript、および画像アセットへのリンクについて詳しくは、こちらをご覧ください。

relative_path

1
{{ relative_path(path) }}
path
type: string
タイプ: 文字列

Returns the relative path from the passed absolute URL. For example, assume you're on the following page in your app: http://example.com/products/hover-board.

渡された絶対 URL からの相対パスを返します。たとえば、アプリの次のページにいるとします:http://example.com/products/hover-board。
1
2
3
4
5
{{ relative_path('http://example.com/human.txt') }}
{# ../human.txt #}

{{ relative_path('http://example.com/products/products_icon.png') }}
{# products_icon.png #}

expression

Creates an Expression related to the ExpressionLanguage component.

ExpressionLanguage コンポーネントに関連する Expression を作成します。

impersonation_exit_path

1
{{ impersonation_exit_path(exitTo = null) }}
exitTo (optional)
type: string
タイプ: 文字列

Generates a URL that you can visit to exit user impersonation. After exiting impersonation, the user is redirected to the current URI. If you prefer to redirect to a different URI, define its value in the exitTo argument.

ユーザーの偽装を終了するためにアクセスできる URL を生成します。偽装を終了すると、ユーザーは現在の URI にリダイレクトされます。別の URI にリダイレクトする場合は、exitTo 引数でその値を定義します。

If no user is being impersonated, the function returns an empty string.

ユーザーが偽装されていない場合、関数は空の文字列を返します。

impersonation_exit_url

1
{{ impersonation_exit_url(exitTo = null) }}
exitTo (optional)
type: string
タイプ: 文字列

It's similar to the impersonation_exit_path function, but it generates absolute URLs instead of relative URLs.

これは impersonation_exit_path 関数に似ていますが、相対 URL ではなく絶対 URL を生成します。

t  

t
1
{{ t(message, parameters = [], domain = 'messages')|trans }}
message
type: string
タイプ: 文字列
parameters (optional)
type: array default: []
タイプ: 配列 デフォルト: []
domain (optional)
type: string default: messages
タイプ: 文字列 デフォルト: メッセージ

Creates a Translatable object that can be passed to the trans filter.

trans フィルターに渡すことができる Translatable オブジェクトを作成します。

The following functions related to Symfony Forms are also available. They are explained in the article about customizing form rendering:

Symfony Forms に関連する以下の機能も利用できます。それらについては、フォーム レンダリングのカスタマイズに関する記事で説明されています。

Filters

humanize

1
{{ text|humanize }}
text
type: string
タイプ: 文字列

Makes a technical name human readable (i.e. replaces underscores by spaces or transforms camelCase text like helloWorld to hello world and then capitalizes the string).

技術名を人間が判読できるようにします (つまり、アンダースコアをスペースに置き換えるか、helloWorld のようなキャメルケースのテキストを hello world に変換してから、文字列を大文字にします)。

trans

1
{{ message|trans(arguments = [], domain = null, locale = null) }}
message
type: string | Translatable
タイプ: 文字列 |翻訳可能
arguments (optional)
type: array default: []
タイプ: 配列 デフォルト: []
domain (optional)
type: string default: null
タイプ: 文字列 デフォルト: null
locale (optional)
type: string default: null
タイプ: 文字列 デフォルト: null

Translates the text into the current language. More information in Translation Filters.

テキストを現在の言語に翻訳します。詳細については、翻訳フィルターを参照してください。

sanitize_html

6.1

6.1

The sanitize_html() filter was introduced in Symfony 6.1.

sanitize_html() フィルターは Symfony 6.1 で導入されました。
1
{{ body|sanitize_html(sanitizer = "default") }}
body
type: string
タイプ: 文字列
sanitizer (optional)
type: string default: "default"
タイプ: 文字列 デフォルト: "デフォルト"

Sanitizes the text using the HTML Sanitizer component. More information in HTML Sanitizer.

HTML Sanitizer コンポーネントを使用してテキストをサニタイズします。詳細については、HTML Sanitizer を参照してください。

yaml_encode

1
{{ input|yaml_encode(inline = 0, dumpObjects = false) }}
input
type: mixed
タイプ: 混合
inline (optional)
type: integer default: 0
タイプ: 整数 デフォルト: 0
dumpObjects (optional)
type: boolean default: false
タイプ: ブール デフォルト: false

Transforms the input into YAML syntax. See The Yaml Component for more information.

入力を YAML 構文に変換します。詳しくは、Yaml コンポーネントを参照してください。

yaml_dump

1
{{ value|yaml_dump(inline = 0, dumpObjects = false) }}
value
type: mixed
タイプ: 混合
inline (optional)
type: integer default: 0
タイプ: 整数 デフォルト: 0
dumpObjects (optional)
type: boolean default: false
タイプ: ブール デフォルト: false

Does the same as yaml_encode(), but includes the type in the output.

yaml_encode() と同じことを行いますが、出力に型を含めます。

abbr_class

1
{{ class|abbr_class }}
class
type: string
タイプ: 文字列

Generates an <abbr> element with the short name of a PHP class (the FQCN will be shown in a tooltip when a user hovers over the element).

PHP クラスの短い名前を持つ要素を生成します (ユーザーが要素にカーソルを合わせると、FQCN がツールチップに表示されます)。

abbr_method

1
{{ method|abbr_method }}
method
type: string
タイプ: 文字列

Generates an <abbr> element using the FQCN::method() syntax. If method is Closure, Closure will be used instead and if method doesn't have a class name, it's shown as a function (method()).

FQCN::method() 構文を使用して要素を生成します。 method が Closure の場合、代わりに Closure が使用され、method にクラス名がない場合は、関数 (method()) として表示されます。

format_args

1
{{ args|format_args }}
args
type: array
タイプ: 配列

Generates a string with the arguments and their types (within <em> elements).

引数とその型 (要素内) を含む文字列を生成します。

format_args_as_text

1
{{ args|format_args_as_text }}
args
type: array
タイプ: 配列

Equal to the format_args filter, but without using HTML tags.

format_args フィルターと同じですが、HTML タグを使用しません。

file_excerpt

1
{{ file|file_excerpt(line, srcContext = 3) }}
file
type: string
タイプ: 文字列
line
type: integer
タイプ: 整数
srcContext (optional)
type: integer
タイプ: 整数

Generates an excerpt of a code file around the given line number. The srcContext argument defines the total number of lines to display around the given line number (use -1 to display the whole file).

指定された行番号周辺のコード ファイルの抜粋を生成します。 srcContext 引数は、指定された行番号の周囲に表示する合計行数を定義します (ファイル全体を表示するには -1 を使用します)。

format_file

1
{{ file|format_file(line, text = null) }}
file
type: string
タイプ: 文字列
line
type: integer
タイプ: 整数
text (optional)
type: string default: null
タイプ: 文字列 デフォルト: null

Generates the file path inside an <a> element. If the path is inside the kernel root directory, the kernel root directory path is replaced by kernel.project_dir (showing the full path in a tooltip on hover).

要素内のファイル パスを生成します。パスがカーネル ルート ディレクトリ内にある場合、カーネル ルート ディレクトリ パスは、kernel.project_dir に置き換えられます (カーソルを合わせるとツールチップにフル パスが表示されます)。

format_file_from_text

1
{{ text|format_file_from_text }}
text
type: string
タイプ: 文字列

Uses format_file to improve the output of default PHP errors.

format_file を使用して、デフォルトの PHP エラーの出力を改善します。
1
{{ file|file_link(line) }}
file
type: string
タイプ: 文字列
line
type: integer
タイプ: 整数

Generates a link to the provided file and line number using a preconfigured scheme.

事前構成されたスキームを使用して、指定されたファイルと行番号へのリンクを生成します。

file_relative

1
{{ file|file_relative }}
file
type: string
タイプ: 文字列

It transforms the given absolute file path into a new file path relative to project's root directory:

指定された絶対ファイル パスを、プロジェクトのルート ディレクトリに相対的な新しいファイル パスに変換します。
1
2
{{ '/var/www/blog/templates/admin/index.html.twig'|file_relative }}
{# if project root dir is '/var/www/blog/', it returns 'templates/admin/index.html.twig' #}

If the given file path is out of the project directory, a null value will be returned.

指定されたファイル パスがプロジェクト ディレクトリの外にある場合、null 値が返されます。

serialize

1
{{ object|serialize(format = 'json', context = []) }}
object
type: mixed
タイプ: 混合
format (optional)
type: string
タイプ: 文字列
context (optional)
type: array
タイプ: 配列

Accepts any data that can be serialized by the Serializer component and returns a serialized string in the specified format.

Serializer コンポーネントによってシリアル化できるすべてのデータを受け入れ、指定された形式でシリアル化された文字列を返します。

Tags

form_theme

1
{% form_theme form resources %}
form
type: FormView
タイプ: FormView
resources
type: array | string
タイプ: 配列 |ストリング

Sets the resources to override the form theme for the given form view instance. You can use _self as resources to set it to the current resource. More information in How to Customize Form Rendering.

特定のフォーム ビュー インスタンスのフォーム テーマをオーバーライドするようにリソースを設定します。リソースとして _self を使用して、現在のリソースに設定できます。詳細については、フォームのレンダリングをカスタマイズする方法を参照してください。

trans

1
{% trans with vars from domain into locale %}{% endtrans %}
vars (optional)
type: array default: []
タイプ: 配列 デフォルト: []
domain (optional)
type: string default: string
タイプ: 文字列 デフォルト: 文字列
locale (optional)
type: string default: string
タイプ: 文字列 デフォルト: 文字列

Renders the translation of the content. More information in Translations.

コンテンツの翻訳をレンダリングします。詳細については、翻訳をご覧ください。

trans_default_domain

1
{% trans_default_domain domain %}
domain
type: string
タイプ: 文字列

This will set the default domain in the current template.

これにより、現在のテンプレートのデフォルト ドメインが設定されます。

stopwatch

1
{% stopwatch 'event_name' %}...{% endstopwatch %}

This measures the time and memory used to execute some code in the template and displays it in the Symfony profiler. See how to profile Symfony applications.

これは、テンプレート内の一部のコードを実行するために使用される時間とメモリを測定し、Symfony プロファイラーに表示します。 Symfony アプリケーションをプロファイリングする方法を参照してください。

Tests

The following tests related to Symfony Forms are available. They are explained in the article about customizing form rendering:

Symfony Forms に関連する以下のテストが利用可能です。これらは、フォーム レンダリングのカスタマイズに関する記事で説明されています。

Global Variables

app

The app variable is injected automatically by Symfony in all templates and provides access to lots of useful application information. Read more about the Twig global app variable.

app 変数は Symfony によってすべてのテンプレートに自動的に挿入され、多くの有用なアプリケーション情報へのアクセスを提供します。 Twig グローバル アプリ変数の詳細を参照してください。