diff --git a/fr/README.md b/fr/README.md index 9fd2d3495bc..09209e7b903 100644 --- a/fr/README.md +++ b/fr/README.md @@ -4,7 +4,7 @@ Craft is a flexible, user-friendly CMS for creating custom digital experiences o It features: -- An intuitive, user-friendly Control Panel for content creation and administrative tasks. +- An intuitive, user-friendly control panel for content creation and administrative tasks. - A clean-slate approach to content modeling and [front-end development](dev/README.md) that doesn’t make any assumptions about your content or how it should be consumed. - A built-in Plugin Store with hundreds of free and commercial [plugins](https://plugins.craftcms.com/), all just a click away. - A robust framework for [module and plugin development](extend/README.md). @@ -29,8 +29,10 @@ Craft is a self-hosted PHP 7 application, built on [Yii 2](https://www.yiiframew ## Diving In +If you’re new to Craft CMS the best place to start is [the tutorial](https://docs.craftcms.com/tutorial/). + To start getting acquainted with how content modeling works in Craft, read [Sections and Entries](sections-and-entries.md) and [Fields](fields.md). -When you’re ready to install Craft, read [Server Requirements](requirements.md) and [Installation Instructions](installation.md). +Before installing, check out the [Server Requirements](requirements.md) and [Installation Instructions](installation.md). Finally, read the [Front-End Development](dev/README.md) section when you’re ready to start building out the front-end of your site or application. diff --git a/fr/assets-fields.md b/fr/assets-fields.md index 4e8431450d6..32216cbac56 100644 --- a/fr/assets-fields.md +++ b/fr/assets-fields.md @@ -40,6 +40,10 @@ Subfolder paths defined by the “Upload Location” and “Default Upload Locat Any properties supported by the source element (the element that has the Assets field) can be used here. +::: tip +If you want to include the entry’s ID or UID in a dynamic subfolder path, use `{sourceId}` or `{sourceUid}` rather than `{id}` or `{uid}`, so the source entry’s ID or UID is used rather than the revision / draft’s. +::: + ::: tip If you are creating the Assets field within a [Matrix field](matrix-fields.md), the source element is going to be the Matrix block, _not_ the element that the Matrix field is being created on. @@ -52,6 +56,10 @@ Assets fields list all of the currently-related assets, with a button to select Clicking the “Add an asset” button will bring up a modal window where you can find and select additional assets, as well as upload new ones. +::: tip +You can also upload assets by dragging files directly onto the assets field or modal window. +::: + ### Inline Asset Editing When you double-click on a related asset, a HUD will appear where you can edit the asset’s title and custom fields, and launch the Image Editor (if it’s an image). @@ -68,10 +76,15 @@ When [querying for elements](dev/element-queries/README.md) that have an Assets Possible values include: -| Value | Fetches elements… -| - | - -| `':empty:'` | that don’t have any related assets. -| `':notempty:'` | that have at least one related asset. +| Value | Fetches elements… | +| ----------------------------------------------------------- | ------------------------------------------------------- | +| `':empty:'` | that don’t have any related assets. | +| `':notempty:'` | that have at least one related asset. | +| `100` | that are related to the asset with an ID of 100. | +| `[100, 200]` | that are related to an asset with an ID of 100 or 200. | +| `['and', 100, 200]` | that are related to the assets with IDs of 100 and 200. | +| an [Asset](api:craft\elements\Asset) object | that are related to the asset. | +| an [AssetQuery](api:craft\elements\db\AssetQuery) object | that are related to any of the resulting assets. | ```twig {# Fetch entries with a related asset #} @@ -103,6 +116,10 @@ To loop through all of the related assets, call [all()](api:craft\db\Query::all( {% endif %} ``` +::: warning +When using `asset.url` or `asset.getUrl()`, the asset’s source volume must have “Assets in this volume have public URLs” enabled and a “Base URL” setting. Otherwise, the result will always be empty. +::: + If you only want the first related asset, call [one()](api:craft\db\Query::one()) instead, and then make sure it returned something: ```twig @@ -132,40 +149,71 @@ You can set [parameters](dev/element-queries/asset-queries.md#parameters) on the It’s always a good idea to clone the asset query using the [clone()](./dev/functions.md#clone) function before adjusting its parameters, so the parameters don’t have unexpected consequences later on in your template. ::: -### Uploading Files from Front-End Entry Forms +### Saving Assets Fields in Entry Forms -If you want to allow users to upload files to an Assets field from a front-end [entry form](dev/examples/entry-form.md), you just need to do two things. +If you have an [entry form](dev/examples/entry-form.md) that needs to contain an Assets field, you will need to submit your field value as a list of asset IDs, in the order you want them to be related. -First, make sure your `
` tag has an `enctype="multipart/form-data"` attribute, so that it is capable of uploading files. +For example, you could create a list of checkboxes for each of the possible relations: -```markup - +```twig +{# Include a hidden input first so Craft knows to update the + existing value, if no checkboxes are checked. #} +{{ hiddenInput('fields[]', '') }} + +{# Get all of the possible asset options #} +{% set possibleAssets = craft.assets() + .volume('siteAssets') + .kind('image') + .orderBy('filename ASC') + .withTransforms([ + { width: 100, height: 100 } + ]) + .all() %} + +{# Get the currently related asset IDs #} +{% set relatedAssetIds = entry is defined + ? entry..ids() + : [] %} + +
    + {% for possibleAsset in possibleAssets %} +
  • + +
  • + {% endfor %} +
``` -Then add a file input to the form: +You could then make the checkbox list sortable, so users have control over the order of related assets. -```markup - -``` +#### Creating New Assets -::: tip -Replace `` with you actual field handle. For example if you field handle is “heroImage”, the input name should be `fields[heroImage]`. -::: +Assets fields can handle new file uploads as well: -If you want to allow multiple file uploads, add the `multiple` attribute and add `[]` to the end of the input name: - -```markup - +```twig +{{ input('file', 'fields[][]', options={ + multiple: true, +}) }} ``` -If you want to add files to a field with existing assets, you will need to first fetch the existing asset ids and add them to a hidden field: +::: tip +Don’t forget to set `enctype="multipart/form-data"` on your `` tag so your browser knows to submit the form as a multipart request. +::: -``` -{% for asset in entry. %} - -{% endfor %} +Alternatively, you can submit Base64-encoded file data, which the Assets field will decode and treat as an uploaded file. To do that, you have to specify both the data and the filename like this: - +```twig +{{ hiddenInput('fields[][data][]', 'data:image/jpeg;base64,') }} +{{ hiddenInput('fields[][filename][]', 'myFile.ext') }} ``` ## See Also diff --git a/fr/assets.md b/fr/assets.md index 3ac719eb997..328a5781763 100644 --- a/fr/assets.md +++ b/fr/assets.md @@ -44,7 +44,7 @@ Any fields you select here will be visible in the asset editor HUD that opens up ## Assets Page -When you create your first volume, an “Assets” item will be added to the main Control Panel navigation. Clicking on it will take you to the Assets page, which shows a list of all of your volumes in the left sidebar, and the selected volume’s files in the main content area. +When you create your first volume, an “Assets” item will be added to the main control panel navigation. Clicking on it will take you to the Assets page, which shows a list of all of your volumes in the left sidebar, and the selected volume’s files in the main content area. From this page, you can do the following: diff --git a/fr/categories-fields.md b/fr/categories-fields.md index 07638f088b8..2af652739ba 100644 --- a/fr/categories-fields.md +++ b/fr/categories-fields.md @@ -59,10 +59,15 @@ You can set [parameters](dev/element-queries/category-queries.md#parameters) on Possible values include: -| Value | Fetches elements… | -| -------------- | ---------------------------------------- | -| `':empty:'` | that don’t have any related categories. | -| `':notempty:'` | that have at least one related category. | +| Value | Fetches elements… | +| ----------------------------------------------------------------- | ----------------------------------------------------------- | +| `':empty:'` | that don’t have any related categories. | +| `':notempty:'` | that have at least one related category. | +| `100` | that are related to the category with an ID of 100. | +| `[100, 200]` | that are related to a category with an ID of 100 or 200. | +| `['and', 100, 200]` | that are related to the categories with IDs of 100 and 200. | +| an [Category](api:craft\elements\Category) object | that are related to the category. | +| an [CategoryQuery](api:craft\elements\db\CategoryQuery) object | that are related to any of the resulting categories. | ```twig {% set relatedCategories = entry..all() %} @@ -111,8 +116,20 @@ To loop through all of the related categories as a flat list, call [all()](api:c Or you can show them as a hierarchical list with the [nav](dev/tags/nav.md) tag: ```twig -{% if entry..exists() %} -

There are related categories!

+{% set relatedCategories = entry..all() %} +{% if relatedCategories|length %} +
    + {% nav rel in relatedCategories %} +
  • + {{ rel.title }} + {% ifchildren %} +
      + {% children %} +
    + {% endifchildren %} +
  • + {% endnav %} +
{% endif %} ``` diff --git a/fr/categories.md b/fr/categories.md index 6b3a7dbb4eb..4ca0faf2be6 100644 --- a/fr/categories.md +++ b/fr/categories.md @@ -25,7 +25,7 @@ You can also add additional fields using all of the available field types in Cra ## Creating and Editing Categories -If you have at least one category group, there will be a “Categories” tab in the primary Control Panel navigation. Clicking on it will take you to the category index. From there you can choose a category group from the sidebar, and add/reorder/delete categories within it: +If you have at least one category group, there will be a “Categories” tab in the primary control panel navigation. Clicking on it will take you to the category index. From there you can choose a category group from the sidebar, and add/reorder/delete categories within it: ![Category Index](./images/categories-category-index.png) diff --git a/fr/changes-in-craft-3.md b/fr/changes-in-craft-3.md index 42ecd3953ef..1d5b3c57d0b 100644 --- a/fr/changes-in-craft-3.md +++ b/fr/changes-in-craft-3.md @@ -35,6 +35,10 @@ The “Position Select” field type has been removed from Craft 3. If you had a If you miss Position Select, you can try installing the [Position Fieldtype](https://github.com/Rias500/craft-position-fieldtype) plugin, which brings it back. +## Lightswitch Fields + +Lightswitch field values are now always `true` or `false`. If you’re accessing a Lightswitch field value for an element that doesn’t have an explicit value set yet, the field’s default value will be returned instead. + ## Remote Volumes Support for Amazon S3, Rackspace Cloud Files, and Google Cloud Storage have been moved into plugins. If you have any asset volumes that were using those services in Craft 2, you will need to install the new plugins: @@ -132,7 +136,7 @@ The acceptable translation categories are: In Craft 3, your `translations/` folder might look something like this: -``` +```treeview translations/ └── de/ ├── app.php @@ -449,14 +453,14 @@ That made it possible to execute variations of an element query, without affecti {% set totalEntries = query.total() %} ``` -Here `.type()` is applying the `type` parameter to a *clone* of `query`, so it had no effect on `query.total()`, which will still return the total number of News entries, regardless of their entry types. +Here `.type()` is applying the `type` parameter to a _clone_ of `query`, so it had no effect on `query.total()`, which will still return the total number of News entries, regardless of their entry types. This behavior has changed in Craft 3, though. Now any time you call a parameter-setter method, the method will: 1. set the parameter value on the current element query 2. return the element query -Which means in the above code example, `totalEntries` will be set to the total *Article* entries, as the `type` parameter will still be applied. +Which means in the above code example, `totalEntries` will be set to the total _Article_ entries, as the `type` parameter will still be applied. If you have any templates that count on the Craft 2 behavior, you can fix them using the [clone()](dev/functions.md#clone-object) function. @@ -571,7 +575,7 @@ Your front-end ``s and JS scripts that submit to a controller action will ### `action` Params -`action` params must be rewritten in in `kebab-case` rather than `camelCase`. +`action` params must be rewritten in `kebab-case` rather than `camelCase`. ```twig Old: diff --git a/fr/checkboxes-fields.md b/fr/checkboxes-fields.md index 20d9b89adc0..68979d0f899 100644 --- a/fr/checkboxes-fields.md +++ b/fr/checkboxes-fields.md @@ -16,12 +16,12 @@ When [querying for elements](dev/element-queries/README.md) that have a Checkbox Possible values include: -| Value | Fetches elements… -| - | - -| `'foo'` | with a `foo` option checked. -| `'not foo'` | without a `foo` option checked. -| `['foo', 'bar']` | with `foo` or `bar` options selected. -| `['and', 'foo', 'bar']` | with `foo` and `bar` options selected. +| Value | Fetches elements… | +| ----------------------- | -------------------------------------- | +| `'foo'` | with a `foo` option checked. | +| `'not foo'` | without a `foo` option checked. | +| `['foo', 'bar']` | with `foo` or `bar` options selected. | +| `['and', 'foo', 'bar']` | with `foo` and `bar` options selected. | ```twig {# Fetch entries with the 'foo' option checked #} diff --git a/fr/coc.md b/fr/coc.md index 3eae5b65b2e..72e264a6310 100644 --- a/fr/coc.md +++ b/fr/coc.md @@ -6,7 +6,7 @@ Diversity is one of our strengths. With that, challenges will arise that can lea This isn’t an exhaustive list of things that you can’t do. Rather, take it in the spirit in which it’s intended - a guide to make it easier to enrich all of us and the technical communities in which we participate. -This code of conduct applies to all spaces used by the Craft community for communication. This includes Craft Slack, Craft CMS Stack Exchange, GitHub, Twitter, Facebook, meetups, conferences, and any other relevant forums. Violations of this code outside of any spaces managed by the Craft team will still affect a person’s ability to participate within them. +This code of conduct applies to all spaces used by the Craft community for communication. This includes Craft Discord, Craft CMS Stack Exchange, GitHub, Twitter, Facebook, meetups, conferences, and any other relevant forums. Violations of this code outside of any spaces managed by the Craft team will still affect a person’s ability to participate within them. If you believe someone is violating the code of conduct, we ask that you report it by contacting us from [craftcms.com/contact](https://craftcms.com/contact). We take all reports seriously, and your identity will remain confidential. diff --git a/fr/config/app.md b/fr/config/app.md index e91ea9a65f6..581a14a1ef4 100644 --- a/fr/config/app.md +++ b/fr/config/app.md @@ -14,6 +14,31 @@ Craft’s default configuration is defined by [src/config/app.php](https://githu By default, Craft will store data caches in the `storage/runtime/cache/` folder. You can configure Craft to use alternative [cache storage](https://www.yiiframework.com/doc/guide/2.0/en/caching-data#supported-cache-storage) by overriding the `cache` application component from `config/app.php`. +#### Database Cache Example + +If you want to store data caches in the database, first you will need to create a `cache` table as specified by . Craft provides a CLI command for convenience: + +```bash +./craft setup/db-cache-table +``` + +Once that’s done, you can set your `cache` application component to use . + +```php + [ + 'cache' => craft\cache\DbCache::class, + ], +]; +``` + +::: tip +If you’ve already configured Craft to use rather than , you can safely switch to the latter if you remove your `cache` table’s `dateCreated`, `dateUpdated`, and `uid` columns. +::: + +#### APC Example + ```php [ 'class' => yii\caching\ApcCache::class, 'useApcu' => true, + 'keyPrefix' => 'a_unique_key', ], ], ]; ``` + #### Memcached Example ```php @@ -49,6 +76,7 @@ return [ 'weight' => 1, ], ], + 'keyPrefix' => 'a_unique_key', ], ], ]; @@ -71,14 +99,59 @@ return [ 'cache' => [ 'class' => yii\redis\Cache::class, 'defaultDuration' => 86400, + 'keyPrefix' => 'a_unique_key', ], ], ]; ``` +## Database Component + +If you need to configure the database connection beyond what’s possible with Craft’s [database config settings](db-settings.md), you can do that by overriding the `db` component: + +```php + [ + 'db' => function() { + // Get the default component config + $config = craft\helpers\App::dbConfig(); + + // Use read/write query splitting + // (requires Craft 3.4.25 or later) + + // Define the default config for replica DB connections + $config['replicaConfig'] = [ + 'username' => getenv('DB_REPLICA_USER'), + 'password' => getenv('DB_REPLICA_PASSWORD'), + 'tablePrefix' => getenv('DB_TABLE_PREFIX'), + 'attributes' => [ + // Use a smaller connection timeout + PDO::ATTR_TIMEOUT => 10, + ], + 'charset' => 'utf8', + ]; + + // Define the replica DB connections + $config['replicas'] = [ + ['dsn' => getenv('DB_REPLICA_DSN_1')], + ['dsn' => getenv('DB_REPLICA_DSN_2')], + ['dsn' => getenv('DB_REPLICA_DSN_3')], + ['dsn' => getenv('DB_REPLICA_DSN_4')], + ]; + + // Instantiate and return it + return Craft::createObject($config); + }, + ], +]; +``` + ## Session Component -In a load-balanced environment, you may want to override the default `session` component to store PHP session data in a centralized location (e.g. Redis): +In a load-balanced environment, you may want to override the default `session` component to store PHP session data in a centralized location. + +#### Redis Example ```php 6379, 'password' => getenv('REDIS_PASSWORD'), ], - 'session' => [ - 'class' => yii\redis\Session::class, - 'as session' => craft\behaviors\SessionBehavior::class, - ], + 'session' => function() { + // Get the default component config + $config = craft\helpers\App::sessionConfig(); + + // Override the class to use Redis' session class + $config['class'] = yii\redis\Session::class; + + // Instantiate and return it + return Craft::createObject($config); + }, + ], +]; +``` + +#### Database Example + +First, you must create the database table that will store PHP’s sessions. You can do that by running the `craft setup/php-session-table` console command from your project’s root folder. + +```php + [ + 'session' => function() { + // Get the default component config + $config = craft\helpers\App::sessionConfig(); + + // Override the class to use DB session class + $config['class'] = yii\web\DbSession::class; + + // Set the session table name + $config['sessionTable'] = craft\db\Table::PHPSESSIONS; + + // Instantiate and return it + return Craft::createObject($config); + }, ], ]; ``` @@ -157,7 +261,7 @@ return [ Available drivers are listed in the [Yii2 Queue Extension documentation](https://github.com/yiisoft/yii2-queue/tree/master/docs/guide). ::: warning -Only drivers that implement will be visible within the Control Panel. +Only drivers that implement will be visible within the control panel. ::: ::: tip diff --git a/fr/config/config-settings.md b/fr/config/config-settings.md index df9bdf3d254..f5fa08dfc6e 100644 --- a/fr/config/config-settings.md +++ b/fr/config/config-settings.md @@ -55,7 +55,7 @@ Defined by -The URI segment Craft should look for when determining if the current request should first be routed to a controller action. +The URI segment Craft should look for when determining if the current request should be routed to a controller action. @@ -78,7 +78,7 @@ Defined by -The URI that users without access to the Control Panel should be redirected to after activating their account. +The URI that users without access to the control panel should be redirected to after activating their account. See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. @@ -147,13 +147,18 @@ Defined by [GeneralConfig::$allowAdminChanges](api:craft\config\GeneralConfig::$allowAdminChanges) +Since +: + +3.1.0 + Whether admins should be allowed to make administrative changes to the system. If this is disabled, the Settings and Plugin Store sections will be hidden, the Craft edition and Craft/plugin versions will be locked, and the project config will become read-only. -Therefore you should only disable this in production environments when [useProjectConfigFile](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#useprojectconfigfile) is enabled, and you have a deployment workflow that runs `composer install` automatically on deploy. +Therefore you should only disable this in production environments when is enabled, and you have a deployment workflow that runs `composer install` automatically on deploy. ::: warning Don’t disable this setting until **all** environments have been updated to Craft 3.1.0 or later. @@ -203,9 +208,9 @@ Defined by -Whether Craft should allow system and plugin updates in the Control Panel, and plugin installation from the Plugin Store. +Whether Craft should allow system and plugin updates in the control panel, and plugin installation from the Plugin Store. -This setting will automatically be disabled if [allowAdminChanges](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#allowadminchanges) is disabled. +This setting will automatically be disabled if is disabled. @@ -356,12 +361,12 @@ Defined by -The base URL that Craft should use when generating Control Panel URLs. +The base URL that Craft should use when generating control panel URLs. It will be determined automatically if left blank. ::: tip -The base CP URL should **not** include the [CP trigger word](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#cptrigger) (e.g. `/admin`). +The base control panel URL should **not** include the [control panel trigger word](config:cpTrigger) (e.g. `/admin`). ::: @@ -464,6 +469,10 @@ Defined by Whether uploaded filenames with non-ASCII characters should be converted to ASCII (i.e. `ñ` → `n`). +::: tip +You can run `./craft utils/ascii-filenames` in your terminal to apply ASCII filenames to all existing assets. +::: + ### `cooldownDuration` @@ -512,7 +521,7 @@ Defined by -The URI segment Craft should look for when determining if the current request should route to the Control Panel rather than the front-end website. +The URI segment Craft should look for when determining if the current request should route to the control panel rather than the front-end website. @@ -535,7 +544,7 @@ Defined by -The name of CSRF token used for CSRF validation if [enableCsrfProtection](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#enablecsrfprotection) is set to `true`. +The name of CSRF token used for CSRF validation if is set to `true`. @@ -581,7 +590,7 @@ Defined by -The default language the Control Panel should use for users who haven’t set a preferred language yet. +The default language the control panel should use for users who haven’t set a preferred language yet. @@ -835,6 +844,11 @@ Defined by [GeneralConfig::$disabledPlugins](api:craft\config\GeneralConfig::$disabledPlugins) +Since +: + +3.1.9 + Array of plugin handles that should be disabled, regardless of what the project config says. @@ -891,7 +905,7 @@ Defined by -Whether to use a cookie to persist the CSRF token if [enableCsrfProtection](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#enablecsrfprotection) is enabled. If false, the CSRF token will be stored in session under the `csrfTokenName` config setting name. Note that while storing CSRF tokens in session increases security, it requires starting a session for every page that a CSRF token is need, which may degrade site performance. +Whether to use a cookie to persist the CSRF token if is enabled. If false, the CSRF token will be stored in session under the `csrfTokenName` config setting name. Note that while storing CSRF tokens in session increases security, it requires starting a session for every page that a CSRF token is needed, which may degrade site performance. @@ -935,6 +949,11 @@ Defined by [GeneralConfig::$enableGql](api:craft\config\GeneralConfig::$enableGql) +Since +: + +3.3.1 + Whether the GraphQL API should be enabled. @@ -943,6 +962,38 @@ Note that the GraphQL API is only available for Craft Pro. +### `enableGraphQlCaching` + +Allowed types +: + +[boolean](http://php.net/language.types.boolean) + +Default value +: + +`true` + +Defined by +: + +[GeneralConfig::$enableGraphQlCaching](api:craft\config\GeneralConfig::$enableGraphQlCaching) + +Since +: + +3.3.12 + + + +Whether Craft should cache GraphQL queries. + +If set to `true`, Craft will cache the results for unique GraphQL queries per access token. The cache is automatically invalidated any time an element is saved, the site structure is updated, or a GraphQL schema is saved. + +This setting will have no effect if a plugin is using the [craft\services\Gql::EVENT_BEFORE_EXECUTE_GQL_QUERY](https://docs.craftcms.com/api/v3/craft-services-gql.html#event-before-execute-gql-query) event to provide its own caching logic and setting the `result` property. + + + ### `enableTemplateCaching` Allowed types @@ -1010,7 +1061,7 @@ Defined by -List of file extensions that will be merged into the [allowedFileExtensions](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#allowedfileextensions) config setting. +List of file extensions that will be merged into the config setting. @@ -1031,6 +1082,11 @@ Defined by [GeneralConfig::$extraAppLocales](api:craft\config\GeneralConfig::$extraAppLocales) +Since +: + +3.0.24 + List of extra locale IDs that the application should support, and users should be able to select as their Preferred Language. @@ -1056,9 +1112,14 @@ Defined by [GeneralConfig::$extraFileKinds](api:craft\config\GeneralConfig::$extraFileKinds) +Since +: + +3.0.37 + -List of additional file kinds Craft should support. This array will get merged with the one defined in `\craft\config\craft\helpers\Assets::_buildFileKinds()`. +List of additional file kinds Craft should support. This array will get merged with the one defined in `\craft\helpers\Assets::_buildFileKinds()`. ```php 'extraFileKinds' => [ @@ -1075,7 +1136,7 @@ List of additional file kinds Craft should support. This array will get merged w ``` ::: tip -File extensions listed here won’t immediately be allowed to be uploaded. You will also need to list them with the [extraAllowedFileExtensions](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#extraallowedfileextensions) config setting. +File extensions listed here won’t immediately be allowed to be uploaded. You will also need to list them with the config setting. ::: @@ -1143,18 +1204,27 @@ Defined by [GeneralConfig::$headlessMode](api:craft\config\GeneralConfig::$headlessMode) +Since +: + +3.3.0 -Bool Whether the system should run in Headless Mode, which optimizes the system and Control Panel for headless CMS implementations. + +Whether the system should run in Headless Mode, which optimizes the system and control panel for headless CMS implementations. When this is enabled, the following changes will take place: -- URI Format settings for sections and category groups will be hidden. +- Template settings for sections and category groups will be hidden. - Template route management will be hidden. - Front-end routing will skip checks for element and template requests. - Front-end responses will be JSON-formatted rather than HTML by default. - Twig will be configured to escape unsafe strings for JavaScript/JSON rather than HTML by default for front-end requests. +- The , , , and settings will be ignored. +::: tip +When Headless Mode is enabled, users will not be able to set an initial password, set a new password, or verify their email address unless they have the "Access the control panel" permission. Make sure to grant this permission to content editors and administrators who should be able to log into the control panel. +::: ### `imageDriver` @@ -1351,6 +1421,8 @@ Defined by The URI Craft should use for user login on the front-end. +This can be set to `false` to disable front-end login. + See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. @@ -1376,10 +1448,35 @@ Defined by The URI Craft should use for user logout on the front-end. +This can be set to `false` to disable front-end logout. + See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. +### `maxBackups` + +Allowed types +: + +[integer](http://php.net/language.types.integer), [false](http://php.net/language.types.boolean) + +Default value +: + +`20` + +Defined by +: + +[GeneralConfig::$maxBackups](api:craft\config\GeneralConfig::$maxBackups) + + + +The number of backups that Craft should make before it starts deleting the oldest backups. If it is set to `false`, then Craft will not delete any backups. + + + ### `maxCachedCloudImageSize` Allowed types @@ -1443,6 +1540,11 @@ Defined by [GeneralConfig::$maxRevisions](api:craft\config\GeneralConfig::$maxRevisions) +Since +: + +3.2.0 + The maximum number of revisions that should be stored for each element. @@ -1583,7 +1685,7 @@ The string preceding a number which Craft will look for when determining if the | `?page` | `/news?page=5` | ::: tip -If you want to set this to `?p` (e.g. `/news?p=5`), you will need to change your [pathParam](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#pathparam) setting as well, which is set to `p` by default, and if your server is running Apache, you will need to update the redirect code in your `.htaccess` file to match your new `pathParam` value. +If you want to set this to `?p` (e.g. `/news?p=5`), you will need to change your setting as well, which is set to `p` by default, and if your server is running Apache, you will need to update the redirect code in your `.htaccess` file to match your new `pathParam` value. ::: @@ -1682,9 +1784,9 @@ Defined by -The path that users should be redirected to after logging in from the Control Panel. +The path that users should be redirected to after logging in from the control panel. -This setting will also come into effect if the user visits the CP’s Login page (`/admin/login`) or the CP’s root URL (/admin) when they are already logged in. +This setting will also come into effect if a user visits the control panel’s Login page (`/admin/login`) or the control panel’s root URL (/admin) when they are already logged in. See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. @@ -1759,11 +1861,16 @@ Defined by [GeneralConfig::$preserveCmykColorspace](api:craft\config\GeneralConfig::$preserveCmykColorspace) +Since +: + +3.0.8 + -Whether CMYK should be preserved as the colorspace when when manipulating images. +Whether CMYK should be preserved as the colorspace when manipulating images. -Setting this to `true` will prevent Craft from transforming CMYK images to sRGB, but on some ImageMagick versions can cause color distortion in the image. This will only have effect if ImageMagick is in use. +Setting this to `true` will prevent Craft from transforming CMYK images to sRGB, but on some ImageMagick versions it can cause color distortion in the image. This will only have effect if ImageMagick is in use. @@ -1838,7 +1945,7 @@ Defined by -When set to `false` and you go through the "forgot password" workflow on the Control Panel login page, for example, you get distinct messages saying if the username/email didn't exist or the email was successfully sent and to check your email for further instructions. This can allow for username/email enumeration based on the response. If set `true`, you will always get a successful response even if there was an error making it difficult to enumerate users. +When set to `false` and you go through the "forgot password" workflow on the control panel login page, for example, you get distinct messages saying if the username/email didn't exist or the email was successfully sent and to check your email for further instructions. This can allow for username/email enumeration based on the response. If set `true`, you will always get a successful response even if there was an error making it difficult to enumerate users. @@ -1913,6 +2020,11 @@ Defined by [GeneralConfig::$purgeStaleUserSessionDuration](api:craft\config\GeneralConfig::$purgeStaleUserSessionDuration) +Since +: + +3.3.0 + The amount of time to wait before Craft purges stale user sessions from the sessions table in the database. @@ -1940,6 +2052,11 @@ Defined by [GeneralConfig::$purgeUnsavedDraftsDuration](api:craft\config\GeneralConfig::$purgeUnsavedDraftsDuration) +Since +: + +3.2.0 + The amount of time to wait before Craft purges drafts of new elements that were never formally saved. @@ -1969,7 +2086,7 @@ Defined by -The amount of time Craft will remember a username and pre-populate it on the CP login page. +The amount of time Craft will remember a username and pre-populate it on the control panel’s Login page. Set to `0` to disable this feature altogether. @@ -2069,7 +2186,7 @@ Defined by -The path to the root directory that should store published CP resources. +The path to the root directory that should store published control panel resources. @@ -2092,7 +2209,7 @@ Defined by -The URL to the root directory that should store published CP resources. +The URL to the root directory that should store published control panel resources. @@ -2117,7 +2234,7 @@ Defined by The shell command that Craft should execute to restore a database backup. -By default Craft will run `mysql` or `psql`, provided that those libraries are in the `$PATH` variable for the user the web server is running as. +By default Craft will run `mysql` or `psql`, provided that those libraries are in the `$PATH` variable for the user the web server is running as. There are several tokens you can use that Craft will swap out at runtime: @@ -2174,18 +2291,18 @@ Defined by -Whether Craft should run pending queue jobs automatically over HTTP requests. +Whether Craft should run pending queue jobs automatically when someone visits the control panel. -This setting should be disabled for servers running Win32, or with Apache’s mod_deflate/mod_gzip installed, where PHP’s [flush()](http://php.net/manual/en/function.flush.php) method won’t work. +If disabled, an alternate queue worker *must* be set up separately, either as an [always-running daemon](https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/worker.md), or a cron job that runs the `queue/run` command every minute: -If disabled, an alternate queue runner *must* be set up separately. - -Here is an example of how you would setup a queue runner from a cron job that ran every minute: - -```text -/1 * * * * /path/to/project/root/craft queue/run +```cron +* * * * * /path/to/project/craft queue/run ``` +::: tip +This setting should be disabled for servers running Win32, or with Apache’s mod_deflate/mod_gzip installed, where PHP’s [flush()](http://php.net/manual/en/function.flush.php) method won’t work. +::: + ### `sameSiteCookieValue` @@ -2216,7 +2333,7 @@ The [SameSite](https://www.owasp.org/index.php/SameSite) value that should be se This can be set to `'Lax'`, `'Strict'`, or `null`. -::: note +::: tip This setting requires PHP 7.3 or later. ::: @@ -2368,10 +2485,14 @@ Defined by -The password-reset template path. Note that this only affects front-end site requests. +The URI Craft should use for Set Password forms on the front-end. See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. +::: tip +You might also want to set in case a user clicks on an expired password reset link. +::: + ### `setPasswordSuccessPath` @@ -2447,7 +2568,7 @@ The base URL to the site(s). If set, it will take precedence over the Base URL s This can be set to a string, which will override the primary site’s base URL only, or an array with site handles used as the keys. -The URL(s) must begin with either `http://`, `https://`, `//` (protocol-relative), or an [alias](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#aliases). +The URL(s) must begin with either `http://`, `https://`, `//` (protocol-relative), or an [alias](config:aliases). ```php 'siteUrl' => [ @@ -2498,6 +2619,11 @@ Defined by [GeneralConfig::$softDeleteDuration](api:craft\config\GeneralConfig::$softDeleteDuration) +Since +: + +3.1.0 + The amount of time before a soft-deleted item will be up for hard-deletion by garbage collection. @@ -2525,6 +2651,11 @@ Defined by [GeneralConfig::$storeUserIps](api:craft\config\GeneralConfig::$storeUserIps) +Since +: + +3.1.0 + Whether user IP addresses should be stored/logged by the system. @@ -2621,6 +2752,11 @@ Defined by [GeneralConfig::$transformGifs](api:craft\config\GeneralConfig::$transformGifs) +Since +: + +3.0.7 + Whether GIF files should be cleansed/transformed. @@ -2677,6 +2813,34 @@ By default, all hosts are trusted. +### `upscaleImages` + +Allowed types +: + +[boolean](http://php.net/language.types.boolean) + +Default value +: + +`true` + +Defined by +: + +[GeneralConfig::$upscaleImages](api:craft\config\GeneralConfig::$upscaleImages) + +Since +: + +3.4.0 + + + +Whether images should be upscaled if the provided transform size is larger than the image. + + + ### `useCompressedJs` Allowed types @@ -2696,7 +2860,7 @@ Defined by -Whether Craft should use compressed JavaScript files whenever possible. +Whether Craft should include minified JavaScript files whenever possible, and minify JavaScript code passed to `\craft\web\View::includeJs()` or `{% js %}` Twig tags. @@ -2771,7 +2935,7 @@ Defined by Whether Craft should specify the path using `PATH_INFO` or as a query string parameter when generating URLs. -Note that this setting only takes effect if [omitScriptNameInUrls](https://docs.craftcms.com/api/v3/craft-config-generalconfig.html#omitscriptnameinurls) is set to false. +Note that this setting only takes effect if is set to false. @@ -2792,6 +2956,11 @@ Defined by [GeneralConfig::$useProjectConfigFile](api:craft\config\GeneralConfig::$useProjectConfigFile) +Since +: + +3.1.0 + Whether the project config should be saved out to `config/project.yaml`. @@ -2906,6 +3075,36 @@ See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/ +### `verifyEmailPath` + +Allowed types +: + +`mixed` + +Default value +: + +`'verifyemail'` + +Defined by +: + +[GeneralConfig::$verifyEmailPath](api:craft\config\GeneralConfig::$verifyEmailPath) + +Since +: + +3.4.0 + + + +The URI Craft should use for email verification links on the front-end. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + ### `verifyEmailSuccessPath` Allowed types @@ -2923,9 +3122,14 @@ Defined by [GeneralConfig::$verifyEmailSuccessPath](api:craft\config\GeneralConfig::$verifyEmailSuccessPath) +Since +: + +3.1.20 + -The URI that users without access to the Control Panel should be redirected to after verifying a new email address. +The URI that users without access to the control panel should be redirected to after verifying a new email address. See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. diff --git a/fr/config/db-settings.md b/fr/config/db-settings.md index cc900dd1e91..dd060578722 100644 --- a/fr/config/db-settings.md +++ b/fr/config/db-settings.md @@ -10,13 +10,13 @@ For example, in a new Craft 3 project, your `.env` file should define these envi ENVIRONMENT="dev" SECURITY_KEY="" DB_DRIVER="mysql" -DB_SERVER="localhost" +DB_SERVER="" +DB_PORT="" +DB_DATABASE="" DB_USER="root" DB_PASSWORD="" -DB_DATABASE="" DB_SCHEMA="public" DB_TABLE_PREFIX="" -DB_PORT="" ``` The variables that start with `DB_` are database connection settings, and they get pulled into `config/db.php` like this: @@ -25,15 +25,19 @@ The variables that start with `DB_` are database connection settings, and they g return [ 'driver' => getenv('DB_DRIVER'), 'server' => getenv('DB_SERVER'), + 'port' => getenv('DB_PORT'), + 'database' => getenv('DB_DATABASE'), 'user' => getenv('DB_USER'), 'password' => getenv('DB_PASSWORD'), - 'database' => getenv('DB_DATABASE'), 'schema' => getenv('DB_SCHEMA'), 'tablePrefix' => getenv('DB_TABLE_PREFIX'), - 'port' => getenv('DB_PORT') ]; ``` +::: tip +NOTE You may also provide a `DB_DSN` environment variable. If defined, Craft will use that. +::: + We recommend this environment variable approach for two reasons: 1. It keeps sensitive information out of your project’s codebase. (`.env` files should never be shared or committed to Git.) @@ -109,7 +113,7 @@ Allowed types Default value : -`''` +`null` Defined by : @@ -132,7 +136,7 @@ Allowed types Default value : -`self::DRIVER_MYSQL` +`null` Defined by : @@ -164,10 +168,12 @@ Defined by -If you want to manually specify your PDO DSN connection string you can do so here. +The Data Source Name (“DSN”) that tells Craft how to connect to the database. -- MySQL: http://php.net/manual/en/ref.pdo-mysql.connection.php -- PostgreSQL: http://php.net/manual/en/ref.pdo-pgsql.connection.php If you set this, then the [server](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#server), [port](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#port), [user](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#user), [password](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#password), [database](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#database), [driver](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#driver) and [unixSocket](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#unixsocket) config settings will be ignored. +DSNs should begin with a driver prefix (`mysql:` or `pgsql:`), followed by driver-specific parameters. For example, `mysql:host=127.0.0.1;port=3306;dbname=acme_corp`. + +- MySQL parameters: http://php.net/manual/en/ref.pdo-mysql.connection.php +- PostgreSQL parameters: http://php.net/manual/en/ref.pdo-pgsql.connection.php @@ -250,7 +256,7 @@ Allowed types Default value : -`'localhost'` +`null` Defined by : @@ -259,7 +265,7 @@ Defined by -The database server name or IP address. Usually 'localhost' or '127.0.0.1'. +The database server name or IP address. Usually `localhost` or `127.0.0.1`. diff --git a/fr/config/environments.md b/fr/config/environments.md index 2153bad2d82..44e8fe8c7c6 100644 --- a/fr/config/environments.md +++ b/fr/config/environments.md @@ -4,7 +4,7 @@ Some settings should be defined on a per-environment basis. For example, when de ## Control Panel Settings -Some settings in the Control Panel can be set to environment variables (like the ones defined in your `.env` file): +Some settings in the control panel can be set to environment variables (like the ones defined in your `.env` file): - General Settings - **System Name** diff --git a/fr/config/php-constants.md b/fr/config/php-constants.md index 076c26fa83d..e5a9f175a38 100644 --- a/fr/config/php-constants.md +++ b/fr/config/php-constants.md @@ -36,6 +36,10 @@ The environment name that [multi-environment configs](environments.md#multi-envi define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production'); ``` +### `CRAFT_EPHEMERAL` + +When defined as `true`, Craft will skip file system permission checks and operations that are not available in an environment with ephemeral or read-only storage. + ### `CRAFT_LICENSE_KEY` Your Craft license key, if for some reason that must be defined by PHP rather than a license key file. (Don’t set this until you have a valid license key.) diff --git a/fr/date-time-fields.md b/fr/date-time-fields.md index ceb5a50108a..86c51120da8 100644 --- a/fr/date-time-fields.md +++ b/fr/date-time-fields.md @@ -29,7 +29,7 @@ Possible values include: {% set end = now|date_modify('+1 month')|atom %} {% set entries = craft.entries() - .('and', ">= #{start}", "< #{end}") + .(['and', ">= #{start}", "< #{end}"]) .all() %} ``` @@ -93,16 +93,21 @@ The [HTML5Forms.js](https://github.com/zoltan-dulac/html5Forms.js) polyfill can #### Customizing the Timezone -By default, Craft will assume the date is posted in UTC. As of Craft 3.1.6 you you can post dates in a different timezone by changing the input name to `fields[][datetime]` and adding a hidden input named `fields[][timezone]`, set to a [valid PHP timezone](http://php.net/manual/en/timezones.php): +By default, Craft will assume the date is posted in UTC. As of Craft 3.1.6 you can post dates in a different timezone by changing the input name to `fields[][datetime]` and adding a hidden input named `fields[][timezone]`, set to a [valid PHP timezone](http://php.net/manual/en/timezones.php): ```twig -{% set pt = 'America/Los_Angeles' %} +{# Use the timezone selected under Settings → General Settings → Time Zone #} +{% set tz = craft.app.getTimezone() %} + +{# Or set a specific timezone #} +{% set tz = 'America/Los_Angeles' %} + {% set currentValue = entry is defined and entry. - ? entry.|date('Y-m-d\\TH:i', timezone=pt) + ? entry.|date('Y-m-d\\TH:i', tz) : '' %} -{{ hiddenInput('fields[][timezone]', pt) }} +{{ hiddenInput('fields[][timezone]', tz) }} ``` Or you can let users decide which timezone the date should be posted in: diff --git a/fr/dev/eager-loading-elements.md b/fr/dev/eager-loading-elements.md index 405db1e9773..a0005880bd7 100644 --- a/fr/dev/eager-loading-elements.md +++ b/fr/dev/eager-loading-elements.md @@ -117,7 +117,7 @@ It’s also possible to load *nested* sets of elements, using this syntax: ### Defining Custom Parameters on Eager-Loaded Elements -You can define custom criteria parameters that will get applied as elements are being eager-loaded, by replacing its key with an array that has two values: the key, and an object that defines the criteria parameters that should be applied. +You can define custom criteria parameters that will get applied as elements are being eager-loaded, by replacing its key with an array that has two values: the key, and a [hash](twig-primer.md#hashes) that defines the criteria parameters that should be applied. ```twig {% set entries = craft.entries() @@ -176,7 +176,7 @@ This problem can be solved with the `withTransforms` asset criteria parameter: .all() %} ``` -Note that each transform definition you want to eager-load can either be a string (the handle of a transform defined in Settings → Assets → Image Transforms) or an object that defines the transform properties. +Note that each transform definition you want to eager-load can either be a string (the handle of a transform defined in Settings → Assets → Image Transforms) or a [hash](twig-primer.md#hashes) that defines the transform properties. Using the `withTransforms` param has no effect on how you’d access image transforms further down in the template. diff --git a/fr/dev/element-queries/asset-queries.md b/fr/dev/element-queries/asset-queries.md index a8c7546a04e..9457e146282 100644 --- a/fr/dev/element-queries/asset-queries.md +++ b/fr/dev/element-queries/asset-queries.md @@ -45,12 +45,53 @@ We can display a list of thumbnails for images in a “Photos” volume by doing ``` +::: warning +When using `asset.url` or `asset.getUrl()`, the asset’s source volume must have “Assets in this volume have public URLs” enabled and a “Base URL” setting. Otherwise, the result will always be empty. +::: + ## Parameters Asset queries support the following parameters: +| Param | Description | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [anyStatus](#anystatus) | Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. | +| [asArray](#asarray) | Causes the query to return matching assets as arrays of data, rather than [Asset](api:craft\elements\Asset) objects. | +| [clearCachedResult](#clearcachedresult) | Clears the cached result. | +| [dateCreated](#datecreated) | Narrows the query results based on the assets’ creation dates. | +| [dateModified](#datemodified) | Narrows the query results based on the assets’ files’ last-modified dates. | +| [dateUpdated](#dateupdated) | Narrows the query results based on the assets’ last-updated dates. | +| [filename](#filename) | Narrows the query results based on the assets’ filenames. | +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). | +| [folderId](#folderid) | Narrows the query results based on the folders the assets belong to, per the folders’ IDs. | +| [height](#height) | Narrows the query results based on the assets’ image heights. | +| [id](#id) | Narrows the query results based on the assets’ IDs. | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). | +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. | +| [includeSubfolders](#includesubfolders) | Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). | +| [kind](#kind) | Narrows the query results based on the assets’ file kinds. | +| [limit](#limit) | Determines the number of assets that should be returned. | +| [offset](#offset) | Determines how many assets should be skipped in the results. | +| [orderBy](#orderby) | Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) | +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. | +| [relatedTo](#relatedto) | Narrows the query results to only assets that are related to certain other elements. | +| [search](#search) | Narrows the query results to only assets that match a search query. | +| [site](#site) | Determines which site(s) the assets should be queried in. | +| [siteId](#siteid) | Determines which site(s) the assets should be queried in, per the site’s ID. | +| [size](#size) | Narrows the query results based on the assets’ file sizes (in bytes). | +| [title](#title) | Narrows the query results based on the assets’ titles. | +| [trashed](#trashed) | Narrows the query results to only assets that have been soft-deleted. | +| [uid](#uid) | Narrows the query results based on the assets’ UIDs. | +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. | +| [uploader](#uploader) | Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. | +| [volume](#volume) | Narrows the query results based on the volume the assets belong to. | +| [volumeId](#volumeid) | Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. | +| [width](#width) | Narrows the query results based on the assets’ image widths. | +| [with](#with) | Causes the query to return matching assets eager-loaded with related elements. | +| [withTransforms](#withtransforms) | Causes the query to return matching assets eager-loaded with image transform indexes. | + ### `anyStatus` Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. @@ -101,6 +142,15 @@ $assets = \craft\elements\Asset::find() ::: +### `clearCachedResult` + +Clears the cached result. + + + + + + ### `dateCreated` Narrows the query results based on the assets’ creation dates. @@ -212,128 +262,6 @@ $assets = \craft\elements\Asset::find() ::: -### `draftCreator` - -Narrows the query results to only drafts created by a given user. - - - -Possible values include: - -| Value | Fetches drafts… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch drafts by the current user #} -{% set assets = craft.assets() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch drafts by the current user -$assets = \craft\elements\Asset::find() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `draftId` - -Narrows the query results based on the assets’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… | -| ----- | ------------------------------ | -| `1` | for the draft with an ID of 1. | - - - -::: code -```twig -{# Fetch a draft #} -{% set assets = craft.assets() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$assets = \craft\elements\Asset::find() - ->draftIf(10) - ->all(); -``` -::: - - -### `draftOf` - -Narrows the query results to only drafts of a given asset. - - - -Possible values include: - -| Value | Fetches drafts… | -| -------------------------------------------- | ---------------------------------------- | -| `1` | for the asset with an ID of 1. | -| a [Asset](api:craft\elements\Asset) object | for the asset represented by the object. | - - - -::: code -```twig -{# Fetch drafts of the asset #} -{% set assets = craft.assets() - .draftOf(myAsset) - .all() %} -``` - -```php -// Fetch drafts of the asset -$assets = \craft\elements\Asset::find() - ->draftOf($myAsset) - ->all(); -``` -::: - - -### `drafts` - -Narrows the query results to only drafts assets. - - - - - -::: code -```twig -{# Fetch a draft asset #} -{% set assets = {twig-function} - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft asset -$assets = \craft\elements\Asset::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - ### `filename` Narrows the query results based on the assets’ filenames. @@ -402,7 +330,7 @@ Narrows the query results based on the folders the assets belong to, per the fol Possible values include: -| Value | Fetches categories… | +| Value | Fetches assets… | | --------------- | ------------------------------------- | | `1` | in a folder with an ID of 1. | | `'not 1'` | not in a folder with an ID of 1. | @@ -420,7 +348,7 @@ Possible values include: ``` ```php -// Fetch categories in the folder with an ID of 1 +// Fetch assets in the folder with an ID of 1 $assets = \craft\elements\Asset::find() ->folderId(1) ->all(); @@ -559,7 +487,7 @@ Broadens the query results to include assets from any of the subfolders of the f ``` ```php -// Fetch categories in the folder with an ID of 1 (including its subfolders) +// Fetch assets in the folder with an ID of 1 (including its subfolders) $assets = \craft\elements\Asset::find() ->folderId(1) ->includeSubfolders() @@ -673,7 +601,7 @@ $assets = \craft\elements\Asset::find() ### `orderBy` -Determines the order that the assets should be returned in. +Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) @@ -754,128 +682,6 @@ $assets = \craft\elements\Asset::find() ::: -### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set assets = craft.assets() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$assets = \craft\elements\Asset::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `revisionId` - -Narrows the query results based on the assets’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… | -| ----- | --------------------------------- | -| `1` | for the revision with an ID of 1. | - - - -::: code -```twig -{# Fetch a revision #} -{% set assets = craft.assets() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$assets = \craft\elements\Asset::find() - ->revisionIf(10) - ->all(); -``` -::: - - -### `revisionOf` - -Narrows the query results to only revisions of a given asset. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------------- | ---------------------------------------- | -| `1` | for the asset with an ID of 1. | -| a [Asset](api:craft\elements\Asset) object | for the asset represented by the object. | - - - -::: code -```twig -{# Fetch revisions of the asset #} -{% set assets = craft.assets() - .revisionOf(myAsset) - .all() %} -``` - -```php -// Fetch revisions of the asset -$assets = \craft\elements\Asset::find() - ->revisionOf($myAsset) - ->all(); -``` -::: - - -### `revisions` - -Narrows the query results to only revision assets. - - - - - -::: code -```twig -{# Fetch a revision asset #} -{% set assets = {twig-function} - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision asset -$assets = \craft\elements\Asset::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - ### `search` Narrows the query results to only assets that match a search query. @@ -919,13 +725,13 @@ The current site will be used by default. Possible values include: -| Value | Fetches assets… | -| -------------------------------------- | ---------------------------------------------- | -| `'foo'` | from the site with a handle of `foo`. | -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | -| a `\craft\elements\db\Site` object | from the site represented by the object. | -| `'*'` | from any site. | +| Value | Fetches assets… | +| ------------------------------------------------------- | ---------------------------------------------- | +| `'foo'` | from the site with a handle of `foo`. | +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | +| a [craft\models\Site](api:craft\models\Site) object | from the site represented by the object. | +| `'*'` | from any site. | ::: tip If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use [unique](#unique) in conjunction with this. @@ -1124,13 +930,43 @@ $assets = \craft\elements\Asset::find() ::: +### `uploader` + +Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. + +Possible values include: + +| Value | Fetches assets… | +| ----------------------------------------------------------- | ----------------------------------------------- | +| `1` | uploaded by the user with an ID of 1. | +| a [craft\elements\User](api:craft\elements\User) object | uploaded by the user represented by the object. | + + + +::: code +```twig +{# Fetch assets uploaded by the user with an ID of 1 #} +{% set assets = craft.assets() + .uploader(1) + .all() %} +``` + +```php +// Fetch assets uploaded by the user with an ID of 1 +$assets = \craft\elements\Asset::find() + ->uploader(1) + ->all(); +``` +::: + + ### `volume` Narrows the query results based on the volume the assets belong to. Possible values include: -| Value | Fetches categories… | +| Value | Fetches assets… | | ------------------------------------------ | ------------------------------------------------ | | `'foo'` | in a volume with a handle of `foo`. | | `'not foo'` | not in a volume with a handle of `foo`. | @@ -1163,7 +999,7 @@ Narrows the query results based on the volumes the assets belong to, per the vol Possible values include: -| Value | Fetches categories… | +| Value | Fetches assets… | | --------------- | ------------------------------------- | | `1` | in a volume with an ID of 1. | | `'not 1'` | not in a volume with an ID of 1. | @@ -1181,7 +1017,7 @@ Possible values include: ``` ```php -// Fetch categories in the volume with an ID of 1 +// Fetch assets in the volume with an ID of 1 $assets = \craft\elements\Asset::find() ->volumeId(1) ->all(); diff --git a/fr/dev/element-queries/category-queries.md b/fr/dev/element-queries/category-queries.md index 2f566e1dd7b..a244c460c94 100644 --- a/fr/dev/element-queries/category-queries.md +++ b/fr/dev/element-queries/category-queries.md @@ -57,6 +57,49 @@ Category queries support the following parameters: +| Param | Description | +| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [ancestorDist](#ancestordist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). | +| [ancestorOf](#ancestorof) | Narrows the query results to only categories that are ancestors of another category. | +| [anyStatus](#anystatus) | Clears out the [status](#status) and [enabledForSite](#enabledforsite) parameters. | +| [asArray](#asarray) | Causes the query to return matching categories as arrays of data, rather than [Category](api:craft\elements\Category) objects. | +| [clearCachedResult](#clearcachedresult) | Clears the cached result. | +| [dateCreated](#datecreated) | Narrows the query results based on the categories’ creation dates. | +| [dateUpdated](#dateupdated) | Narrows the query results based on the categories’ last-updated dates. | +| [descendantDist](#descendantdist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). | +| [descendantOf](#descendantof) | Narrows the query results to only categories that are descendants of another category. | +| [enabledForSite](#enabledforsite) | Narrows the query results based on whether the categories are enabled in the site they’re being queried in, per the [site](#site) parameter. | +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). | +| [group](#group) | Narrows the query results based on the category groups the categories belong to. | +| [groupId](#groupid) | Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. | +| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the categories have any descendants. | +| [id](#id) | Narrows the query results based on the categories’ IDs. | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). | +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. | +| [leaves](#leaves) | Narrows the query results based on whether the categories are “leaves” (categories with no descendants). | +| [level](#level) | Narrows the query results based on the categories’ level within the structure. | +| [limit](#limit) | Determines the number of categories that should be returned. | +| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the category that comes immediately after another category. | +| [offset](#offset) | Determines how many categories should be skipped in the results. | +| [orderBy](#orderby) | Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`.) | +| [positionedAfter](#positionedafter) | Narrows the query results to only categories that are positioned after another category. | +| [positionedBefore](#positionedbefore) | Narrows the query results to only categories that are positioned before another category. | +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. | +| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the category that comes immediately before another category. | +| [relatedTo](#relatedto) | Narrows the query results to only categories that are related to certain other elements. | +| [search](#search) | Narrows the query results to only categories that match a search query. | +| [siblingOf](#siblingof) | Narrows the query results to only categories that are siblings of another category. | +| [site](#site) | Determines which site(s) the categories should be queried in. | +| [siteId](#siteid) | Determines which site(s) the categories should be queried in, per the site’s ID. | +| [slug](#slug) | Narrows the query results based on the categories’ slugs. | +| [status](#status) | Narrows the query results based on the categories’ statuses. | +| [title](#title) | Narrows the query results based on the categories’ titles. | +| [trashed](#trashed) | Narrows the query results to only categories that have been soft-deleted. | +| [uid](#uid) | Narrows the query results based on the categories’ UIDs. | +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. | +| [uri](#uri) | Narrows the query results based on the categories’ URIs. | +| [with](#with) | Causes the query to return matching categories eager-loaded with related elements. | + ### `ancestorDist` Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). @@ -172,6 +215,15 @@ $categories = \craft\elements\Category::find() ::: +### `clearCachedResult` + +Clears the cached result. + + + + + + ### `dateCreated` Narrows the query results based on the categories’ creation dates. @@ -313,128 +365,6 @@ This can be combined with [descendantDist](#descendantdist) if you want to limit ::: -### `draftCreator` - -Narrows the query results to only drafts created by a given user. - - - -Possible values include: - -| Value | Fetches drafts… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch drafts by the current user #} -{% set categories = craft.categories() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch drafts by the current user -$categories = \craft\elements\Category::find() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `draftId` - -Narrows the query results based on the categories’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… | -| ----- | ------------------------------ | -| `1` | for the draft with an ID of 1. | - - - -::: code -```twig -{# Fetch a draft #} -{% set categories = craft.categories() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$categories = \craft\elements\Category::find() - ->draftIf(10) - ->all(); -``` -::: - - -### `draftOf` - -Narrows the query results to only drafts of a given category. - - - -Possible values include: - -| Value | Fetches drafts… | -| -------------------------------------------------- | ------------------------------------------- | -| `1` | for the category with an ID of 1. | -| a [Category](api:craft\elements\Category) object | for the category represented by the object. | - - - -::: code -```twig -{# Fetch drafts of the category #} -{% set categories = craft.categories() - .draftOf(myCategory) - .all() %} -``` - -```php -// Fetch drafts of the category -$categories = \craft\elements\Category::find() - ->draftOf($myCategory) - ->all(); -``` -::: - - -### `drafts` - -Narrows the query results to only drafts categories. - - - - - -::: code -```twig -{# Fetch a draft category #} -{% set categories = {twig-function} - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft category -$categories = \craft\elements\Category::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - ### `enabledForSite` Narrows the query results based on whether the categories are enabled in the site they’re being queried in, per the [site](#site) parameter. @@ -445,7 +375,7 @@ Possible values include: | Value | Fetches categories… | | ------------------ | -------------------------------------------- | -| `true` *(default)* | that are enabled in the site. | +| `true` _(default)_ | that are enabled in the site. | | `false` | whether they are enabled or not in the site. | @@ -602,7 +532,6 @@ Possible values include: | `['not', 1, 2]` | not with an ID of 1 or 2. | - ::: code ```twig {# Fetch the category by its ID #} @@ -806,7 +735,7 @@ $categories = \craft\elements\Category::find() ### `orderBy` -Determines the order that the categories should be returned in. +Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`.) @@ -983,128 +912,6 @@ $categories = \craft\elements\Category::find() ::: -### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set categories = craft.categories() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$categories = \craft\elements\Category::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `revisionId` - -Narrows the query results based on the categories’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… | -| ----- | --------------------------------- | -| `1` | for the revision with an ID of 1. | - - - -::: code -```twig -{# Fetch a revision #} -{% set categories = craft.categories() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$categories = \craft\elements\Category::find() - ->revisionIf(10) - ->all(); -``` -::: - - -### `revisionOf` - -Narrows the query results to only revisions of a given category. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------------------- | ------------------------------------------- | -| `1` | for the category with an ID of 1. | -| a [Category](api:craft\elements\Category) object | for the category represented by the object. | - - - -::: code -```twig -{# Fetch revisions of the category #} -{% set categories = craft.categories() - .revisionOf(myCategory) - .all() %} -``` - -```php -// Fetch revisions of the category -$categories = \craft\elements\Category::find() - ->revisionOf($myCategory) - ->all(); -``` -::: - - -### `revisions` - -Narrows the query results to only revision categories. - - - - - -::: code -```twig -{# Fetch a revision category #} -{% set categories = {twig-function} - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision category -$categories = \craft\elements\Category::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - ### `search` Narrows the query results to only categories that match a search query. @@ -1180,13 +987,13 @@ The current site will be used by default. Possible values include: -| Value | Fetches categories… | -| -------------------------------------- | ---------------------------------------------- | -| `'foo'` | from the site with a handle of `foo`. | -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | -| a `\craft\elements\db\Site` object | from the site represented by the object. | -| `'*'` | from any site. | +| Value | Fetches categories… | +| ------------------------------------------------------- | ---------------------------------------------- | +| `'foo'` | from the site with a handle of `foo`. | +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | +| a [craft\models\Site](api:craft\models\Site) object | from the site represented by the object. | +| `'*'` | from any site. | ::: tip If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use [unique](#unique) in conjunction with this. @@ -1289,10 +1096,10 @@ Narrows the query results based on the categories’ statuses. Possible values include: -| Value | Fetches categories… | -| ----------------------- | ------------------- | -| `'enabled'` *(default)* | that are enabled. | -| `'disabled'` | that are disabled. | +| Value | Fetches categories… | +| ------------------------ | ------------------- | +| `'enabled'` _(default)_ | that are enabled. | +| `'disabled'` | that are disabled. | diff --git a/fr/dev/element-queries/entry-queries.md b/fr/dev/element-queries/entry-queries.md index 63649b9764e..61c0f983a5c 100644 --- a/fr/dev/element-queries/entry-queries.md +++ b/fr/dev/element-queries/entry-queries.md @@ -53,6 +53,66 @@ Entry queries support the following parameters: +| Param | Description | +| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [after](#after) | Narrows the query results to only entries that were posted on or after a certain date. | +| [ancestorDist](#ancestordist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). | +| [ancestorOf](#ancestorof) | Narrows the query results to only entries that are ancestors of another entry. | +| [anyStatus](#anystatus) | Clears out the [status](#status) and [enabledForSite](#enabledforsite) parameters. | +| [asArray](#asarray) | Causes the query to return matching entries as arrays of data, rather than [Entry](api:craft\elements\Entry) objects. | +| [authorGroup](#authorgroup) | Narrows the query results based on the user group the entries’ authors belong to. | +| [authorGroupId](#authorgroupid) | Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. | +| [authorId](#authorid) | Narrows the query results based on the entries’ authors. | +| [before](#before) | Narrows the query results to only entries that were posted before a certain date. | +| [clearCachedResult](#clearcachedresult) | Clears the cached result. | +| [dateCreated](#datecreated) | Narrows the query results based on the entries’ creation dates. | +| [dateUpdated](#dateupdated) | Narrows the query results based on the entries’ last-updated dates. | +| [descendantDist](#descendantdist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). | +| [descendantOf](#descendantof) | Narrows the query results to only entries that are descendants of another entry. | +| [draftCreator](#draftcreator) | Narrows the query results to only drafts created by a given user. | +| [draftId](#draftid) | Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). | +| [draftOf](#draftof) | Narrows the query results to only drafts of a given entry. | +| [drafts](#drafts) | Narrows the query results to only drafts entries. | +| [enabledForSite](#enabledforsite) | Narrows the query results based on whether the entries are enabled in the site they’re being queried in, per the [site](#site) parameter. | +| [expiryDate](#expirydate) | Narrows the query results based on the entries’ expiry dates. | +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). | +| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the entries have any descendants. | +| [id](#id) | Narrows the query results based on the entries’ IDs. | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). | +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. | +| [leaves](#leaves) | Narrows the query results based on whether the entries are “leaves” (entries with no descendants). | +| [level](#level) | Narrows the query results based on the entries’ level within the structure. | +| [limit](#limit) | Determines the number of entries that should be returned. | +| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the entry that comes immediately after another entry. | +| [offset](#offset) | Determines how many entries should be skipped in the results. | +| [orderBy](#orderby) | Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`.) | +| [positionedAfter](#positionedafter) | Narrows the query results to only entries that are positioned after another entry. | +| [positionedBefore](#positionedbefore) | Narrows the query results to only entries that are positioned before another entry. | +| [postDate](#postdate) | Narrows the query results based on the entries’ post dates. | +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. | +| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the entry that comes immediately before another entry. | +| [relatedTo](#relatedto) | Narrows the query results to only entries that are related to certain other elements. | +| [revisionCreator](#revisioncreator) | Narrows the query results to only revisions created by a given user. | +| [revisionId](#revisionid) | Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). | +| [revisionOf](#revisionof) | Narrows the query results to only revisions of a given entry. | +| [revisions](#revisions) | Narrows the query results to only revision entries. | +| [search](#search) | Narrows the query results to only entries that match a search query. | +| [section](#section) | Narrows the query results based on the sections the entries belong to. | +| [sectionId](#sectionid) | Narrows the query results based on the sections the entries belong to, per the sections’ IDs. | +| [siblingOf](#siblingof) | Narrows the query results to only entries that are siblings of another entry. | +| [site](#site) | Determines which site(s) the entries should be queried in. | +| [siteId](#siteid) | Determines which site(s) the entries should be queried in, per the site’s ID. | +| [slug](#slug) | Narrows the query results based on the entries’ slugs. | +| [status](#status) | Narrows the query results based on the entries’ statuses. | +| [title](#title) | Narrows the query results based on the entries’ titles. | +| [trashed](#trashed) | Narrows the query results to only entries that have been soft-deleted. | +| [type](#type) | Narrows the query results based on the entries’ entry types. | +| [typeId](#typeid) | Narrows the query results based on the entries’ entry types, per the types’ IDs. | +| [uid](#uid) | Narrows the query results based on the entries’ UIDs. | +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. | +| [uri](#uri) | Narrows the query results based on the entries’ URIs. | +| [with](#with) | Causes the query to return matching entries eager-loaded with related elements. | + ### `after` Narrows the query results to only entries that were posted on or after a certain date. @@ -333,6 +393,15 @@ $entries = \craft\elements\Entry::find() ::: +### `clearCachedResult` + +Clears the cached result. + + + + + + ### `dateCreated` Narrows the query results based on the entries’ creation dates. @@ -482,10 +551,10 @@ Narrows the query results to only drafts created by a given user. Possible values include: -| Value | Fetches drafts… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | +| Value | Fetches drafts… | +| ----------------------------------------------------------- | ---------------------------------------------- | +| `1` | created by the user with an ID of 1. | +| a [craft\elements\User](api:craft\elements\User) object | created by the user represented by the object. | @@ -531,7 +600,7 @@ Possible values include: ```php // Fetch a draft $entries = \craft\elements\Entry::find() - ->draftIf(10) + ->draftId(10) ->all(); ``` ::: @@ -606,7 +675,7 @@ Possible values include: | Value | Fetches entries… | | ------------------ | -------------------------------------------- | -| `true` *(default)* | that are enabled in the site. | +| `true` _(default)_ | that are enabled in the site. | | `false` | whether they are enabled or not in the site. | @@ -939,7 +1008,7 @@ $entries = \craft\elements\Entry::find() ### `orderBy` -Determines the order that the entries should be returned in. +Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`.) @@ -1161,10 +1230,10 @@ Narrows the query results to only revisions created by a given user. Possible values include: -| Value | Fetches revisions… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | +| Value | Fetches revisions… | +| ----------------------------------------------------------- | ---------------------------------------------- | +| `1` | created by the user with an ID of 1. | +| a [craft\elements\User](api:craft\elements\User) object | created by the user represented by the object. | @@ -1415,13 +1484,13 @@ The current site will be used by default. Possible values include: -| Value | Fetches entries… | -| -------------------------------------- | ---------------------------------------------- | -| `'foo'` | from the site with a handle of `foo`. | -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | -| a `\craft\elements\db\Site` object | from the site represented by the object. | -| `'*'` | from any site. | +| Value | Fetches entries… | +| ------------------------------------------------------- | ---------------------------------------------- | +| `'foo'` | from the site with a handle of `foo`. | +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | +| a [craft\models\Site](api:craft\models\Site) object | from the site represented by the object. | +| `'*'` | from any site. | ::: tip If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use [unique](#unique) in conjunction with this. @@ -1524,7 +1593,7 @@ Possible values include: | Value | Fetches entries… | | --------------------- | ----------------------------------------------------------- | -| `'live'` *(default)* | that are live. | +| `'live'` _(default)_ | that are live. | | `'pending'` | that are pending (enabled with a Post Date in the future). | | `'expired'` | that are expired (enabled with an Expiry Date in the past). | | `'disabled'` | that are disabled. | diff --git a/fr/dev/element-queries/global-set-queries.md b/fr/dev/element-queries/global-set-queries.md index 147c133d095..a64e1467878 100644 --- a/fr/dev/element-queries/global-set-queries.md +++ b/fr/dev/element-queries/global-set-queries.md @@ -51,6 +51,31 @@ Global set queries support the following parameters: +| Param | Description | +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [anyStatus](#anystatus) | Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. | +| [asArray](#asarray) | Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](api:craft\elements\GlobalSet) objects. | +| [clearCachedResult](#clearcachedresult) | Clears the cached result. | +| [dateCreated](#datecreated) | Narrows the query results based on the global sets’ creation dates. | +| [dateUpdated](#dateupdated) | Narrows the query results based on the global sets’ last-updated dates. | +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). | +| [handle](#handle) | Narrows the query results based on the global sets’ handles. | +| [id](#id) | Narrows the query results based on the global sets’ IDs. | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). | +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. | +| [limit](#limit) | Determines the number of global sets that should be returned. | +| [offset](#offset) | Determines how many global sets should be skipped in the results. | +| [orderBy](#orderby) | Determines the order that the global sets should be returned in. (If empty, defaults to `name ASC`.) | +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. | +| [relatedTo](#relatedto) | Narrows the query results to only global sets that are related to certain other elements. | +| [search](#search) | Narrows the query results to only global sets that match a search query. | +| [site](#site) | Determines which site(s) the global sets should be queried in. | +| [siteId](#siteid) | Determines which site(s) the global sets should be queried in, per the site’s ID. | +| [trashed](#trashed) | Narrows the query results to only global sets that have been soft-deleted. | +| [uid](#uid) | Narrows the query results based on the global sets’ UIDs. | +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. | +| [with](#with) | Causes the query to return matching global sets eager-loaded with related elements. | + ### `anyStatus` Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. @@ -101,6 +126,15 @@ $globalSets = \craft\elements\GlobalSet::find() ::: +### `clearCachedResult` + +Clears the cached result. + + + + + + ### `dateCreated` Narrows the query results based on the global sets’ creation dates. @@ -177,128 +211,6 @@ $globalSets = \craft\elements\GlobalSet::find() ::: -### `draftCreator` - -Narrows the query results to only drafts created by a given user. - - - -Possible values include: - -| Value | Fetches drafts… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch drafts by the current user #} -{% set globalSets = craft.globalSets() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch drafts by the current user -$globalSets = \craft\elements\GlobalSet::find() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `draftId` - -Narrows the query results based on the global sets’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… | -| ----- | ------------------------------ | -| `1` | for the draft with an ID of 1. | - - - -::: code -```twig -{# Fetch a draft #} -{% set globalSets = craft.globalSets() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$globalSets = \craft\elements\GlobalSet::find() - ->draftIf(10) - ->all(); -``` -::: - - -### `draftOf` - -Narrows the query results to only drafts of a given global set. - - - -Possible values include: - -| Value | Fetches drafts… | -| ---------------------------------------------------- | --------------------------------------------- | -| `1` | for the global set with an ID of 1. | -| a [GlobalSet](api:craft\elements\GlobalSet) object | for the global set represented by the object. | - - - -::: code -```twig -{# Fetch drafts of the global set #} -{% set globalSets = craft.globalSets() - .draftOf(myGlobalSet) - .all() %} -``` - -```php -// Fetch drafts of the global set -$globalSets = \craft\elements\GlobalSet::find() - ->draftOf($myGlobalSet) - ->all(); -``` -::: - - -### `drafts` - -Narrows the query results to only drafts global sets. - - - - - -::: code -```twig -{# Fetch a draft global set #} -{% set globalSets = {twig-function} - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft global set -$globalSets = \craft\elements\GlobalSet::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - ### `fixedOrder` Causes the query results to be returned in the order specified by [id](#id). @@ -484,7 +396,7 @@ $globalSets = \craft\elements\GlobalSet::find() ### `orderBy` -Determines the order that the global sets should be returned in. +Determines the order that the global sets should be returned in. (If empty, defaults to `name ASC`.) @@ -565,128 +477,6 @@ $globalSets = \craft\elements\GlobalSet::find() ::: -### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set globalSets = craft.globalSets() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$globalSets = \craft\elements\GlobalSet::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `revisionId` - -Narrows the query results based on the global sets’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… | -| ----- | --------------------------------- | -| `1` | for the revision with an ID of 1. | - - - -::: code -```twig -{# Fetch a revision #} -{% set globalSets = craft.globalSets() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$globalSets = \craft\elements\GlobalSet::find() - ->revisionIf(10) - ->all(); -``` -::: - - -### `revisionOf` - -Narrows the query results to only revisions of a given global set. - - - -Possible values include: - -| Value | Fetches revisions… | -| ---------------------------------------------------- | --------------------------------------------- | -| `1` | for the global set with an ID of 1. | -| a [GlobalSet](api:craft\elements\GlobalSet) object | for the global set represented by the object. | - - - -::: code -```twig -{# Fetch revisions of the global set #} -{% set globalSets = craft.globalSets() - .revisionOf(myGlobalSet) - .all() %} -``` - -```php -// Fetch revisions of the global set -$globalSets = \craft\elements\GlobalSet::find() - ->revisionOf($myGlobalSet) - ->all(); -``` -::: - - -### `revisions` - -Narrows the query results to only revision global sets. - - - - - -::: code -```twig -{# Fetch a revision global set #} -{% set globalSets = {twig-function} - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision global set -$globalSets = \craft\elements\GlobalSet::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - ### `search` Narrows the query results to only global sets that match a search query. @@ -730,13 +520,13 @@ The current site will be used by default. Possible values include: -| Value | Fetches global sets… | -| -------------------------------------- | ---------------------------------------------- | -| `'foo'` | from the site with a handle of `foo`. | -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | -| a `\craft\elements\db\Site` object | from the site represented by the object. | -| `'*'` | from any site. | +| Value | Fetches global sets… | +| ------------------------------------------------------- | ---------------------------------------------- | +| `'foo'` | from the site with a handle of `foo`. | +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | +| a [craft\models\Site](api:craft\models\Site) object | from the site represented by the object. | +| `'*'` | from any site. | ::: tip If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use [unique](#unique) in conjunction with this. diff --git a/fr/dev/element-queries/matrix-block-queries.md b/fr/dev/element-queries/matrix-block-queries.md index 709ce881e43..a66d788b14e 100644 --- a/fr/dev/element-queries/matrix-block-queries.md +++ b/fr/dev/element-queries/matrix-block-queries.md @@ -54,6 +54,67 @@ Matrix block queries support the following parameters: +| Param | Description | +| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [allowOwnerDrafts](#allowownerdrafts) | Narrows the query results based on whether the Matrix blocks’ owners are drafts. | +| [allowOwnerRevisions](#allowownerrevisions) | Narrows the query results based on whether the Matrix blocks’ owners are revisions. | +| [anyStatus](#anystatus) | Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. | +| [asArray](#asarray) | Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](api:craft\elements\MatrixBlock) objects. | +| [clearCachedResult](#clearcachedresult) | Clears the cached result. | +| [dateCreated](#datecreated) | Narrows the query results based on the Matrix blocks’ creation dates. | +| [dateUpdated](#dateupdated) | Narrows the query results based on the Matrix blocks’ last-updated dates. | +| [field](#field) | Narrows the query results based on the field the Matrix blocks belong to. | +| [fieldId](#fieldid) | Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. | +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). | +| [id](#id) | Narrows the query results based on the Matrix blocks’ IDs. | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). | +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. | +| [limit](#limit) | Determines the number of Matrix blocks that should be returned. | +| [offset](#offset) | Determines how many Matrix blocks should be skipped in the results. | +| [orderBy](#orderby) | Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) | +| [owner](#owner) | Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. | +| [ownerId](#ownerid) | Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. | +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. | +| [relatedTo](#relatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. | +| [search](#search) | Narrows the query results to only Matrix blocks that match a search query. | +| [site](#site) | Determines which site(s) the Matrix blocks should be queried in. | +| [siteId](#siteid) | Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. | +| [status](#status) | Narrows the query results based on the Matrix blocks’ statuses. | +| [trashed](#trashed) | Narrows the query results to only Matrix blocks that have been soft-deleted. | +| [type](#type) | Narrows the query results based on the Matrix blocks’ block types. | +| [typeId](#typeid) | Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. | +| [uid](#uid) | Narrows the query results based on the Matrix blocks’ UIDs. | +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. | +| [with](#with) | Causes the query to return matching Matrix blocks eager-loaded with related elements. | + +### `allowOwnerDrafts` + +Narrows the query results based on whether the Matrix blocks’ owners are drafts. + +Possible values include: + +| Value | Fetches Matrix blocks… | +| ------- | ------------------------------- | +| `true` | which can belong to a draft. | +| `false` | which cannot belong to a draft. | + + + + +### `allowOwnerRevisions` + +Narrows the query results based on whether the Matrix blocks’ owners are revisions. + +Possible values include: + +| Value | Fetches Matrix blocks… | +| ------- | ---------------------------------- | +| `true` | which can belong to a revision. | +| `false` | which cannot belong to a revision. | + + + + ### `anyStatus` Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. @@ -104,6 +165,15 @@ $MatrixBlocks = \craft\elements\MatrixBlock::find() ::: +### `clearCachedResult` + +Clears the cached result. + + + + + + ### `dateCreated` Narrows the query results based on the Matrix blocks’ creation dates. @@ -180,128 +250,39 @@ $MatrixBlocks = \craft\elements\MatrixBlock::find() ::: -### `draftCreator` - -Narrows the query results to only drafts created by a given user. - +### `field` +Narrows the query results based on the field the Matrix blocks belong to. Possible values include: -| Value | Fetches drafts… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | +| Value | Fetches Matrix blocks… | +| ----------------------------------------------------------- | ----------------------------------------------- | +| `'foo'` | in a field with a handle of `foo`. | +| `'not foo'` | not in a field with a handle of `foo`. | +| `['foo', 'bar']` | in a field with a handle of `foo` or `bar`. | +| `['not', 'foo', 'bar']` | not in a field with a handle of `foo` or `bar`. | +| a [craft\fields\Matrix](api:craft\fields\Matrix) object | in a field represented by the object. | ::: code ```twig -{# Fetch drafts by the current user #} +{# Fetch Matrix blocks in the Foo field #} {% set MatrixBlocks = craft.matrixBlocks() - .draftCreator(currentUser) + .field('foo') .all() %} ``` ```php -// Fetch drafts by the current user +// Fetch Matrix blocks in the Foo field $MatrixBlocks = \craft\elements\MatrixBlock::find() - ->draftCreator(Craft::$app->user->identity) + ->field('foo') ->all(); ``` ::: -### `draftId` - -Narrows the query results based on the Matrix blocks’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… | -| ----- | ------------------------------ | -| `1` | for the draft with an ID of 1. | - - - -::: code -```twig -{# Fetch a draft #} -{% set MatrixBlocks = craft.matrixBlocks() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->draftIf(10) - ->all(); -``` -::: - - -### `draftOf` - -Narrows the query results to only drafts of a given Matrix block. - - - -Possible values include: - -| Value | Fetches drafts… | -| -------------------------------------------------------- | ----------------------------------------------- | -| `1` | for the Matrix block with an ID of 1. | -| a [MatrixBlock](api:craft\elements\MatrixBlock) object | for the Matrix block represented by the object. | - - - -::: code -```twig -{# Fetch drafts of the Matrix block #} -{% set MatrixBlocks = craft.matrixBlocks() - .draftOf(myBlock) - .all() %} -``` - -```php -// Fetch drafts of the Matrix block -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->draftOf($myBlock) - ->all(); -``` -::: - - -### `drafts` - -Narrows the query results to only drafts Matrix blocks. - - - - - -::: code -```twig -{# Fetch a draft Matrix block #} -{% set MatrixBlocks = {twig-function} - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft Matrix block -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - ### `fieldId` Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. @@ -487,7 +468,7 @@ $MatrixBlocks = \craft\elements\MatrixBlock::find() ### `orderBy` -Determines the order that the Matrix blocks should be returned in. +Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) @@ -623,128 +604,6 @@ $MatrixBlocks = \craft\elements\MatrixBlock::find() ::: -### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set MatrixBlocks = craft.matrixBlocks() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `revisionId` - -Narrows the query results based on the Matrix blocks’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… | -| ----- | --------------------------------- | -| `1` | for the revision with an ID of 1. | - - - -::: code -```twig -{# Fetch a revision #} -{% set MatrixBlocks = craft.matrixBlocks() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->revisionIf(10) - ->all(); -``` -::: - - -### `revisionOf` - -Narrows the query results to only revisions of a given Matrix block. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------------------------- | ----------------------------------------------- | -| `1` | for the Matrix block with an ID of 1. | -| a [MatrixBlock](api:craft\elements\MatrixBlock) object | for the Matrix block represented by the object. | - - - -::: code -```twig -{# Fetch revisions of the Matrix block #} -{% set MatrixBlocks = craft.matrixBlocks() - .revisionOf(myBlock) - .all() %} -``` - -```php -// Fetch revisions of the Matrix block -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->revisionOf($myBlock) - ->all(); -``` -::: - - -### `revisions` - -Narrows the query results to only revision Matrix blocks. - - - - - -::: code -```twig -{# Fetch a revision Matrix block #} -{% set MatrixBlocks = {twig-function} - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision Matrix block -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - ### `search` Narrows the query results to only Matrix blocks that match a search query. @@ -788,13 +647,13 @@ The current site will be used by default. Possible values include: -| Value | Fetches Matrix blocks… | -| -------------------------------------- | ---------------------------------------------- | -| `'foo'` | from the site with a handle of `foo`. | -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | -| a `\craft\elements\db\Site` object | from the site represented by the object. | -| `'*'` | from any site. | +| Value | Fetches Matrix blocks… | +| ------------------------------------------------------- | ---------------------------------------------- | +| `'foo'` | from the site with a handle of `foo`. | +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | +| a [craft\models\Site](api:craft\models\Site) object | from the site represented by the object. | +| `'*'` | from any site. | ::: tip If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use [unique](#unique) in conjunction with this. @@ -854,10 +713,10 @@ Narrows the query results based on the Matrix blocks’ statuses. Possible values include: -| Value | Fetches Matrix blocks… | -| ----------------------- | ---------------------- | -| `'enabled'` *(default)* | that are enabled. | -| `'disabled'` | that are disabled. | +| Value | Fetches Matrix blocks… | +| ------------------------ | ---------------------- | +| `'enabled'` _(default)_ | that are enabled. | +| `'disabled'` | that are disabled. | diff --git a/fr/dev/element-queries/tag-queries.md b/fr/dev/element-queries/tag-queries.md index 5c12b2cf2ef..823999f269d 100644 --- a/fr/dev/element-queries/tag-queries.md +++ b/fr/dev/element-queries/tag-queries.md @@ -50,6 +50,34 @@ Tag queries support the following parameters: +| Param | Description | +| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [anyStatus](#anystatus) | Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. | +| [asArray](#asarray) | Causes the query to return matching tags as arrays of data, rather than [Tag](api:craft\elements\Tag) objects. | +| [clearCachedResult](#clearcachedresult) | Clears the cached result. | +| [dateCreated](#datecreated) | Narrows the query results based on the tags’ creation dates. | +| [dateUpdated](#dateupdated) | Narrows the query results based on the tags’ last-updated dates. | +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). | +| [group](#group) | Narrows the query results based on the tag groups the tags belong to. | +| [groupId](#groupid) | Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. | +| [id](#id) | Narrows the query results based on the tags’ IDs. | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). | +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. | +| [limit](#limit) | Determines the number of tags that should be returned. | +| [offset](#offset) | Determines how many tags should be skipped in the results. | +| [orderBy](#orderby) | Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) | +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. | +| [relatedTo](#relatedto) | Narrows the query results to only tags that are related to certain other elements. | +| [search](#search) | Narrows the query results to only tags that match a search query. | +| [site](#site) | Determines which site(s) the tags should be queried in. | +| [siteId](#siteid) | Determines which site(s) the tags should be queried in, per the site’s ID. | +| [title](#title) | Narrows the query results based on the tags’ titles. | +| [trashed](#trashed) | Narrows the query results to only tags that have been soft-deleted. | +| [uid](#uid) | Narrows the query results based on the tags’ UIDs. | +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. | +| [uri](#uri) | Narrows the query results based on the tags’ URIs. | +| [with](#with) | Causes the query to return matching tags eager-loaded with related elements. | + ### `anyStatus` Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. @@ -100,6 +128,15 @@ $tags = \craft\elements\Tag::find() ::: +### `clearCachedResult` + +Clears the cached result. + + + + + + ### `dateCreated` Narrows the query results based on the tags’ creation dates. @@ -176,128 +213,6 @@ $tags = \craft\elements\Tag::find() ::: -### `draftCreator` - -Narrows the query results to only drafts created by a given user. - - - -Possible values include: - -| Value | Fetches drafts… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch drafts by the current user #} -{% set tags = craft.tags() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch drafts by the current user -$tags = \craft\elements\Tag::find() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `draftId` - -Narrows the query results based on the tags’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… | -| ----- | ------------------------------ | -| `1` | for the draft with an ID of 1. | - - - -::: code -```twig -{# Fetch a draft #} -{% set tags = craft.tags() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$tags = \craft\elements\Tag::find() - ->draftIf(10) - ->all(); -``` -::: - - -### `draftOf` - -Narrows the query results to only drafts of a given tag. - - - -Possible values include: - -| Value | Fetches drafts… | -| ---------------------------------------- | -------------------------------------- | -| `1` | for the tag with an ID of 1. | -| a [Tag](api:craft\elements\Tag) object | for the tag represented by the object. | - - - -::: code -```twig -{# Fetch drafts of the tag #} -{% set tags = craft.tags() - .draftOf(myTag) - .all() %} -``` - -```php -// Fetch drafts of the tag -$tags = \craft\elements\Tag::find() - ->draftOf($myTag) - ->all(); -``` -::: - - -### `drafts` - -Narrows the query results to only drafts tags. - - - - - -::: code -```twig -{# Fetch a draft tag #} -{% set tags = {twig-function} - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft tag -$tags = \craft\elements\Tag::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - ### `fixedOrder` Causes the query results to be returned in the order specified by [id](#id). @@ -516,7 +431,7 @@ $tags = \craft\elements\Tag::find() ### `orderBy` -Determines the order that the tags should be returned in. +Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) @@ -597,128 +512,6 @@ $tags = \craft\elements\Tag::find() ::: -### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… | -| -------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a `\craft\elements\db\User` object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set tags = craft.tags() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$tags = \craft\elements\Tag::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `revisionId` - -Narrows the query results based on the tags’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… | -| ----- | --------------------------------- | -| `1` | for the revision with an ID of 1. | - - - -::: code -```twig -{# Fetch a revision #} -{% set tags = craft.tags() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$tags = \craft\elements\Tag::find() - ->revisionIf(10) - ->all(); -``` -::: - - -### `revisionOf` - -Narrows the query results to only revisions of a given tag. - - - -Possible values include: - -| Value | Fetches revisions… | -| ---------------------------------------- | -------------------------------------- | -| `1` | for the tag with an ID of 1. | -| a [Tag](api:craft\elements\Tag) object | for the tag represented by the object. | - - - -::: code -```twig -{# Fetch revisions of the tag #} -{% set tags = craft.tags() - .revisionOf(myTag) - .all() %} -``` - -```php -// Fetch revisions of the tag -$tags = \craft\elements\Tag::find() - ->revisionOf($myTag) - ->all(); -``` -::: - - -### `revisions` - -Narrows the query results to only revision tags. - - - - - -::: code -```twig -{# Fetch a revision tag #} -{% set tags = {twig-function} - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision tag -$tags = \craft\elements\Tag::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - ### `search` Narrows the query results to only tags that match a search query. @@ -762,13 +555,13 @@ The current site will be used by default. Possible values include: -| Value | Fetches tags… | -| -------------------------------------- | ---------------------------------------------- | -| `'foo'` | from the site with a handle of `foo`. | -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | -| a `\craft\elements\db\Site` object | from the site represented by the object. | -| `'*'` | from any site. | +| Value | Fetches tags… | +| ------------------------------------------------------- | ---------------------------------------------- | +| `'foo'` | from the site with a handle of `foo`. | +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. | +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. | +| a [craft\models\Site](api:craft\models\Site) object | from the site represented by the object. | +| `'*'` | from any site. | ::: tip If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use [unique](#unique) in conjunction with this. diff --git a/fr/dev/element-queries/user-queries.md b/fr/dev/element-queries/user-queries.md index 3873feebf2e..3499e566c11 100644 --- a/fr/dev/element-queries/user-queries.md +++ b/fr/dev/element-queries/user-queries.md @@ -50,6 +50,37 @@ User queries support the following parameters: +| Param | Description | +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [admin](#admin) | Narrows the query results to only users that have admin accounts. | +| [anyStatus](#anystatus) | Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. | +| [asArray](#asarray) | Causes the query to return matching users as arrays of data, rather than [User](api:craft\elements\User) objects. | +| [can](#can) | Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. | +| [clearCachedResult](#clearcachedresult) | Clears the cached result. | +| [dateCreated](#datecreated) | Narrows the query results based on the users’ creation dates. | +| [dateUpdated](#dateupdated) | Narrows the query results based on the users’ last-updated dates. | +| [email](#email) | Narrows the query results based on the users’ email addresses. | +| [firstName](#firstname) | Narrows the query results based on the users’ first names. | +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). | +| [group](#group) | Narrows the query results based on the user group the users belong to. | +| [groupId](#groupid) | Narrows the query results based on the user group the users belong to, per the groups’ IDs. | +| [id](#id) | Narrows the query results based on the users’ IDs. | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). | +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. | +| [lastLoginDate](#lastlogindate) | Narrows the query results based on the users’ last login dates. | +| [lastName](#lastname) | Narrows the query results based on the users’ last names. | +| [limit](#limit) | Determines the number of users that should be returned. | +| [offset](#offset) | Determines how many users should be skipped in the results. | +| [orderBy](#orderby) | Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) | +| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. | +| [relatedTo](#relatedto) | Narrows the query results to only users that are related to certain other elements. | +| [search](#search) | Narrows the query results to only users that match a search query. | +| [status](#status) | Narrows the query results based on the users’ statuses. | +| [trashed](#trashed) | Narrows the query results to only users that have been soft-deleted. | +| [uid](#uid) | Narrows the query results based on the users’ UIDs. | +| [username](#username) | Narrows the query results based on the users’ usernames. | +| [with](#with) | Causes the query to return matching users eager-loaded with related elements. | + ### `admin` Narrows the query results to only users that have admin accounts. @@ -59,14 +90,14 @@ Narrows the query results to only users that have admin accounts. ::: code ```twig {# Fetch admins #} -{% set elements = craft.queryFunction() +{% set users = craft.users() .admin() .all() %} ``` ```php // Fetch admins -$elements = ElementClass::find() +$users = \craft\elements\User::find() ->admin() ->all(); ``` @@ -83,15 +114,15 @@ Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.co ::: code ```twig -{# Fetch all elements, regardless of status #} -{% set elements = craft.queryFunction() +{# Fetch all users, regardless of status #} +{% set users = craft.users() .anyStatus() .all() %} ``` ```php -// Fetch all elements, regardless of status -$elements = ElementClass::find() +// Fetch all users, regardless of status +$users = \craft\elements\User::find() ->anyStatus() ->all(); ``` @@ -100,7 +131,7 @@ $elements = ElementClass::find() ### `asArray` -Causes the query to return matching elements as arrays of data, rather than ElementClass objects. +Causes the query to return matching users as arrays of data, rather than [User](api:craft\elements\User) objects. @@ -108,15 +139,15 @@ Causes the query to return matching elements as arrays of data, rather than Elem ::: code ```twig -{# Fetch elements as arrays #} -{% set elements = craft.queryFunction() +{# Fetch users as arrays #} +{% set users = craft.users() .asArray() .all() %} ``` ```php -// Fetch elements as arrays -$elements = ElementClass::find() +// Fetch users as arrays +$users = \craft\elements\User::find() ->asArray() ->all(); ``` @@ -133,30 +164,39 @@ See [Users](https://docs.craftcms.com/v3/users.html) for a full list of availabl ::: code ```twig -{# Fetch users that can access the Control Panel #} -{% set elements = craft.queryFunction() +{# Fetch users that can access the control panel #} +{% set users = craft.users() .can('accessCp') .all() %} ``` ```php -// Fetch users that can access the Control Panel -$elements = ElementClass::find() +// Fetch users that can access the control panel +$users = \craft\elements\User::find() ->can('accessCp') ->all(); ``` ::: +### `clearCachedResult` + +Clears the cached result. + + + + + + ### `dateCreated` -Narrows the query results based on the elements’ creation dates. +Narrows the query results based on the users’ creation dates. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ------------------------------------------------ | ---------------------------------------------------- | | `'>= 2018-04-01'` | that were created on or after 2018-04-01. | | `'< 2018-05-01'` | that were created before 2018-05-01 | @@ -166,21 +206,21 @@ Possible values include: ::: code ```twig -{# Fetch elements created last month #} +{# Fetch users created last month #} {% set start = date('first day of last month')|atom %} {% set end = date('first day of this month')|atom %} -{% set elements = craft.queryFunction() +{% set users = craft.users() .dateCreated(['and', ">= #{start}", "< #{end}"]) .all() %} ``` ```php -// Fetch elements created last month +// Fetch users created last month $start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); $end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); -$elements = ElementClass::find() +$users = \craft\elements\User::find() ->dateCreated(['and', ">= {$start}", "< {$end}"]) ->all(); ``` @@ -189,13 +229,13 @@ $elements = ElementClass::find() ### `dateUpdated` -Narrows the query results based on the elements’ last-updated dates. +Narrows the query results based on the users’ last-updated dates. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ------------------------------------------------ | ---------------------------------------------------- | | `'>= 2018-04-01'` | that were updated on or after 2018-04-01. | | `'< 2018-05-01'` | that were updated before 2018-05-01 | @@ -205,154 +245,32 @@ Possible values include: ::: code ```twig -{# Fetch elements updated in the last week #} +{# Fetch users updated in the last week #} {% set lastWeek = date('1 week ago')|atom %} -{% set elements = craft.queryFunction() +{% set users = craft.users() .dateUpdated(">= #{lastWeek}") .all() %} ``` ```php -// Fetch elements updated in the last week +// Fetch users updated in the last week $lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); -$elements = ElementClass::find() +$users = \craft\elements\User::find() ->dateUpdated(">= {$lastWeek}") ->all(); ``` ::: -### `draftCreator` - -Narrows the query results to only drafts created by a given user. - - - -Possible values include: - -| Value | Fetches drafts… | -| ----------------------------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a [craft\elements\User](api:craft\elements\User) object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch drafts by the current user #} -{% set elements = craft.queryFunction() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch drafts by the current user -$elements = ElementClass::find() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `draftId` - -Narrows the query results based on the elements’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… | -| ----- | ------------------------------ | -| `1` | for the draft with an ID of 1. | - - - -::: code -```twig -{# Fetch a draft #} -{% set elements = craft.queryFunction() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$elements = ElementClass::find() - ->draftIf(10) - ->all(); -``` -::: - - -### `draftOf` - -Narrows the query results to only drafts of a given element. - - - -Possible values include: - -| Value | Fetches drafts… | -| --------------------- | ------------------------------------------ | -| `1` | for the element with an ID of 1. | -| a ElementClass object | for the element represented by the object. | - - - -::: code -```twig -{# Fetch drafts of the element #} -{% set elements = craft.queryFunction() - .draftOf(myElement) - .all() %} -``` - -```php -// Fetch drafts of the element -$elements = ElementClass::find() - ->draftOf($myElement) - ->all(); -``` -::: - - -### `drafts` - -Narrows the query results to only drafts elements. - - - - - -::: code -```twig -{# Fetch a draft element #} -{% set elements = {twig-function} - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft element -$elements = ElementClass::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - ### `email` Narrows the query results based on the users’ email addresses. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ------------------- | ---------------------------------------- | | `'foo@bar.baz'` | with an email of `foo@bar.baz`. | | `'not foo@bar.baz'` | not with an email of `foo@bar.baz`. | @@ -363,14 +281,14 @@ Possible values include: ::: code ```twig {# Fetch users with a .co.uk domain on their email address #} -{% set elements = craft.queryFunction() +{% set users = craft.users() .email('*.co.uk') .all() %} ``` ```php // Fetch users with a .co.uk domain on their email address -$elements = ElementClass::find() +$users = \craft\elements\User::find() ->email('*.co.uk') ->all(); ``` @@ -383,7 +301,7 @@ Narrows the query results based on the users’ first names. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ------------ | -------------------------------- | | `'Jane'` | with a first name of `Jane`. | | `'not Jane'` | not with a first name of `Jane`. | @@ -393,14 +311,14 @@ Possible values include: ::: code ```twig {# Fetch all the Jane's #} -{% set elements = craft.queryFunction() +{% set users = craft.users() .firstName('Jane') .all() %} ``` ```php // Fetch all the Jane's -$elements = ElementClass::find() +$users = \craft\elements\User::find() ->firstName('Jane') ->one(); ``` @@ -417,16 +335,16 @@ Causes the query results to be returned in the order specified by [id](#id). ::: code ```twig -{# Fetch elements in a specific order #} -{% set elements = craft.queryFunction() +{# Fetch users in a specific order #} +{% set users = craft.users() .id([1, 2, 3, 4, 5]) .fixedOrder() .all() %} ``` ```php -// Fetch elements in a specific order -$elements = ElementClass::find() +// Fetch users in a specific order +$users = \craft\elements\User::find() ->id([1, 2, 3, 4, 5]) ->fixedOrder() ->all(); @@ -440,7 +358,7 @@ Narrows the query results based on the user group the users belong to. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | -------------------------------------------------- | ----------------------------------------------- | | `'foo'` | in a group with a handle of `foo`. | | `'not foo'` | not in a group with a handle of `foo`. | @@ -452,15 +370,15 @@ Possible values include: ::: code ```twig -{# Fetch elements in the Foo user group #} -{% set elements = craft.queryFunction() +{# Fetch users in the Foo user group #} +{% set users = craft.users() .group('foo') .all() %} ``` ```php -// Fetch elements in the Foo user group -$elements = ElementClass::find() +// Fetch users in the Foo user group +$users = \craft\elements\User::find() ->group('foo') ->all(); ``` @@ -473,7 +391,7 @@ Narrows the query results based on the user group the users belong to, per the g Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | --------------- | ------------------------------------ | | `1` | in a group with an ID of 1. | | `'not 1'` | not in a group with an ID of 1. | @@ -484,15 +402,15 @@ Possible values include: ::: code ```twig -{# Fetch elements in a group with an ID of 1 #} -{% set elements = craft.queryFunction() +{# Fetch users in a group with an ID of 1 #} +{% set users = craft.users() .groupId(1) .all() %} ``` ```php -// Fetch elements in a group with an ID of 1 -$elements = ElementClass::find() +// Fetch users in a group with an ID of 1 +$users = \craft\elements\User::find() ->groupId(1) ->all(); ``` @@ -501,13 +419,13 @@ $elements = ElementClass::find() ### `id` -Narrows the query results based on the elements’ IDs. +Narrows the query results based on the users’ IDs. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | --------------- | ------------------------- | | `1` | with an ID of 1. | | `'not 1'` | not with an ID of 1. | @@ -518,15 +436,15 @@ Possible values include: ::: code ```twig -{# Fetch the element by its ID #} -{% set element = craft.queryFunction() +{# Fetch the user by its ID #} +{% set user = craft.users() .id(1) .one() %} ``` ```php -// Fetch the element by its ID -$element = ElementClass::find() +// Fetch the user by its ID +$user = \craft\elements\User::find() ->id(1) ->one(); ``` @@ -541,7 +459,7 @@ This can be combined with [fixedOrder](#fixedorder) if you want the results to b ### `ignorePlaceholders` -Causes the query to return matching elements as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). @@ -562,15 +480,15 @@ Causes the query results to be returned in reverse order. ::: code ```twig -{# Fetch elements in reverse #} -{% set elements = craft.queryFunction() +{# Fetch users in reverse #} +{% set users = craft.users() .inReverse() .all() %} ``` ```php -// Fetch elements in reverse -$elements = ElementClass::find() +// Fetch users in reverse +$users = \craft\elements\User::find() ->inReverse() ->all(); ``` @@ -583,7 +501,7 @@ Narrows the query results based on the users’ last login dates. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ------------------------------------------------ | ------------------------------------------------------ | | `'>= 2018-04-01'` | that last logged-in on or after 2018-04-01. | | `'< 2018-05-01'` | that last logged-in before 2018-05-01 | @@ -593,19 +511,19 @@ Possible values include: ::: code ```twig -{# Fetch elements that logged in recently #} +{# Fetch users that logged in recently #} {% set aWeekAgo = date('7 days ago')|atom %} -{% set elements = craft.queryFunction() +{% set users = craft.users() .lastLoginDate(">= #{aWeekAgo}") .all() %} ``` ```php -// Fetch elements that logged in recently +// Fetch users that logged in recently $aWeekAgo = (new \DateTime('7 days ago'))->format(\DateTime::ATOM); -$elements = ElementClass::find() +$users = \craft\elements\User::find() ->lastLoginDate(">= {$aWeekAgo}") ->all(); ``` @@ -618,7 +536,7 @@ Narrows the query results based on the users’ last names. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ----------- | ------------------------------ | | `'Doe'` | with a last name of `Doe`. | | `'not Doe'` | not with a last name of `Doe`. | @@ -628,14 +546,14 @@ Possible values include: ::: code ```twig {# Fetch all the Doe's #} -{% set elements = craft.queryFunction() +{% set users = craft.users() .lastName('Doe') .all() %} ``` ```php // Fetch all the Doe's -$elements = ElementClass::find() +$users = \craft\elements\User::find() ->lastName('Doe') ->one(); ``` @@ -644,21 +562,21 @@ $elements = ElementClass::find() ### `limit` -Determines the number of elements that should be returned. +Determines the number of users that should be returned. ::: code ```twig -{# Fetch up to 10 elements #} -{% set elements = craft.queryFunction() +{# Fetch up to 10 users #} +{% set users = craft.users() .limit(10) .all() %} ``` ```php -// Fetch up to 10 elements -$elements = ElementClass::find() +// Fetch up to 10 users +$users = \craft\elements\User::find() ->limit(10) ->all(); ``` @@ -667,21 +585,21 @@ $elements = ElementClass::find() ### `offset` -Determines how many elements should be skipped in the results. +Determines how many users should be skipped in the results. ::: code ```twig -{# Fetch all elements except for the first 3 #} -{% set elements = craft.queryFunction() +{# Fetch all users except for the first 3 #} +{% set users = craft.users() .offset(3) .all() %} ``` ```php -// Fetch all elements except for the first 3 -$elements = ElementClass::find() +// Fetch all users except for the first 3 +$users = \craft\elements\User::find() ->offset(3) ->all(); ``` @@ -690,21 +608,21 @@ $elements = ElementClass::find() ### `orderBy` -Determines the order that the elements should be returned in. +Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) ::: code ```twig -{# Fetch all elements in order of date created #} -{% set elements = craft.queryFunction() +{# Fetch all users in order of date created #} +{% set users = craft.users() .orderBy('dateCreated asc') .all() %} ``` ```php -// Fetch all elements in order of date created -$elements = ElementClass::find() +// Fetch all users in order of date created +$users = \craft\elements\User::find() ->orderBy('dateCreated asc') ->all(); ``` @@ -725,8 +643,8 @@ If this isn’t set, then preference goes to the current site. ::: code ```twig -{# Fetch unique elements from Site A, or Site B if they don’t exist in Site A #} -{% set elements = craft.queryFunction() +{# Fetch unique users from Site A, or Site B if they don’t exist in Site A #} +{% set users = craft.users() .site('*') .unique() .preferSites(['a', 'b']) @@ -734,8 +652,8 @@ If this isn’t set, then preference goes to the current site. ``` ```php -// Fetch unique elements from Site A, or Site B if they don’t exist in Site A -$elements = ElementClass::find() +// Fetch unique users from Site A, or Site B if they don’t exist in Site A +$users = \craft\elements\User::find() ->site('*') ->unique() ->preferSites(['a', 'b']) @@ -746,7 +664,7 @@ $elements = ElementClass::find() ### `relatedTo` -Narrows the query results to only elements that are related to certain other elements. +Narrows the query results to only users that are related to certain other elements. @@ -756,146 +674,24 @@ See [Relations](https://docs.craftcms.com/v3/relations.html) for a full explanat ::: code ```twig -{# Fetch all elements that are related to myCategory #} -{% set elements = craft.queryFunction() +{# Fetch all users that are related to myCategory #} +{% set users = craft.users() .relatedTo(myCategory) .all() %} ``` ```php -// Fetch all elements that are related to $myCategory -$elements = ElementClass::find() +// Fetch all users that are related to $myCategory +$users = \craft\elements\User::find() ->relatedTo($myCategory) ->all(); ``` ::: -### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… | -| ----------------------------------------------------------- | -------------------------------------- | -| `1` | created by the user with an ID of 1. | -| a [craft\elements\User](api:craft\elements\User) object | by the user represented by the object. | - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set elements = craft.queryFunction() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$elements = ElementClass::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -### `revisionId` - -Narrows the query results based on the elements’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… | -| ----- | --------------------------------- | -| `1` | for the revision with an ID of 1. | - - - -::: code -```twig -{# Fetch a revision #} -{% set elements = craft.queryFunction() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$elements = ElementClass::find() - ->revisionIf(10) - ->all(); -``` -::: - - -### `revisionOf` - -Narrows the query results to only revisions of a given element. - - - -Possible values include: - -| Value | Fetches revisions… | -| --------------------- | ------------------------------------------ | -| `1` | for the element with an ID of 1. | -| a ElementClass object | for the element represented by the object. | - - - -::: code -```twig -{# Fetch revisions of the element #} -{% set elements = craft.queryFunction() - .revisionOf(myElement) - .all() %} -``` - -```php -// Fetch revisions of the element -$elements = ElementClass::find() - ->revisionOf($myElement) - ->all(); -``` -::: - - -### `revisions` - -Narrows the query results to only revision elements. - - - - - -::: code -```twig -{# Fetch a revision element #} -{% set elements = {twig-function} - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision element -$elements = ElementClass::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - ### `search` -Narrows the query results to only elements that match a search query. +Narrows the query results to only users that match a search query. @@ -908,8 +704,8 @@ See [Searching](https://docs.craftcms.com/v3/searching.html) for a full explanat {# Get the search query from the 'q' query string param #} {% set searchQuery = craft.app.request.getQueryParam('q') %} -{# Fetch all elements that match the search query #} -{% set elements = craft.queryFunction() +{# Fetch all users that match the search query #} +{% set users = craft.users() .search(searchQuery) .all() %} ``` @@ -918,8 +714,8 @@ See [Searching](https://docs.craftcms.com/v3/searching.html) for a full explanat // Get the search query from the 'q' query string param $searchQuery = \Craft::$app->request->getQueryParam('q'); -// Fetch all elements that match the search query -$elements = ElementClass::find() +// Fetch all users that match the search query +$users = \craft\elements\User::find() ->search($searchQuery) ->all(); ``` @@ -928,13 +724,13 @@ $elements = ElementClass::find() ### `status` -Narrows the query results based on the elements’ statuses. +Narrows the query results based on the users’ statuses. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ------------------------- | ------------------------------------------------------------------------- | -| `'active'` *(default)* | with active accounts. | +| `'active'` _(default)_ | with active accounts. | | `'suspended'` | with suspended accounts. | | `'pending'` | with accounts that are still pending activation. | | `'locked'` | with locked accounts (regardless of whether they’re active or suspended). | @@ -944,15 +740,15 @@ Possible values include: ::: code ```twig -{# Fetch active and locked elements #} -{% set elements = craft.queryFunction() +{# Fetch active and locked users #} +{% set users = craft.users() .status(['active', 'locked']) .all() %} ``` ```php -// Fetch active and locked elements -$elements = ElementClass::find() +// Fetch active and locked users +$users = \craft\elements\User::find() ->status(['active', 'locked']) ->all(); ``` @@ -961,7 +757,7 @@ $elements = ElementClass::find() ### `trashed` -Narrows the query results to only elements that have been soft-deleted. +Narrows the query results to only users that have been soft-deleted. @@ -969,15 +765,15 @@ Narrows the query results to only elements that have been soft-deleted. ::: code ```twig -{# Fetch trashed elements #} -{% set elements = craft.queryFunction() +{# Fetch trashed users #} +{% set users = craft.users() .trashed() .all() %} ``` ```php -// Fetch trashed elements -$elements = ElementClass::find() +// Fetch trashed users +$users = \craft\elements\User::find() ->trashed() ->all(); ``` @@ -986,7 +782,7 @@ $elements = ElementClass::find() ### `uid` -Narrows the query results based on the elements’ UIDs. +Narrows the query results based on the users’ UIDs. @@ -994,15 +790,15 @@ Narrows the query results based on the elements’ UIDs. ::: code ```twig -{# Fetch the element by its UID #} -{% set element = craft.queryFunction() +{# Fetch the user by its UID #} +{% set user = craft.users() .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') .one() %} ``` ```php -// Fetch the element by its UID -$element = ElementClass::find() +// Fetch the user by its UID +$user = \craft\elements\User::find() ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') ->one(); ``` @@ -1015,7 +811,7 @@ Narrows the query results based on the users’ usernames. Possible values include: -| Value | Fetches elements… | +| Value | Fetches users… | | ----------- | ----------------------------- | | `'foo'` | with a username of `foo`. | | `'not foo'` | not with a username of `foo`. | @@ -1028,7 +824,7 @@ Possible values include: {% set requestedUsername = craft.app.request.getSegment(2) %} {# Fetch that user #} -{% set element = craft.queryFunction() +{% set user = craft.users() .username(requestedUsername|literal) .one() %} ``` @@ -1038,7 +834,7 @@ Possible values include: $requestedUsername = \Craft::$app->request->getSegment(2); // Fetch that user -$element = ElementClass::find() +$user = \craft\elements\User::find() ->username(\craft\helpers\Db::escapeParam($requestedUsername)) ->one(); ``` @@ -1047,7 +843,7 @@ $element = ElementClass::find() ### `with` -Causes the query to return matching elements eager-loaded with related elements. +Causes the query to return matching users eager-loaded with related elements. @@ -1057,15 +853,15 @@ See [Eager-Loading Elements](https://docs.craftcms.com/v3/dev/eager-loading-elem ::: code ```twig -{# Fetch elements eager-loaded with the "Related" field’s relations #} -{% set elements = craft.queryFunction() +{# Fetch users eager-loaded with the "Related" field’s relations #} +{% set users = craft.users() .with(['related']) .all() %} ``` ```php -// Fetch elements eager-loaded with the "Related" field’s relations -$elements = ElementClass::find() +// Fetch users eager-loaded with the "Related" field’s relations +$users = \craft\elements\User::find() ->with(['related']) ->all(); ``` diff --git a/fr/dev/examples/entry-form.md b/fr/dev/examples/entry-form.md index 649a2d86018..79cbed59e85 100644 --- a/fr/dev/examples/entry-form.md +++ b/fr/dev/examples/entry-form.md @@ -1,54 +1,60 @@ # Entry Form -You can create a new entry form for the front-end of your site using the following code: +You can create a form for submitting new entries using the following code as a starting point: ```twig {% macro errorList(errors) %} - {% if errors %} -
    - {% for error in errors %} -
  • {{ error }}
  • - {% endfor %} -
- {% endif %} + {% if errors %} +
    + {% for error in errors %} +
  • {{ error }}
  • + {% endfor %} +
+ {% endif %} {% endmacro %} +{# If there were any validation errors, an `entry` variable will be passed to the + template, which contains the posted values and validation errors. If that’s not + set, we’ll default to a new entry. #} +{% set entry = entry ?? create('craft\\elements\\Entry') %} + - {{ csrfInput() }} - {{ actionInput('entries/save-entry') }} - {{ redirectInput('viewentry/{slug}') }} - {{ hiddenInput('sectionId', '2') }} - {{ hiddenInput('enabled', '1') }} - - - - - {% if entry is defined %} - {{ _self.errorList(entry.getErrors('title')) }} - {% endif %} - - - - - {% if entry is defined %} - {{ _self.errorList(entry.getErrors('body')) }} - {% endif %} - - + {{ csrfInput() }} + {{ actionInput('entries/save-entry') }} + {{ redirectInput('viewentry/{slug}') }} + {{ hiddenInput('sectionId', '2') }} + {{ hiddenInput('enabled', '1') }} + + + {{ input('text', 'title', entry.title, { + id: 'title', + class: entry.hasErrors('title') ? 'error', + }) }} + {{ _self.errorList(entry.getErrors('title')) }} + + + {{ tag('textarea', entry.body, { + id: 'body', + name: 'body', + class: entry.hasErrors('body') ? 'error', + }) }} + {{ _self.errorList(entry.getErrors('body')) }} + + - ``` -Be sure and adjust the “sectionId” to the actual ID of the section want to save the entry to. +Be sure to change the `sectionId` value to the actual ID of the section want to save the entry to. The user submitting the entry will also need to have the permission necessary to create entries for the section they are posting to. -### Editing Entry Form +::: tip +You can accept anonymous entry submissions using the [Guest Entries](https://plugins.craftcms.com/guest-entries) plugin. +::: + +### Editing Existing Entries -You can modify the form to save existing entries by adding an “entryId” hidden input to the form: +You can modify the form to save existing entries by adding an `entryId` hidden input to the form: ```twig {{ hiddenInput('entryId', entry.id) }} diff --git a/fr/dev/examples/user-profile-form.md b/fr/dev/examples/user-profile-form.md index a57f7c41b07..e78ddc0635b 100644 --- a/fr/dev/examples/user-profile-form.md +++ b/fr/dev/examples/user-profile-form.md @@ -1,473 +1,114 @@ # User Profile Form -You can create a front-end form to let users edit their profiles without granting them access to the Control Panel. To do this, you can point your form to the same controller that the Control Panel uses for its profile form. (Jump down to [Form Action](#form-action) for more about forms and controllers.) - -We’ll provide two examples: The simplest possible profile form and a full-featured profile form. - -## Simple Profile - -The following fields don't require any validation. - -- first name -- last name -- photo - -If those are all you need, then the form can be quite simple. - -```twig -{% requireLogin %} - -
- {{ actionInput('users/save-user') }} - - {{ csrfInput() }} - - {{ hiddenInput('userId', currentUser.id) }} - -
- - -
- -
- - -
- -
- - - {% if currentUser.photo %} -
- -
- {% endif %} -
- -
- {# This file field takes precedence over the ”Delete photo” checkbox #} - - -
- -
- {# If a file has been selected, this has no effect #} - -
- -
- - Reset -
-
-``` - -The [Breaking it down](#breaking-it-down) section will cover these fields as they appear in the advanced profile example below. - -## Advanced Profile - -This example adds everything including: - -- first name -- last name -- photo -- username -- email -- password -- a custom field -- validation - -See the [Breakdown](#breakdown) section for details. See the [Extras](#extras) section for some example styles for this form. - -Keep in mind that there is a custom Bio field included in this example, so if you don’t have a Bio field, then delete that section after you copy and paste into your template. +You can create a form that allows users to edit their profile using the following code as a starting point: ```twig +{# Require that a user is logged in to view this form. #} {% requireLogin %} -
- - {% set notice = craft.app.session.getFlash('notice') %} - {% if notice %} -

{{ notice }}

+{% macro errorList(errors) %} + {% if errors %} +
    + {% for error in errors %} +
  • {{ error }}
  • + {% endfor %} +
{% endif %} +{% endmacro %} - {% set formUser = user is defined ? user : currentUser %} - - {% if formUser.hasErrors() %} -
-

Unable to save user. Please check for errors.

+{# If there were any validation errors, a `user` variable will be passed to the + template, which contains the posted values and validation errors. If that’s not + set, we’ll default to the current user. #} +{% set user = user ?? currentUser %} -
    - {% for error in formUser.getFirstErrors() %} -
  • {{ error }}
  • - {% endfor %} -
-
- {% endif %} +{% if user.hasErrors() %} +

Unable to save your profile.

+{% endif %} + {{ csrfInput() }} - - {# {{ redirectInput('users/'~currentUser.username) }} #} - {{ actionInput('users/save-user') }} + {{ hiddenInput('userId', user.id) }} + {{ redirectInput("users/#{currentUser.username}") }} - {{ hiddenInput('userId', formUser.id) }} - -
- - -
+ + {{ input('text', 'firstName', user.firstName, { + id: 'first-name', + class: user.hasErrors('firstName') ? 'error', + }) }} + {{ _self.errorList(user.getErrors('firstName')) }} -
- - -
+ + {{ input('text', 'lastName', user.firstName, { + id: 'last-name', + class: user.hasErrors('lastName') ? 'error', + }) }} + {{ _self.errorList(user.getErrors('lastName')) }} - {% if formUser.photo %} -
+ {% if user.photo %} - -
+ {{ user.photo.getImg({width: 150, height: 150})|attr({ + id: 'user-photo', + alt: user.friendlyName, + }) }} -
-

If a new photo is selected, this checkbox has no effect.

-
{% endif %} -
- - -
+ + {{ input('file', 'photo', null, { + id: 'photo', + accept: 'image/png,image/jpeg', + }) }} {% if not craft.app.config.general.useEmailAsUsername %} - {% set error = formUser.getFirstError('username') %} - {% set class = error ? 'has-error' : '' %} -
- -

If left blank, this will become the email address.

- -

{{ error }}

- -
+ + {{ input('text', 'username', user.username, { + id: 'username', + class: user.hasErrors('username') ? 'error', + }) }} + {{ _self.errorList(user.getErrors('username')) }} {% endif %} - {% set error = formUser.getFirstError('email') %} - {% set class = error ? 'has-error' : '' %} -
- - - {% if craft.app.projectConfig.get('users.requireEmailVerification') %} -

New email addresses need to be verified.

- {% endif %} - -

{{ error }}

- -
- - {% set error = formUser.getFirstError('newPassword') %} - {% set class = error ? 'has-error' : '' %} -
- -

{{ error }}

- -
- - {% set error = formUser.getFirstError('currentPassword') %} - {% set class = error ? 'has-error' : '' %} -
- -

Required to change Password and Email

-

{{ error }}

- -
- - {# Custom field example. Delete if you don't have a `bio` field. #} - {% set error = formUser.getFirstError('bio') %} - {% set class = error ? 'has-error' : '' %} -
- -

{{ error }}

- -
- -
- - Reset -
-
-``` - -### Breaking it down - -We’ll walk through the advanced form example step by step. - -#### Require Login -```twig -{% requireLogin %} -``` - -Make sure the user is logged in or else the template will throw errors doing anything with `currentUser`. Be sure to read the documentation for [{% requireLogin %} Tags](https://docs.craftcms.com/v3/dev/tags/requirelogin.html) to avoid unexpected `404 Not Found` errors. - -#### Form Action - -```twig -
- {{ actionInput('users/save-user') }} -``` - -The `` tag does not have an `action=""` parameter on purpose. The hidden `name="action"` input tells Craft which controller and controller method to use. - -:::tip -The Control Panel profile form uses Craft’s [UserController::actionSaveUser()](api:craft\controllers\UsersController#method-actionsaveuser) controller and you’re free to use it on the front end too if it suits your needs. Otherwise, you can use it as inspiration to build your own controller in a custom module or plugin. -::: - -#### Notice - -```twig -{% set notice = craft.app.session.getFlash('notice') %} -{% if notice %} -

{{ notice }}

-{% endif %} -``` - -Upon success, this notice will display the message, “User saved.” That is, of course, unless you’ve set a redirect input. (Jump to [Optional Redirect](#optional-redirect) to see how.) - -#### User Variable - -```twig -{% set formUser = user is defined ? user : currentUser %} -``` - -When the form first loads, we use the `currentUser` variable. If there were validation errors, there will be a `user` variable with the previously-submitted values. - -#### CSRF - -```twig -{{ csrfInput() }} -``` - -The `csrfInput()` generator function is required in all forms for Craft’s [cross-site request forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection unless you disabled it in the setting. - -#### Optional Redirect - -```twig -{# {{ redirectInput('users/'~currentUser.username) }} #} -``` - -That line is commented out, but demonstrates that upon a successful save, you can redirect to another page; perhaps a user’s home page based on their username. - -```twig -{{ hiddenInput('userId', formUser.id) }} -``` - -The user id is required to update the correct user. You’ll want to make sure group permissions are set not to allow users to edit other users’ profiles. - -#### Name Fields - -```twig -
- - -
- -
- - -
-``` - -These fields don’t need any validation, so they’re pretty straightforward. - -#### User Photo - -```twig -{% if formUser.photo %} -
- - -
- -
- -

If a new photo is selected, this checkbox has no effect.

-
-{% endif %} - -
- - -
-``` - -If a user photo exists, we’ll show it and include a checkbox for the option to delete it. No matter what, we’ll show a file field so they can choose a new photo. If this section feels unrefined, then some JavaScript enhancements might help. That’s up to you. - -#### Username - -```twig -{% if not craft.app.config.general.useEmailAsUsername %} - {% set error = formUser.getFirstError('username') %} - {% set class = error ? 'has-error' : '' %} -
- -

If left blank, this will become the email address.

- -

{{ error }}

- -
-{% endif %} -``` - -If you’ve set the config setting to `true`, then we won’t show the Username field. - -Here is where validation comes into play. Setting an `error` variable to `getFirstError('username')` tells us whether or not there is an error for this field. (It will be `null` if not.) If there is an error, then we’ll set the appropriate class names on HTML elements to reveal them and show the error message. - -You’ll find styles in the [Extras](#extras) section to show and hide HTML elements based on class names. Of course, you can handle that however you like. - -#### Email - -```twig -{% set error = formUser.getFirstError('email') %} -{% set class = error ? 'has-error' : '' %} -
- + + {{ input('text', 'email', user.unverifiedEmail ?? user.email, { + id: 'email', + class: user.hasErrors('email') ? 'error', + }) }} + {{ _self.errorList(user.getErrors('username')) }} {% if craft.app.projectConfig.get('users.requireEmailVerification') %} -

New email addresses need to be verified.

+

New email addresses need to be verified.

{% endif %} -

{{ error }}

- -
-``` - -That is like the Username field except for showing a message that the user should expect to verify a new email address if you’ve ticked the checkbox for “Verify email addresses?” in the Control Panel under Settings → Users → Settings. The [Current Password](#current-password) field will be required to change an email address. - -#### Password - -```twig -{% set error = formUser.getFirstError('newPassword') %} -{% set class = error ? 'has-error' : '' %} -
- -

{{ error }}

- -
-``` - -The user can change their password, but they’ll need to enter their [Current Password](#current-password) too. There will be an error if the given password is too short. - -#### Current Password - -```twig -{% set error = formUser.getFirstError('currentPassword') %} -{% set class = error ? 'has-error' : '' %} -
- -

Required to change Password and Email

-

{{ error }}

- -
-``` - -This field is required when the email address or password has changed. Otherwise, the user can leave it blank. You could use some fancy JavaScript to hide or show this based on the state of the other fields. - -#### Custom Field: Bio - -```twig -{% set error = formUser.getFirstError('bio') %} -{% set class = error ? 'has-error' : '' %} -
- -

{{ error }}

- -
-``` - -Let’s say you added a custom field named “Bio” with a handle of `bio` to the user profile field layout under Settings → Users → Fields. Let’s also say it’s a required field. The difference here is that custom fields belong in a `fields` array with names like `field[]`. - -:::tip -Handling complex custom fields, like Matrix or third-party plugin fields, can seem complicated. You might want to view the source code of a user profile form in the Control Panel to see how to handle those types of fields. -::: - -#### Form Submission + + {{ input('password', 'newPassword', null, { + id: 'new-password', + class: user.hasErrors('newPassword') ? 'error', + }) }} + {{ _self.errorList(user.getErrors('newPassword')) }} + + + {{ input('password', 'password', null, { + id: 'current-password', + class: user.hasErrors('currentPassword') ? 'error' + }) }} + {{ _self.errorList(user.getErrors('currentPassword')) }} + + {# Custom “Bio” field #} + + {{ tag('textarea', user.bio, { + id: 'bio', + name: 'fields[bio]', + class: user.hasErrors('bio') ? 'error', + }) }} + {{ _self.errorList(user.getErrors('bio')) }} -```twig -
- Reset -
-``` - -A link to reload the current page is a good way to reset the form because it will use `currentUser` variable, and validation errors on will be forgotten. - -## Extras - -Here are some styles to make the forms on this page more readable in your browser. - -```html - + ``` diff --git a/fr/dev/filters.md b/fr/dev/filters.md index f277901c4de..be61eeaec09 100644 --- a/fr/dev/filters.md +++ b/fr/dev/filters.md @@ -1,12 +1,88 @@ # Filters -The following filters are available to Twig templates in Craft: - -## `abs` - -Returns an absolute value. - -This works identically to Twig’s core [`abs`](https://twig.symfony.com/doc/2.x/filters/abs.html) filter. +The following [filters](https://twig.symfony.com/doc/2.x/templates.html#filters) are available to Twig templates in Craft: + +| Filter | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| [abs](https://twig.symfony.com/doc/2.x/filters/abs.html) | Returns the absolute value of a number. | +| [append](#append) | Appends HTML to the end of another element. | +| [ascii](#ascii) | Converts a string to ASCII characters. | +| [atom](#atom) | Converts a date to an ISO-8601 timestamp. | +| [attr](#attr) | Modifies an HTML tag’s attributes. | +| [batch](https://twig.symfony.com/doc/2.x/filters/batch.html) | Batches items in an array. | +| [camel](#camel) | Formats a string into camelCase. | +| [capitalize](https://twig.symfony.com/doc/2.x/filters/capitalize.html) | Capitalizes the first character of a string. | +| [column](#column) | Returns the values from a single property or key in an array. | +| [contains](#contains) | Returns whether an array contains a nested item with a given key/value pair. | +| [convert_encoding](https://twig.symfony.com/doc/2.x/filters/convert_encoding.html) | Converts a string from one encoding to another. | +| [currency](#currency) | Formats a number as currency. | +| [date](#date) | Formats a date. | +| [date_modify](https://twig.symfony.com/doc/2.x/filters/date_modify.html) | Modifies a date. | +| [datetime](#datetime) | Formats a date with its time. | +| [default](https://twig.symfony.com/doc/2.x/filters/default.html) | Returns the value or a default value if empty. | +| [duration](#duration) | Returns a `DateInterval` object. | +| [encenc](#encenc) | Encrypts and base64-encodes a string. | +| [escape](https://twig.symfony.com/doc/2.x/filters/escape.html) | Escapes a string. | +| [filesize](#filesize) | Formats a number of bytes into something else. | +| [filterByValue](#filterbyvalue) | Filters an array by key/value pairs. | +| [filter](#filter) | Filters the items in an array. | +| [first](https://twig.symfony.com/doc/2.x/filters/first.html) | Returns the first character/item of a string/array. | +| [format](https://twig.symfony.com/doc/2.x/filters/format.html) | Formats a string by replacing placeholders. | +| [group](#group) | Groups items in an array. | +| [hash](#hash) | Prefixes a string with a keyed-hash message authentication code (HMAC). | +| [id](#id) | Normalizes an element ID into only alphanumeric characters, underscores, and dashes. | +| [indexOf](#indexof) | Returns the index of a given value within an array, or the position of a passed-in string within another string. | +| [index](#index) | Indexes the items in an array. | +| [intersect](#intersect) | Returns the intersecting items of two arrays. | +| [join](https://twig.symfony.com/doc/2.x/filters/join.html) | Concatenates multiple strings into one. | +| [json_decode](#json_decode) | JSON-decodes a value. | +| [json_encode](#json_encode) | JSON-encodes a value. | +| [kebab](#kebab) | Formats a string into “kebab-case”. | +| [keys](https://twig.symfony.com/doc/2.x/filters/keys.html) | Returns the keys of an array. | +| [last](https://twig.symfony.com/doc/2.x/filters/last.html) | Returns the last character/item of a string/array. | +| [lcfirst](#lcfirst) | Lowercases the first character of a string. | +| [length](https://twig.symfony.com/doc/2.x/filters/length.html) | Returns the length of a string or array. | +| [literal](#literal) | Escapes an untrusted string for use with element query params. | +| [lower](https://twig.symfony.com/doc/2.x/filters/lower.html) | Lowercases a string. | +| [map](https://twig.symfony.com/doc/2.x/filters/map.html) | Applies an arrow function to the items in an array. | +| [markdown](#markdown-or-md) | Processes a string as Markdown. | +| [merge](https://twig.symfony.com/doc/2.x/filters/merge.html) | Merges an array with another array | +| [multisort](#multisort) | Sorts an array by one or more keys within its sub-arrays. | +| [namespace](#namespace) | Namespaces input names and other HTML attributes. | +| [namespaceInputId](#namespaceinputid) | Namespaces an element ID. | +| [namespaceInputName](#namespaceinputname) | Namespaces an input name. | +| [nl2br](https://twig.symfony.com/doc/2.x/filters/nl2br.html) | Replaces newlines with `
` tags. | +| [number](#number) | Formats a number. | +| [number_format](https://twig.symfony.com/doc/2.x/filters/number_format.html) | Formats numbers. | +| [parseRefs](#parserefs) | Parses a string for reference tags. | +| [pascal](#pascal) | Formats a string into “PascalCase”. | +| [percentage](#percentage) | Formats a percentage. | +| [prepend](#prepend) | Prepends HTML to the beginning of another element. | +| [purify](#purify) | Runs HTML code through HTML Purifier. | +| [raw](https://twig.symfony.com/doc/2.x/filters/raw.html) | Marks as value as safe for the current escaping strategy. | +| [reduce](https://twig.symfony.com/doc/2.x/filters/reduce.html) | Iteratively reduces a sequence or mapping to a single value. | +| [replace](#replace) | Replaces parts of a string with other things. | +| [reverse](https://twig.symfony.com/doc/2.x/filters/reverse.html) | Reverses a string or array. | +| [round](https://twig.symfony.com/doc/2.x/filters/round.html) | Rounds a number. | +| [rss](#rss) | Converts a date to RSS date format. | +| [slice](https://twig.symfony.com/doc/2.x/filters/slice.html) | Extracts a slice of a string or array. | +| [snake](#snake) | Formats a string into “snake_case”. | +| [sort](https://twig.symfony.com/doc/2.x/filters/sort.html) | Sorts an array. | +| [spaceless](https://twig.symfony.com/doc/2.x/filters/spaceless.html) | Removes whitespace between HTML tags. | +| [split](https://twig.symfony.com/doc/2.x/filters/split.html) | Splits a string by a delimiter. | +| [striptags](https://twig.symfony.com/doc/2.x/filters/striptags.html) | Strips SGML/XML tags from a string. | +| [time](#time) | Formats a time. | +| [timestamp](#timestamp) | Formats a human-readable timestamp. | +| [title](https://twig.symfony.com/doc/2.x/filters/title.html) | Formats a string into “Title Case”. | +| [translate](#translate-or-t) | Translates a message. | +| [trim](https://twig.symfony.com/doc/2.x/filters/trim.html) | Strips whitespace from the beginning and end of a string. | +| [ucfirst](#ucfirst) | Capitalizes the first character of a string. | +| [unique](#unique) | Removes duplicate values from an array. | +| [upper](https://twig.symfony.com/doc/2.x/filters/upper.html) | Formats a string into “UPPER CASE”. | +| [url_encode](https://twig.symfony.com/doc/2.x/filters/url_encode.html) | Percent-encodes a string as a URL segment or an array as a query string. | +| [values](#values) | Returns all the values in an array, resetting its keys. | +| [withoutKey](#withoutkey) | Returns an array without the specified key. | +| [without](#without) | Returns an array without the specified element(s). | ## `append` @@ -121,12 +197,6 @@ If you want to completely replace a `class` or `style` attribute, remove it firs {# Output:
#} ``` -## `batch` - -“Batches” items by returning a list of lists with the given number of items - -This works identically to Twig’s core [`batch`](https://twig.symfony.com/doc/2.x/filters/batch.html) filter. - ## `camel` Returns a string formatted in “camelCase”. @@ -136,27 +206,36 @@ Returns a string formatted in “camelCase”. {# Output: fooBar #} ``` -## `capitalize` - -Capitalizes a value. - -This works identically to Twig’s core [`capitalize`](https://twig.symfony.com/doc/2.x/filters/capitalize.html) filter. - ## `column` -Returns the values from a single column in the input array. +Returns the values from a single property or key in the input array. ```twig {% set entryIds = entries|column('id') %} ``` +An arrow function can be passed instead, if the values that should be returned don’t exist as a property or key on the array elements. + +```twig +{% set authorNames = entries|column(e => e.author.fullName) %} +``` + This works similarly to Twig’s core [`column`](https://twig.symfony.com/doc/2.x/filters/column.html) filter, except that [ArrayHelper::getColumn()](api:yii\helpers\BaseArrayHelper::getColumn()) is used rather than PHP’s [array_column()](https://secure.php.net/array_column) function. -## `convert_encoding` +## `contains` -Converts a string from one encoding to another. +Returns whether the passed-in array contains any nested arrays/objects with a particular key/attribute set to a given value. -This works identically to Twig’s core [`convert_encoding`](https://twig.symfony.com/doc/2.x/filters/convert_encoding.html) filter. +```twig +{% set works = craft.entries() + .section('artwork') + .all() %} + +{# See if any of the artwork has a mature rating #} +{% if works|contains('rating', 'm') %} +

Some of this artwork is meant for mature viewers.

+{% endif %} +``` ## `currency` @@ -218,11 +297,9 @@ You can customize the timezone the time is output in, using the `timezone` param {# Output: 12/21/1990 #} ``` -## `date_modify` - -Modifies a date with a given modifier string. - -This works identically to Twig’s core [`date_modify`](https://twig.symfony.com/doc/2.x/filters/date_modify.html) filter. +::: tip +If the value passed to the date filter is `null`, it will return the current date by default. +::: ## `datetime` @@ -242,12 +319,12 @@ Craft provides some special format keywords that will output locale-specific dat Possible `format` values are: -| Format | Example | -| -------------------- | ---------------------------------------------- | -| `short` | 12/20/1990, 5:00 PM | -| `medium` *(default)* | Dec 20, 1990, 5:00:00 PM | -| `long` | December 20, 1990 at 5:00:00 PM PDT | -| `full` | Thursday, December 20, 19909 at 5:00:00 PM PDT | +| Format | Example | +| -------------------- | --------------------------------------------- | +| `short` | 12/20/1990, 5:00 PM | +| `medium` *(default)* | Dec 20, 1990, 5:00:00 PM | +| `long` | December 20, 1990 at 5:00:00 PM PDT | +| `full` | Thursday, December 20, 1990 at 5:00:00 PM PDT | The current application locale will be used by default. If you want to format the date and time for a different locale, use the `locale` argument: @@ -263,12 +340,6 @@ You can customize the timezone the time is output in, using the `timezone` param {# Output: 12/21/1990, 12:00 AM #} ``` -## `default` - -Returns the passed default value if the value is undefined or empty, otherwise the value of the variable. - -This works identically to Twig’s core [`default`](https://twig.symfony.com/doc/2.x/filters/default.html) filter. - ## `duration` Runs a [DateInterval](http://php.net/manual/en/class.dateinterval.php) object through @@ -285,16 +356,18 @@ Encrypts and base64-encodes a string. {{ 'secure-string'|encenc }} ``` -## `escape` - -Escapes a string using strategies that depend on the context. - -This works identically to Twig’s core [`escape`](https://twig.symfony.com/doc/2.x/filters/escape.html) filter. - ## `filesize` Formats a number of bytes into something nicer. +```twig +{{ asset.size }} +{# Output: 1944685 #} + +{{ asset.size|filesize }} +{# Output: 1.945 MB #} +``` + ## `filter` Filters elements of an array. @@ -317,27 +390,21 @@ When an arrow function is passed, this works identically to Twig’s core [`filt ## `filterByValue` -Runs an array through . +Runs an array through . -## `first` - -Returns the first element of an array or string. - -This works identically to Twig’s core [`first`](https://twig.symfony.com/doc/2.x/filters/first.html) filter. - -## `format` - -formats a given string by replacing the placeholders (placeholders follows the [sprintf()](https://secure.php.net/sprintf) notation). - -This works identically to Twig’s core [`format`](https://twig.symfony.com/doc/2.x/filters/format.html) filter. +```twig +{% set array = { 'foo': 'bar', 'bar': 'baz', 'bat': 'bar' } %} +{{ array|filterByValue(v => v == 'bar') }} +{# Result: { 'foo': 'bar', 'bat': 'bar' } #} +``` ## `group` -Groups the items of an array together based on common properties. +Groups items in an array by a the results of an arrow function. ```twig {% set allEntries = craft.entries.section('blog').all() %} -{% set allEntriesByYear = allEntries|group('postDate|date("Y")') %} +{% set allEntriesByYear = allEntries|group(e => e.postDate|date('Y')) %} {% for year, entriesInYear in allEntriesByYear %}

{{ year }}

@@ -428,12 +495,6 @@ Returns an array containing only the values that are also in a passed-in array. %} ``` -## `join` - -Returns a string which is the concatenation of the elements in an array. - -This works identically to Twig’s core [`join`](https://twig.symfony.com/doc/2.x/filters/join.html) filter. - ## `json_encode` Returns the JSON representation of a value. @@ -442,7 +503,7 @@ This works similarly to Twig’s core [`json_encode`](https://twig.symfony.com/d ## `json_decode` -JSON-decodes a string into an array by passing it through . +JSON-decodes a string into an array by passing it through . ```twig {% set arr = '[1, 2, 3]'|json_decode %} @@ -452,50 +513,32 @@ JSON-decodes a string into an array by passing it through - -## `lower` - -Converts a value to lowercase. - -This works identically to Twig’s core [`lower`](https://twig.symfony.com/doc/2.x/filters/lower.html) filter. +Runs a string through . -## `map` - -Applies an arrow function to the elements of an array. - -This works identically to Twig’s core [`map`](https://twig.symfony.com/doc/2.x/filters/map.html) filter. +```twig +{{ 'SELECT id, * FROM table'|literal }} +{# Output: SELECT id\, \* FROM table #} +``` ## `markdown` or `md` @@ -518,21 +561,111 @@ This filter supports two arguments: - `flavor` can be `'original'` (default value), `'gfm'`(GitHub-Flavored Markdown), `'gfm-comment'` (GFM with newlines converted to `
`s), or `'extra'` (Markdown Extra) - `inlineOnly` determines whether to only parse inline elements, omitting any `

` tags (defaults to `false`) -## `merge` +## `multisort` + +Sorts an array by one or more properties or keys within an array’s values. -Merges an array with another array. +To sort by a single property or key, pass its name as a string: -This works identically to Twig’s core [`merge`](https://twig.symfony.com/doc/2.x/filters/merge.html) filter. +```twig +{% set entries = entries|multisort('title') %} +``` -## `multisort` +To sort by multiple properties or keys, pass them in as an array. For example, this will sort entries by their post date first, and then by their title: + +```twig +{% set entries = entries|multisort(['postDate', 'title']) %} +``` + +An arrow function can be passed instead, if the values that should be sorted by don’t exist as a property or key on the array elements. + +```twig +{% set entries = entries|multisort(e => e.author.fullName) %} +``` + +The values will be sorted in ascending order by default. You can switch to descending order with the `direction` param: + +```twig +{% set entries = entries|multisort('title', direction=SORT_DESC) %} +``` -Sorts an array with [ArrayHelper::multisort()](api:yii\helpers\BaseArrayHelper::multisort()). +You can also customize which sorting behavior is used, with the `sortFlag` param. For example, to sort items numerically, use `SORT_NUMERIC`: -## `nl2br` +```twig +{% set entries = entries|multisort('id', sortFlag=SORT_NUMERIC) %} +``` + +See PHP’s [sort()](https://www.php.net/manual/en/function.sort.php) documentation for the available sort flags. -Inserts HTML line breaks before all newlines in a string. +When sorting by multiple properties or keys, you must set the `direction` and `sortFlag` params to arrays as well. -This works identically to Twig’s core [`nl2br`](https://twig.symfony.com/doc/2.x/filters/nl2br.html) filter. +```twig +{% set entries = entries|multisort([ + 'postDate', + 'title', +], sortFlag=[SORT_NATURAL, SORT_FLAG_CASE]) %} +``` + +## `namespace` + +The `|namespace` filter can be used to namespace input names and other HTML attributes. + +For example, this: + +```twig +{% set html %} + +{% endset %} +{{ html|namespace('foo') }} +``` + +would become this: + +```html + +``` + +Notice how the `id` attribute changed from `title` to `foo-title`, and the `name` attribute changed from `title` to `foo[title]`. + +## `namespaceInputId` + +Namepaces an element ID. + +For example, this: + +```twig +{{ 'bar'|namespaceInputId('foo') }} +``` + +would output: + +```html +foo-bar +``` + +::: tip +If this is used within a [namespace](tags.md#namespace) tag, the namespace applied by the tag will be used by default. +::: + +## `namespaceInputName` + +Namepaces an input name. + +For example, this: + +```twig +{{ 'bar'|namespaceInputName('foo') }} +``` + +would output: + +```html +foo[bar] +``` + +::: tip +If this is used within a [namespace](tags.md#namespace) tag, the namespace applied by the tag will be used by default. +::: ## `number` @@ -548,12 +681,6 @@ You can optionally pass `false` to it if you want group symbols to be omitted (e {# Output: 1000000 #} ``` -## `number_format` - -Formats numbers. It is a wrapper around PHP’s [number_format()](https://secure.php.net/number_format) function: - -This works identically to Twig’s core [`number_format`](https://twig.symfony.com/doc/2.x/filters/number_format.html) filter. - ## `parseRefs` Parses a string for [reference tags](../reference-tags.md). @@ -602,17 +729,21 @@ If you want to replace an existing element of the same type, pass `'replace'` as {# Output:

Lorem

#} ``` -## `raw` +## `purify` -Marks a value as being “safe”, which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it. +Runs the given text through HTML Purifier. -This works identically to Twig’s core [`raw`](https://twig.symfony.com/doc/2.x/filters/raw.html) filter. +```twig +{{ user.bio|purify }} +``` -## `reduce` +You can specify a custom HTML Purifier config file as well: -Iteratively reduces a sequence or a mapping to a single value using an arrow function, so as to reduce it to a single value. The arrow function receives the return value of the previous iteration and the current value of the sequence or mapping. +```twig +{{ user.bio|purify('user_bio') }} +``` -This works identically to Twig’s core [`reduce`](https://twig.symfony.com/doc/2.x/filters/reduce.html) filter. +That will configure HTML Purifier based on the settings defined by `config/htmlpurifier/user_bio.json`. ## `replace` @@ -643,18 +774,6 @@ You can also use a regular expression to search for matches by starting and endi {{ tag.title|lower|replace('/[^\\w]+/', '-') }} ``` -## `reverse` - -Reverses an array or string. - -This works identically to Twig’s core [`reverse`](https://twig.symfony.com/doc/2.x/filters/reverse.html) filter. - -## `round` - -Rounds a number to a given precision. - -This works identically to Twig’s core [`round`](https://twig.symfony.com/doc/2.x/filters/round.html) filter. - ## `rss` Outputs a date in the format required for RSS feeds (`D, d M Y H:i:s O`). @@ -663,12 +782,6 @@ Outputs a date in the format required for RSS feeds (`D, d M Y H:i:s O`). {{ entry.postDate|rss }} ``` -## `slice` - -Extracts a slice of an array or string. - -This works identically to Twig’s core [`slice`](https://twig.symfony.com/doc/2.x/filters/slice.html) filter. - ## `snake` Returns a string formatted in “snake_case”. @@ -678,30 +791,6 @@ Returns a string formatted in “snake_case”. {# Output: foo_bar #} ``` -## `sort` - -Sorts an array. - -This works identically to Twig’s core [`sort`](https://twig.symfony.com/doc/2.x/filters/sort.html) filter. - -## `spaceless` - -Removes whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text. - -This works identically to Twig’s core [`spaceless`](https://twig.symfony.com/doc/2.x/filters/spaceless.html) filter. - -## `split` - -Splits a string by the given delimiter and returns a list of string. - -This works identically to Twig’s core [`split`](https://twig.symfony.com/doc/2.x/filters/split.html) filter. - -## `striptags` - -Strips SGML/XML tags and replace adjacent whitespace by one space. - -This works identically to Twig’s core [`striptags`](https://twig.symfony.com/doc/2.x/filters/striptags.html) filter. - ## `time` Outputs the time of day for a timestamp or [DateTime](http://php.net/manual/en/class.datetime.php) object. @@ -723,7 +812,7 @@ Possible `format` values are: | Format | Example | | -------------------- | -------------- | | `short` | 5:00 PM | -| `medium` *(default)* | 5:00:00 PM | +| `medium` _(default)_ | 5:00:00 PM | | `long` | 5:00:00 PM PDT | The current application locale will be used by default. If you want to format the date and time for a different locale, use the `locale` argument: @@ -744,17 +833,10 @@ You can customize the timezone the time is output in, using the `timezone` param Formats a date as a human-readable timestamp, via . -## `title` - -Returns a titlecased version of the value. Words will start with uppercase letters, all remaining characters are lowercase. - -This works identically to Twig’s core [`title`](https://twig.symfony.com/doc/2.x/filters/title.html) filter. - -## `trim` - -Strips whitespace (or other characters) from the beginning and end of a string - -This works identically to Twig’s core [`trim`](https://twig.symfony.com/doc/2.x/filters/trim.html) filter. +```twig +{{ now|timestamp }} +{# Output: 9:00:00 AM #} +``` ## `translate` or `t` @@ -778,25 +860,20 @@ See [Static Message Translations](../static-translations.md) for a full explanat Capitalizes the first character of a string. -## `ucwords` - -Capitalizes the first character of each word in a string. +```twig +{{ 'foobar'|ucfirst }} +{# Output: Foobar #} +``` ## `unique` Runs an array through [array_unique()](http://php.net/manual/en/function.array-unique.php). -## `upper` - -Converts a value to uppercase. - -This works identically to Twig’s core [`upper`](https://twig.symfony.com/doc/2.x/filters/upper.html) filter. - -## `url_encode` - -Percent-encodes a given string as URL segment or an array as query string. - -This works identically to Twig’s core [`url_encode`](https://twig.symfony.com/doc/2.x/filters/url_encode.html) filter. +```twig +{% set array = ['Larry', 'Darryl', 'Darryl'] %} +{{ array|unique }} +{# Result: ['Larry', 'Darryl'] #} +``` ## `values` diff --git a/fr/dev/functions.md b/fr/dev/functions.md index 675bd7ae702..dc85e61da29 100644 --- a/fr/dev/functions.md +++ b/fr/dev/functions.md @@ -1,6 +1,52 @@ # Functions -The following functions are available to Twig templates in Craft: +The following [functions](https://twig.symfony.com/doc/2.x/templates.html#functions) are available to Twig templates in Craft: + +| Function | Description | +| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| [actionInput](#actioninput) | Outputs a hidden `action` input. | +| [actionUrl](#actionurl) | Generates a controller action URL. | +| [alias](#alias) | Parses a string as an alias. | +| [attr](#attr) | Generates HTML attributes. | +| [attribute](https://twig.symfony.com/doc/2.x/functions/attribute.html) | Accesses a dynamic attribute of a variable. | +| [beginBody](#beginbody) | Outputs scripts and styles that were registered for the “begin body” position. | +| [block](https://twig.symfony.com/doc/2.x/functions/block.html) | Prints a block’s output. | +| [ceil](#ceil) | Rounds a number up. | +| [className](#classname) | Returns the fully qualified class name of a given object. | +| [clone](#clone) | Clones an object. | +| [combine](#combine) | Combines two arrays into one. | +| [constant](https://twig.symfony.com/doc/2.x/functions/constant.html) | Returns the constant value for a given string. | +| [create](#create) | Creates a new object. | +| [csrfInput](#csrfinput) | Returns a hidden CSRF token input. | +| [cpUrl](#cpurl) | Generates a control panel URL. | +| [cycle](https://twig.symfony.com/doc/2.x/functions/cycle.html) | Cycles on an array of values. | +| [date](https://twig.symfony.com/doc/2.x/functions/date.html) | Creates a date. | +| [dump](https://twig.symfony.com/doc/2.x/functions/dump.html) | Dumps information about a variable. | +| [endBody](#endbody) | Outputs scripts and styles that were registered for the “end body” position. | +| [expression](#expression) | Creates a database expression object. | +| [floor](#floor) | Rounds a number down. | +| [getenv](#getenv) | Returns the value of an environment variable. | +| [gql](#gql) | Executes a GraphQL query against the full schema. | +| [parseEnv](#parseenv) | Parses a string as an environment variable or alias. | +| [head](#head) | Outputs scripts and styles that were registered for the “head” position. | +| [hiddenInput](#hiddeninput) | Outputs a hidden input. | +| [include](https://twig.symfony.com/doc/2.x/functions/include.html) | Returns the rendered content of a template. | +| [input](#input) | Outputs an HTML input. | +| [max](https://twig.symfony.com/doc/2.x/functions/max.html) | Returns the biggest value in an array. | +| [min](https://twig.symfony.com/doc/2.x/functions/min.html) | Returns the lowest value in an array. | +| [parent](https://twig.symfony.com/doc/2.x/functions/parent.html) | Returns the parent block’s output. | +| [plugin](#plugin) | Returns a plugin instance by its handle. | +| [random](https://twig.symfony.com/doc/2.x/functions/random.html) | Returns a random value. | +| [range](https://twig.symfony.com/doc/2.x/functions/range.html) | Returns a list containing an arithmetic progression of integers. | +| [redirectInput](#redirectinput) | Outputs a hidden `redirect` input. | +| [seq](#seq) | Outputs the next or current number in a sequence. | +| [shuffle](#shuffle) | Randomizes the order of the items in an array. | +| [siteUrl](#siteurl) | Generates a front-end URL. | +| [svg](#svg) | Outputs an SVG document. | +| [source](https://twig.symfony.com/doc/2.x/functions/source.html) | Returns the content of a template without rendering it. | +| [tag](#tag) | Outputs an HTML tag. | +| [template_from_string](https://twig.symfony.com/doc/2.x/functions/template_from_string.html) | Loads a template from a string. | +| [url](#url) | Generates a URL. | ## `actionInput` @@ -18,6 +64,18 @@ You can optionally set additional attributes on the tag by passing an `options` }) }} ``` +## `actionUrl` + +Returns a controller action URL, automatically accounting for relative vs. absolute format and the active setting. + +### Arguments + +The `actionUrl()` function has the following arguments: + +* **`path`** – The path that the resulting URL should point to on your site. It will be appended to your base site URL. +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). +* **`scheme`** – Which scheme the URL should use (`'http'` or `'https'`). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, then `https` will be used. + ## `alias` Passes a string through [Craft::getAlias()](api:yii\BaseYii::getAlias()), which will check if the string begins with an [alias](https://www.yiiframework.com/doc/guide/2.0/en/concept-aliases). (See [Configuration](../config/README.md#aliases) for more info.) @@ -28,7 +86,7 @@ Passes a string through [Craft::getAlias()](api:yii\BaseYii::getAlias()), which ## `attr` -Generates a list of HTML attributes based on the given object, using . +Generates a list of HTML attributes based on the given [hash](twig-primer.md#hashes), using . ```twig {% set myAttributes = { @@ -50,12 +108,6 @@ Generates a list of HTML attributes based on the given object, using
``` -## `attribute` - -Accesses a dynamic attribute of a variable. - -This works identically to Twig’s core [`attribute`](https://twig.symfony.com/doc/2.x/functions/attribute.html) function. - ## `beginBody` Outputs any scripts and styles that were registered for the “begin body” position. It should be placed right after your `` tag. @@ -102,6 +154,17 @@ Clones a given object. {% set articles = clone(query).type('articles') %} ``` +## `combine` + +Combines two arrays into one, using the first array to define the keys, and the second array to define the values. + +```twig +{% set arr1 = ['a', 'b', 'c'] %} +{% set arr2 = ['foo', 'bar', 'baz'] %} +{% set arr3 = combine(arr1, arr2) %} +{# arr3 will now be `{a: 'foo', b: 'bar', c: 'baz'}` #} +``` + ## `constant` Returns the constant value for a given string. @@ -116,7 +179,7 @@ Creates a new object instance based on a given class name or object configuratio {# Pass in a class name #} {% set cookie = create('yii\\web\\Cookie') %} -{# Or a full object configuration array #} +{# Or a full object configuration hash #} {% set cookie = create({ class: 'yii\\web\\cookie', name: 'foo', @@ -124,6 +187,22 @@ Creates a new object instance based on a given class name or object configuratio }) %} ``` +## `cpUrl` + +Returns a control panel URL, automatically accounting for relative vs. absolute format and the active setting. + +```twig +Visit control panel settings +``` + +### Arguments + +The `cpUrl()` function has the following arguments: + +* **`path`** – The path that the resulting URL should point to on your site. It will be appended to your base site URL. +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). +* **`scheme`** – Which scheme the URL should use (`'http'` or `'https'`). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, then `https` will be used. + ## `csrfInput` Returns a hidden CSRF Token input. All sites that have CSRF Protection enabled must include this in each form that submits via POST. @@ -140,24 +219,6 @@ You can optionally set additional attributes on the tag by passing an `options` }) }} ``` -## `cycle` - -Cycles on an array of values. - -This works identically to Twig’s core [`cycle`](https://twig.symfony.com/doc/2.x/functions/cycle.html) function. - -## `date` - -Converts an argument to a date. - -This works identically to Twig’s core [`date`](https://twig.symfony.com/doc/2.x/functions/date.html) function. - -## `dump` - -Dumps information about a template variable. - -This works identically to Twig’s core [`dump`](https://twig.symfony.com/doc/2.x/functions/dump.html) function. - ## `endBody` Outputs any scripts and styles that were registered for the “end body” position. It should be placed right before your `` tag. @@ -198,6 +259,38 @@ Returns the value of an environment variable. {{ getenv('MAPS_API_KEY') }} ``` +## `gql` + +Executes a GraphQL query against the full schema. + +```twig +{% set result = gql('{ + entries (section: "news", limit: 2, orderBy: "dateCreated DESC") { + postDate @formatDateTime (format: "Y-m-d") + title + url + ... on news_article_Entry { + shortDescription + featuredImage { + url @transform (width: 300, immediately: true) + altText + } + } + } +}') %} + +{% for entry in result.data %} +

{{ entry.title }}

+

{{ entry.postDate }}

+ + {% set image = entry.featuredImage[0] %} + {{ image.altText }} + + {{ entry.shortDescription|markdown }} +

Continue reading…

+{% endfor %} +``` + ## `parseEnv` Checks if a string references an environment variable (`$VARIABLE_NAME`) and/or an alias (`@aliasName`), and returns the referenced value. @@ -265,12 +358,6 @@ Returns the lowest value in an array. This works identically to Twig’s core [`min`](https://twig.symfony.com/doc/2.x/functions/min.html) function. -## `parent` - -Returns the parent block’s output. - -This works identically to Twig’s core [`parent`](https://twig.symfony.com/doc/2.x/functions/parent.html) function. - ## `plugin` Returns a plugin instance by its handle, or `null` if no plugin is installed and enabled with that handle. @@ -279,18 +366,6 @@ Returns a plugin instance by its handle, or `null` if no plugin is installed and {{ plugin('commerce').version }} ``` -## `random` - -Returns a random value. - -This works identically to Twig’s core [`random`](https://twig.symfony.com/doc/2.x/functions/random.html) function. - -## `range` - -Returns a list containing an arithmetic progression of integers. - -This works identically to Twig’s core [`range`](https://twig.symfony.com/doc/2.x/functions/range.html) function. - ## `redirectInput` Shortcut for typing ``. @@ -336,9 +411,10 @@ To view the current number in the sequence without incrementing it, set the `nex Randomizes the order of the elements within an array. ```twig -{% set promos = shuffle(homepage.promos) %} +{% set promos = craft.entries.section('promos').all() %} +{% set shuffledPromos = shuffle(promos) %} -{% for promo in promos %} +{% for promo in shuffledPromos %}

{{ promo.title }}

{{ promo.description }}

@@ -349,7 +425,7 @@ Randomizes the order of the elements within an array. ## `siteUrl` -Similar to [url()](#url-path-params-scheme-mustshowscriptname), except *only* for creating URLs to pages on your site. +Similar to [url()](#url-path-params-scheme-mustshowscriptname), except _only_ for creating URLs to pages on your site. ```twig Contact Us @@ -360,7 +436,7 @@ Similar to [url()](#url-path-params-scheme-mustshowscriptname), except *only* fo The `siteUrl()` function has the following arguments: * **`path`** – The path that the resulting URL should point to on your site. It will be appended to your base site URL. -* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or an object (e.g. `{foo:'1', bar:'2'}`). +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). * **`scheme`** – Which scheme the URL should use (`'http'` or `'https'`). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, then `https` will be used. * **`siteId`** – The ID of the site that the URL should point to. By default the current site will be used. @@ -395,13 +471,13 @@ You can pass the following things into it: By default, if you pass an asset or raw markup into the function, the SVG will be sanitized of potentially malicious scripts using [svg-sanitizer](https://github.com/darylldoyle/svg-sanitizer), and any IDs or class names within the document will be namespaced so they don’t conflict with other IDs or class names in the DOM. You can disable those behaviors using the `sanitize` and `namespace` arguments: ```twig -{{ svg('@webroot/icons/lemon.svg') }} +{{ svg(image, sanitize=false, namespace=false) }} ``` You can also specify a custom class name that should be added to the root `` node using the `class` argument: ```twig -{{ svg(image, sanitize=false, namespace=false) }} +{{ svg('@webroot/icons/lemon.svg', class='lemon-icon') }} ``` ## `source` @@ -415,44 +491,38 @@ This works identically to Twig’s core [`source`](https://twig.symfony.com/doc/ Renders a complete HTML tag. ```twig -{{ svg('@webroot/icons/lemon.svg', class='lemon-icon') }} +{{ tag('div', { + class: 'foo' +}) }} +{# Output:
#} ``` If `text` is included in the attributes argument, its value will be HTML-encoded and set as the text contents of the tag. ```twig {{ tag('div', { - class: 'foo' + text: 'Hello' }) }} -{# Output:
#} +{# Output:
Hello
#} ``` If `html` is included in the attributes argument (and `text` isn’t), its value will be set as the inner HTML of the tag (without getting HTML-encoded). ```twig {{ tag('div', { - text: 'Hello' + html: 'Hello
world' }) }} -{# Output:
Hello
#} +{# Output:
Hello
world
#} ``` All other keys passed to the second argument will be set as attributes on the tag, using . -## `template_from_string` - -Loads a template from a string. - -This works identically to Twig’s core [`template_from_string`](https://twig.symfony.com/doc/2.x/functions/template_from_string.html) function. - ## `url` Returns a URL. ```twig -{{ tag('div', { - html: 'Hello
world' -}) }} -{# Output:
Hello
world
#} +Contact Us ``` ### Arguments @@ -460,13 +530,14 @@ Returns a URL. The `url()` function has the following arguments: * **`path`** – The path that the resulting URL should point to on your site. It will be appended to your base site URL. -* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or an object (e.g. `{foo:'1', bar:'2'}`). +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). * **`scheme`** – Which scheme the URL should use (`'http'` or `'https'`). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, then `https` will be used. * **`mustShowScriptName`** – If this is set to `true`, then the URL returned will include “index.php”, disregarding the config setting. (This can be useful if the URL will be used by POST requests over Ajax, where the URL will not be shown in the browser’s address bar, and you want to avoid a possible collision with your site’s .htaccess file redirect.) ::: tip You can use the `url()` function for appending query string parameters and/or enforcing a scheme on an absolute URL: ```twig -Contact Us +{{ url('http://my-project.com', 'foo=1', 'https') }} +{# Outputs: "https://my-project.com?foo=1" #} ``` ::: diff --git a/fr/dev/global-variables.md b/fr/dev/global-variables.md index 1c9cfb3f3ef..23c14df3d65 100644 --- a/fr/dev/global-variables.md +++ b/fr/dev/global-variables.md @@ -1,6 +1,37 @@ # Global Variables -Every single template is going to get loaded with the following variables: +The following [global variables](https://twig.symfony.com/doc/2.x/templates.html#global-variables) are available to Twig templates in Craft: + +| Variable | Description | +| --------------------------------------------- | --------------------------------------------------------------------------- | +| `_self` | The current template name. | +| `_context` | The currently-defined variables. | +| `_charset` | The current charset. | +| [craft](#craft) | A object. | +| [currentSite](#currentsite) | The requested site. | +| [currentUser](#currentuser) | The currently logged-in user. | +| [devMode](#devmode) | Whether Dev Mode is enabled. | +| [Global set variables](#global-set-variables) | Variables for each of the global sets. | +| [loginUrl](#loginurl) | The URL to the front-end Login page. | +| [logoutUrl](#logouturl) | The URL to the front-end Logout page. | +| [now](#now) | The current date/time. | +| [POS_BEGIN](#pos-begin) | The [craft\web\View::POS_BEGIN](api:craft\web\View#constants) constant. | +| [POS_END](#pos-end) | The [craft\web\View::POS_END](api:craft\web\View#constants) constant. | +| [POS_HEAD](#pos-head) | The [craft\web\View::POS_HEAD](api:craft\web\View#constants) constant. | +| [POS_LOAD](#pos-load) | The [craft\web\View::POS_LOAD](api:craft\web\View#constants) constant. | +| [POS_READY](#pos-ready) | The [craft\web\View::POS_READY](api:craft\web\View#constants) constant. | +| [siteName](#sitename) | The name of the current site. | +| [siteUrl](#siteurl) | The base URL of the current site. | +| [SORT_ASC](#sort-asc) | The `SORT_ASC` PHP constant. | +| [SORT_DESC](#sort-desc) | The `SORT_DESC` PHP constant. | +| [SORT_FLAG_CASE](#sort-flag-case) | The `SORT_FLAG_CASE` PHP constant. | +| [SORT_LOCALE_STRING](#sort-locale-string) | The `SORT_LOCALE_STRING` PHP constant. | +| [SORT_NATURAL](#sort-natural) | The `SORT_NATURAL` PHP constant. | +| [SORT_NUMERIC](#sort-numeric) | The `SORT_NUMERIC` PHP constant. | +| [SORT_REGULAR](#sort-regular) | The `SORT_REGULAR` PHP constant. | +| [SORT_STRING](#sort-string) | The `SORT_STRING` PHP constant.T | +| [systemName](#systemname) | The system name. | +| [view](#view) | The app’s `view` component. | ## `craft` diff --git a/fr/dev/headless.md b/fr/dev/headless.md index 738c4b2395b..d66545483f2 100644 --- a/fr/dev/headless.md +++ b/fr/dev/headless.md @@ -4,6 +4,8 @@ Craft’s templating system isn’t the only way to get your content out of Craf If you want to use Craft as a “headless” CMS, meaning it acts as a content API instead of (or in addition to) a regular website, there are a few ways you can go about it. +To see exactly what enabling Headless Mode does, see the [`headlessMode` config setting](../config/config-settings.md#headlessmode). + ::: tip Check out CraftQuest’s [Headless Craft CMS](https://craftquest.io/courses/headless-craft) course to learn more about using Craft as a headless CMS. ::: diff --git a/fr/dev/tags.md b/fr/dev/tags.md index 8c0f63e4258..38df2214609 100644 --- a/fr/dev/tags.md +++ b/fr/dev/tags.md @@ -1,16 +1,711 @@ # Tags -In addition to the template tags that [Twig comes with](https://twig.symfony.com/doc/tags/index.html), Craft provides a few of its own. - -- [cache](tags/cache.md) -- [css](tags/css.md) -- [exit](tags/exit.md) -- [header](tags/header.md) -- [hook](tags/hook.md) -- [js](tags/js.md) -- [nav](tags/nav.md) -- [paginate](tags/paginate.md) -- [redirect](tags/redirect.md) -- [requireLogin](tags/requirelogin.md) -- [requirePermission](tags/requirepermission.md) -- [switch](tags/switch.md) +The following [tags](https://twig.symfony.com/doc/2.x/templates.html#control-structure) are available to Twig templates in Craft: + +| Tag | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------ | +| [apply](https://twig.symfony.com/doc/2.x/tags/apply.html) | Applies Twig filters to the nested template code. | +| [autoescape](https://twig.symfony.com/doc/2.x/tags/autoescape.html) | Controls the escaping strategy for the nested template code. | +| [block](https://twig.symfony.com/doc/2.x/tags/block.html) | Defines a template block. | +| [cache](#cache) | Caches a portion of your template. | +| [css](#css) | Registers a ` + ``` diff --git a/ja/dev/filters.md b/ja/dev/filters.md index 78ea3822a13..444088a6e73 100644 --- a/ja/dev/filters.md +++ b/ja/dev/filters.md @@ -1,144 +1,387 @@ # フィルタ -[Twig に付随する](https://twig.symfony.com/doc/filters/index.html)テンプレートフィルタに加えて、Craft がいくつか独自のものを提供します。 - -## `atom` - -とりわけ Atom フィードで使用される、ISO-8601 タイムスタンプ(例:`2019-01-29T10:00:00-08:00`)に日付を変換します。 - -「camelCase」でフォーマットされた文字列を返します。 - -## `camel` - -配列に [ArrayHelper::getColumn()](api:yii\helpers\BaseArrayHelper::getColumn()) を実行し、その結果を返します。 +The following [filters](https://twig.symfony.com/doc/2.x/templates.html#filters) are available to Twig templates in Craft: + +| Filter | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| [abs](https://twig.symfony.com/doc/2.x/filters/abs.html) | Returns the absolute value of a number. | +| [append](#append) | Appends HTML to the end of another element. | +| [ascii](#ascii) | Converts a string to ASCII characters. | +| [atom](#atom) | Converts a date to an ISO-8601 timestamp. | +| [attr](#attr) | Modifies an HTML tag’s attributes. | +| [batch](https://twig.symfony.com/doc/2.x/filters/batch.html) | Batches items in an array. | +| [camel](#camel) | Formats a string into camelCase. | +| [capitalize](https://twig.symfony.com/doc/2.x/filters/capitalize.html) | Capitalizes the first character of a string. | +| [column](#column) | Returns the values from a single property or key in an array. | +| [contains](#contains) | Returns whether an array contains a nested item with a given key/value pair. | +| [convert_encoding](https://twig.symfony.com/doc/2.x/filters/convert_encoding.html) | Converts a string from one encoding to another. | +| [currency](#currency) | Formats a number as currency. | +| [date](#date) | Formats a date. | +| [date_modify](https://twig.symfony.com/doc/2.x/filters/date_modify.html) | Modifies a date. | +| [datetime](#datetime) | Formats a date with its time. | +| [default](https://twig.symfony.com/doc/2.x/filters/default.html) | Returns the value or a default value if empty. | +| [duration](#duration) | Returns a `DateInterval` object. | +| [encenc](#encenc) | Encrypts and base64-encodes a string. | +| [escape](https://twig.symfony.com/doc/2.x/filters/escape.html) | Escapes a string. | +| [filesize](#filesize) | Formats a number of bytes into something else. | +| [filterByValue](#filterbyvalue) | Filters an array by key/value pairs. | +| [filter](#filter) | Filters the items in an array. | +| [first](https://twig.symfony.com/doc/2.x/filters/first.html) | Returns the first character/item of a string/array. | +| [format](https://twig.symfony.com/doc/2.x/filters/format.html) | Formats a string by replacing placeholders. | +| [group](#group) | Groups items in an array. | +| [hash](#hash) | Prefixes a string with a keyed-hash message authentication code (HMAC). | +| [id](#id) | Normalizes an element ID into only alphanumeric characters, underscores, and dashes. | +| [indexOf](#indexof) | Returns the index of a given value within an array, or the position of a passed-in string within another string. | +| [index](#index) | Indexes the items in an array. | +| [intersect](#intersect) | Returns the intersecting items of two arrays. | +| [join](https://twig.symfony.com/doc/2.x/filters/join.html) | Concatenates multiple strings into one. | +| [json_decode](#json_decode) | JSON-decodes a value. | +| [json_encode](#json_encode) | JSON-encodes a value. | +| [kebab](#kebab) | Formats a string into “kebab-case”. | +| [keys](https://twig.symfony.com/doc/2.x/filters/keys.html) | Returns the keys of an array. | +| [last](https://twig.symfony.com/doc/2.x/filters/last.html) | Returns the last character/item of a string/array. | +| [lcfirst](#lcfirst) | Lowercases the first character of a string. | +| [length](https://twig.symfony.com/doc/2.x/filters/length.html) | Returns the length of a string or array. | +| [literal](#literal) | Escapes an untrusted string for use with element query params. | +| [lower](https://twig.symfony.com/doc/2.x/filters/lower.html) | Lowercases a string. | +| [map](https://twig.symfony.com/doc/2.x/filters/map.html) | Applies an arrow function to the items in an array. | +| [markdown](#markdown-or-md) | Processes a string as Markdown. | +| [merge](https://twig.symfony.com/doc/2.x/filters/merge.html) | Merges an array with another array | +| [multisort](#multisort) | Sorts an array by one or more keys within its sub-arrays. | +| [namespace](#namespace) | Namespaces input names and other HTML attributes. | +| [namespaceInputId](#namespaceinputid) | Namespaces an element ID. | +| [namespaceInputName](#namespaceinputname) | Namespaces an input name. | +| [nl2br](https://twig.symfony.com/doc/2.x/filters/nl2br.html) | Replaces newlines with `
` tags. | +| [number](#number) | Formats a number. | +| [number_format](https://twig.symfony.com/doc/2.x/filters/number_format.html) | Formats numbers. | +| [parseRefs](#parserefs) | Parses a string for reference tags. | +| [pascal](#pascal) | Formats a string into “PascalCase”. | +| [percentage](#percentage) | Formats a percentage. | +| [prepend](#prepend) | Prepends HTML to the beginning of another element. | +| [purify](#purify) | Runs HTML code through HTML Purifier. | +| [raw](https://twig.symfony.com/doc/2.x/filters/raw.html) | Marks as value as safe for the current escaping strategy. | +| [reduce](https://twig.symfony.com/doc/2.x/filters/reduce.html) | Iteratively reduces a sequence or mapping to a single value. | +| [replace](#replace) | Replaces parts of a string with other things. | +| [reverse](https://twig.symfony.com/doc/2.x/filters/reverse.html) | Reverses a string or array. | +| [round](https://twig.symfony.com/doc/2.x/filters/round.html) | Rounds a number. | +| [rss](#rss) | Converts a date to RSS date format. | +| [slice](https://twig.symfony.com/doc/2.x/filters/slice.html) | Extracts a slice of a string or array. | +| [snake](#snake) | Formats a string into “snake_case”. | +| [sort](https://twig.symfony.com/doc/2.x/filters/sort.html) | Sorts an array. | +| [spaceless](https://twig.symfony.com/doc/2.x/filters/spaceless.html) | Removes whitespace between HTML tags. | +| [split](https://twig.symfony.com/doc/2.x/filters/split.html) | Splits a string by a delimiter. | +| [striptags](https://twig.symfony.com/doc/2.x/filters/striptags.html) | Strips SGML/XML tags from a string. | +| [time](#time) | Formats a time. | +| [timestamp](#timestamp) | Formats a human-readable timestamp. | +| [title](https://twig.symfony.com/doc/2.x/filters/title.html) | Formats a string into “Title Case”. | +| [translate](#translate-or-t) | Translates a message. | +| [trim](https://twig.symfony.com/doc/2.x/filters/trim.html) | Strips whitespace from the beginning and end of a string. | +| [ucfirst](#ucfirst) | Capitalizes the first character of a string. | +| [unique](#unique) | Removes duplicate values from an array. | +| [upper](https://twig.symfony.com/doc/2.x/filters/upper.html) | Formats a string into “UPPER CASE”. | +| [url_encode](https://twig.symfony.com/doc/2.x/filters/url_encode.html) | Percent-encodes a string as a URL segment or an array as a query string. | +| [values](#values) | Returns all the values in an array, resetting its keys. | +| [withoutKey](#withoutkey) | Returns an array without the specified key. | +| [without](#without) | Returns an array without the specified element(s). | + +## `append` + +Appends HTML to the end of another element. ```twig {{ entry.postDate|atom }} ``` -ユーザーが優先する言語に応じて指定された通貨で、数値をフォーマットします。 +If you only want to append a new element if one of the same type doesn’t already exist, pass `'keep'` as a second argument. ```twig {{ "foo bar"|camel }} {# Outputs: fooBar #} ``` -最後の引数に `true` を渡すと、フォーマットされる値が小数値(例:cents)を持たない場合、小数部の桁が削除されます。 +If you want to replace an existing element of the same type, pass `'replace'` as a second argument. ```twig {% set entryIds = entries|column('id') %} ``` -## `column` +## `ascii` -利用可能な `numberOptions` は、[こちらのリスト](api:yii\i18n\Formatter::$numberFormatterOptions)を参照してください。 +Converts a string to ASCII characters. ```twig {{ 1000000|currency('USD') }} → $1,000,000.00 {{ 1000000|currency('USD', [], [], true) }} → $1,000,000 ``` -利用可能な `textOptions` は、[こちらのリスト](api:yii\i18n\Formatter::$numberFormatterTextOptions) を参照してください。 +By default, the current site’s language will be used when choosing ASCII character mappings. You can override that by passing in a different locale ID. ```twig {{ entry.postDate|date }} → Sep 26, 2018 ``` -## `currency( currency, numberOptions, textOptions, stripZeros )` +## `atom` -タイムスタンプ、または、[DateTime](http://php.net/manual/en/class.datetime.php) オブジェクトのフォーマットされた日付を出力します。 +Converts a date to an ISO-8601 timestamp (e.g. `2019-01-29T10:00:00-08:00`), which should be used for Atom feeds, among other things. ```twig {{ entry.postDate|date('short') }} → 9/26/2018 ``` -## `date` +## `attr` -`format` パラメータに値を渡すことで、詳細がどの程度提供されるかをカスタマイズできます。 +Modifies an HTML tag’s attributes, using the same attribute definitions supported by using . ```twig {{ entry.postDate|date('short', locale='en-GB') }} → 26/9/2018 ``` -利用可能な `format` 値は、次の通りです。 +Only the first tag will be modified, and any HTML comments or doctype declarations before it will be ignored. ```twig -{{ entry.postDate|date('Y-m-d') }} → 2018-09-26 +{% set svg %} + + ... +{% endset %} +{{ svg|attr({ + class: 'icon' +}) }} +{# Output: + + ... #} ``` -使用される正確な時刻のフォーマットは、現在のアプリケーションのローケルに依存します。異なるローケルの時刻のフォーマットを使用したい場合、`locale` パラメータを利用します。 +Attributes can be removed by setting them to `false`. ```twig {{ entry.postDate|date('short', timezone='UTC') }} → 9/27/2018 ``` -PHP の `date()` ファンクションでサポートされるものと同じ [フォーマットオプション](http://php.net/manual/en/function.date.php) を使用して、カスタムの日付フォーマットを渡すこともできます。 +`class` and `style` attributes will be combined with the element’s existing attributes, if set. ```twig {{ entry.postDate|datetime }} → Sep 26, 2018, 5:00:00 PM ``` -`timezone` パラメータを使用して、出力される時刻のタイムゾーンをカスタマイズできます。 +All other attributes will replace the existing attribute values. ```twig {{ entry.postDate|datetime('short') }} → 9/26/2018, 5:00 PM ``` -タイムスタンプ、または、[DateTime](http://php.net/manual/en/class.datetime.php) オブジェクトのフォーマットされた(時刻を含む)日付を出力します。 +If you want to completely replace a `class` or `style` attribute, remove it first, then set the new value: ```twig {{ entry.postDate|datetime('short', locale='en-GB') }} → 26/9/2018, 17:00 ``` +## `camel` + +Returns a string formatted in “camelCase”. + +```twig +{{ entry.postDate|datetime('short', timezone='UTC') }} → 9/27/2018, 12:00 AM +``` + +## `column` + +Returns the values from a single property or key in the input array. + +```twig +

Posted {{ entry.postDate.diff(now)|duration(false) }} ago.

+``` + +An arrow function can be passed instead, if the values that should be returned don’t exist as a property or key on the array elements. + +```twig +{% set authorNames = entries|column(e => e.author.fullName) %} +``` + +This works similarly to Twig’s core [`column`](https://twig.symfony.com/doc/2.x/filters/column.html) filter, except that [ArrayHelper::getColumn()](api:yii\helpers\BaseArrayHelper::getColumn()) is used rather than PHP’s [array_column()](https://secure.php.net/array_column) function. + +## `contains` + +Returns whether the passed-in array contains any nested arrays/objects with a particular key/attribute set to a given value. + +```twig +{% set works = craft.entries() + .section('artwork') + .all() %} + +{# See if any of the artwork has a mature rating #} +{% if works|contains('rating', 'm') %} +

Some of this artwork is meant for mature viewers.

+{% endif %} +``` + +## `currency` + +Formats a number with a given currency according to the user’s preferred language. + +```twig +{{ 1000000|currency('USD') }} +{# Output: $1,000,000.00 #} +``` + +You can pass `stripZeros=true` to remove any fraction digits if the value to be formatted has no minor value (e.g. cents): + +```twig +{{ 1000000|currency('USD', stripZeros=true) }} +{# Output: $1,000,000 #} +``` + +## `date` + +Formats a timestamp or [DateTime](http://php.net/manual/en/class.datetime.php) object. + +```twig +{{ entry.postDate|date }} +{# Output: Dec 20, 1990 #} +``` + +You can customize how the date is presented by passing a custom date format, just like Twig’s core [`date`](https://twig.symfony.com/doc/2.x/filters/date.html) filter: + +```twig +{{ 'now'|date('m/d/Y') }} +{# Output: 12/20/1990 #} +``` + +Craft also provides some special format keywords that will output locale-specific date formats: + +| フォーマット | 実例 | +| ------------------ | --------------------------- | +| `short` | 12/20/1990 | +| `medium` _(デフォルト)_ | Dec 20, 1990 | +| `long` | December 20, 1990 | +| `full` | Thursday, December 20, 1990 | + +```twig +{{ entry.postDate|date('short') }} +{# Output: 12/20/1990 #} +``` + +The current application locale will be used by default. If you want to format the date for a different locale, use the `locale` argument: + +```twig +{{ entry.postDate|date('short', locale='en-GB') }} +{# Output: 20/12/1990 #} +``` + +You can customize the timezone the time is output in, using the `timezone` param: + +```twig +{{ entry.postDate|date('short', timezone='UTC') }} +{# Output: 12/21/1990 #} +``` + +::: tip +If the value passed to the date filter is `null`, it will return the current date by default. +::: + ## `datetime` -`format` パラメータに値を渡すことで、詳細がどの程度提供されるかをカスタマイズできます。 +Formats a timestamp or [DateTime](http://php.net/manual/en/class.datetime.php) object, including the time of day. -利用可能な `format` 値は、次の通りです。 +```twig +{{ entry.postDate|datetime }} +{# Output: Dec 20, 1990, 5:00:00 PM #} +``` + +Craft provides some special format keywords that will output locale-specific date and time formats: + +```twig +{{ entry.postDate|datetime('short') }} +{# Output: 9/26/2018, 5:00 PM #} +``` + +Possible `format` values are: + +| フォーマット | 実例 | +| ------------------ | --------------------------------------------- | +| `short` | 12/20/1990, 5:00 PM | +| `medium` _(デフォルト)_ | Dec 20, 1990, 5:00:00 PM | +| `long` | December 20, 1990 at 5:00:00 PM PDT | +| `full` | Thursday, December 20, 1990 at 5:00:00 PM PDT | + +The current application locale will be used by default. If you want to format the date and time for a different locale, use the `locale` argument: + +```twig +{{ entry.postDate|datetime('short', locale='en-GB') }} +{# Output: 20/12/1990, 17:00 #} +``` + +You can customize the timezone the time is output in, using the `timezone` param: + +```twig +{{ entry.postDate|datetime('short', timezone='UTC') }} +{# Output: 12/21/1990, 12:00 AM #} +``` ## `duration` -使用される正確な時刻のフォーマットは、現在のアプリケーションのローケルに依存します。異なるローケルの時刻のフォーマットを使用したい場合、`locale` パラメータを利用します。 +Runs a [DateInterval](http://php.net/manual/en/class.dateinterval.php) object through ```twig -{{ entry.postDate|datetime('short', timezone='UTC') }} → 9/27/2018, 12:00 AM +

Posted {{ entry.postDate.diff(now)|duration(false) }} ago.

``` ## `encenc` -`timezone` パラメータを使用して、出力される時刻のタイムゾーンをカスタマイズできます。 +Encrypts and base64-encodes a string. -[DateInterval](http://php.net/manual/en/class.dateinterval.php) オブジェクトに を実行します。 +```twig +{{ 'secure-string'|encenc }} +``` ## `filesize` -文字列を暗号化し、base64 エンコードします。 +Formats a number of bytes into something nicer. ```twig -

Posted {{ entry.postDate.diff(now)|duration(false) }} ago.

-``` +{{ asset.size }} +{# Output: 1944685 #} -バイト数をより良い何かにフォーマットします。 +{{ asset.size|filesize }} +{# Output: 1.945 MB #} +``` ## `filter` -配列から空のエレメントを削除し、変更された配列を返します。 +Filters elements of an array. + +If nothing is passed to it, any “empty” elements will be removed. + +```twig +{% set array = ['foo', '', 'bar', '', 'baz'] %} +{% set filteredArray = array|filter %} +{# Result: ['foo', 'bar', 'baz'] #} +``` + +When an arrow function is passed, this works identically to Twig’s core [`filter`](https://twig.symfony.com/doc/2.x/filters/filter.html) filter. -配列に を実行します。 +```twig +{% set array = ['foo', 'bar', 'baz'] %} +{% set filteredArray = array|filter(v => v[0] == 'b') %} +{# Result: ['bar', 'baz'] #} +``` ## `filterByValue` -共通のプロパティに基づいて、配列の項目をグループ化します。 +Runs an array through . ```twig -{{ "secure-string"|encenc }} +{% set array = { 'foo': 'bar', 'bar': 'baz', 'bat': 'bar' } %} +{{ array|filterByValue(v => v == 'bar') }} +{# Result: { 'foo': 'bar', 'bat': 'bar' } #} ``` -不正に変更されるべきではないフォームのデータを安全に渡すために、メッセージ認証コード(HMAC)の鍵付ハッシュを指定された文字列の先頭に追加します。 +## `group` + +Groups items in an array by a the results of an arrow function. ```twig {% set allEntries = craft.entries.section('blog').all() %} -{% set allEntriesByYear = allEntries|group('postDate|date("Y")') %} +{% set allEntriesByYear = allEntries|group(e => e.postDate|date('Y')) %} {% for year, entriesInYear in allEntriesByYear %}

{{ year }}

@@ -151,18 +394,18 @@ PHP の `date()` ファンクションでサポートされるものと同じ [ {% endfor %} ``` -## `group` +## `hash` -PHP スクリプトは、[Security::validateData()](api:yii\base\Security::validateData()) を経由して値を検証できます。 +Prefixes the given string with a keyed-hash message authentication code (HMAC), for securely passing data in forms that should not be tampered with. ```twig ``` -を経由して、HTML の input 要素の `id` としてうまく動作するよう、文字列をフォーマットします。 +PHP scripts can validate the value via [Security::validateData()](api:yii\base\Security::validateData()): -```twig -$foo = Craft::$app->request->getPost('foo'); +```php +$foo = Craft::$app->request->getBodyParam('foo'); $foo = Craft::$app->security->validateData($foo); if ($foo !== false) { @@ -170,47 +413,40 @@ if ($foo !== false) { } ``` -配列に [ArrayHelper::index()](api:yii\helpers\BaseArrayHelper::index()) を実行します。 +## `id` -| フォーマット | 実例 | -| ------------------ | ----------------------------- | -| `short` | 9/26/2018 | -| `medium` _(デフォルト)_ | Sep 26, 2018 | -| `long` | September 26, 2018 | -| `full` | Wednesday, September 26, 2018 | +Formats a string into something that will work well as an HTML input `id`, via . ```twig {% set name = 'input[name]' %} ``` -配列内の渡された値のインデックス、または、他の文字列に含まれる渡された文字列のインデックスを返します。(返される位置は、0 からはじまることに注意してください。)見つからなかった場合、代わりに `-1` が返されます。 +## `index` + +Runs an array through [ArrayHelper::index()](api:yii\helpers\BaseArrayHelper::index()). ```twig {% set entries = entries|index('id') %} ``` -渡された配列内にある値だけを含む配列を返します。 +## `indexOf` + +Returns the index of a passed-in value within an array, or the position of a passed-in string within another string. (Note that the returned position is 0-indexed.) If no position can be found, `-1` is returned instead. ```twig {% set colors = ['red', 'green', 'blue'] %}

Green is located at position {{ colors|indexOf('green') + 1 }}.

-{% set position = "team"|indexOf('i') %} +{% set position = 'team'|indexOf('i') %} {% if position != -1 %}

There is an “i” in “team”! It’s at position {{ position + 1 }}.

{% endif %} ``` -## `hash` - -Twig の [json_encode](https://twig.symfony.com/doc/2.x/filters/json_encode.html) フィルタと同様ですが、引数 `options` がセットされておらず、レスポンスのコンテンツタイプが `text/html` または `application/xhtml+xml` の場合、デフォルトで `JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT` になります。 - -を通して、文字列を JSON デコードし配列にします。 - -## `id` +## `intersect` -「kebab-case」でフォーマットされた文字列を返します。 +Returns an array containing only the values that are also in a passed-in array. ```twig {% set ownedIngredients = [ @@ -236,273 +472,177 @@ Twig の [json_encode](https://twig.symfony.com/doc/2.x/filters/json_encode.html %} ``` -ヒント:類推できない方のために、[シシカバブ](https://en.wikipedia.org/wiki/Kebab#Shish)の参照です。 +## `json_encode` -```twig -{% set arr = '[1, 2, 3]'|json_decode %} -``` +Returns the JSON representation of a value. -文字列の最初の文字を小文字にします。 +This works similarly to Twig’s core [`json_encode`](https://twig.symfony.com/doc/2.x/filters/json_encode.html) filter, except that the `options` argument will default to `JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT` if the response content type is either `text/html` or `application/xhtml+xml`. -| フォーマット | 実例 | -| ------------------ | ----------------------------------------------- | -| `short` | 9/26/2018, 5:00 PM | -| `medium` _(デフォルト)_ | Sep 26, 2018, 5:00:00 PM | -| `long` | September 26, 2018 at 5:00:00 PM PDT | -| `full` | Wednesday, September 26, 2018 at 5:00:00 PM PDT | +## `json_decode` -文字列に を実行します。 +JSON-decodes a string into an array by passing it through . ```twig -{{ "foo bar?"|kebab }} -{# Outputs: foo-bar #} +{% set arr = '[1, 2, 3]'|json_decode %} ``` -[Markdown](https://daringfireball.net/projects/markdown/) で文字列を処理します。 - -```twig -{% set content %} -# Everything You Need to Know About Computer Keyboards +## `kebab` -The only *real* computer keyboard ever made was famously -the [Apple Extended Keyboard II] [1]. +Returns a string formatted in “kebab-case”. - [1]: https://www.flickr.com/photos/gruber/sets/72157604797968156/ -{% endset %} +::: tip +That’s a reference to [shish kebabs](https://en.wikipedia.org/wiki/Kebab#Shish) for those of you that don’t get the analogy. +::: -{{ content|markdown }} +```twig +{{ 'foo bar?'|kebab }} +{# Output: foo-bar #} ``` -## `index` - -このフィルタは、2つの引数をサポートしています。 - -[ArrayHelper::multisort()](api:yii\helpers\BaseArrayHelper::multisort()) で配列をソートします。 - -## `indexOf` +## `lcfirst` -ユーザーが優先する言語に応じて、数値をフォーマットします。 +Lowercases the first character of a string. ```twig -{{ 1000000|number }} → 1,000,000 -{{ 1000000|number(false) }} → 1000000 +{{ 'Foobar'|lcfirst }} +{# Output: foobar #} ``` -## `intersect` +## `literal` -グループシンボル(例えば、英語のコンマ)を省略したい場合は、オプションで `false` を渡すことができます。 +Runs a string through . ```twig -{% set content %} - {entry:blog/hello-world:link} was my first blog post. Pretty geeky, huh? -{% endset %} - -{{ content|parseRefs|raw }} +{{ 'SELECT id, * FROM table'|literal }} +{# Output: SELECT id\, \* FROM table #} ``` -## `json_encode` - -[リファレンスタグ](../reference-tags.md)の文字列を解析します。 - -「PascalCase」(別名「UpperCamelCase」)でフォーマットされた文字列を返します。 - -## `json_decode` - -ユーザーが優先する言語に応じて、割合をフォーマットします。 - -## `kebab` - -文字列の一部を他のものに置き換えます。 +## `markdown` or `md` -ペアの検索 / 置換のオブジェクトを渡すことで、一度に複数のものを置き換えることができます。 +Processes a string with [Markdown](https://daringfireball.net/projects/markdown/). ```twig -{{ "foo bar"|pascal }} -{# Outputs: FooBar #} -``` +{% set content %} +# Everything You Need to Know About Computer Keyboards -または、一度に1つのものを置き換えることができます。 +The only *real* computer keyboard ever made was famously +the [Apple Extended Keyboard II] [1]. -```twig -{% set str = "Hello, FIRST LAST" %} + [1]: https://www.flickr.com/photos/gruber/sets/72157604797968156/ +{% endset %} -{{ str|replace({ - FIRST: currentUser.firstName, - LAST: currentUser.lastName -}) }} +{{ content|markdown }} ``` -## `lcfirst` - -置換文字列の値の最初と最後にスラッシュを付けてマッチするものを検索することで、正規表現も利用できます。 - -## `literal` - -最も近い整数値に数を丸めます。 - -RSS フィードに必要な形式(`D, d M Y H:i:s O`)で日付を出力します。 - -## `format` - -「snake_case」でフォーマットされた文字列を返します。 - -タイムスタンプ、または、[DateTime](http://php.net/manual/en/class.datetime.php) オブジェクトのフォーマットされた時刻を出力します。 +This filter supports two arguments: +- `flavor` は、`'original'`(デフォルト値)、`'gfm'`(GitHub-Flavored Markdown)、`'gfm-comment'`(改行が`
`に変換された GFM)、 または、`'extra'`(Markdown Extra)にできます。 +- `inlineOnly` は、`

` タグを除き、インライン要素だけを解析するかどうかを決定します。(デフォルトは `false`) ## `multisort` -`format` パラメータに値を渡すことで、詳細がどの程度提供されるかをカスタマイズできます。 - -```twig -{% set str = "Hello, NAME" %} - -{{ str|replace('NAME', currentUser.name) }} -``` - -## `number` +Sorts an array by one or more properties or keys within an array’s values. -利用可能な `format` 値は、次の通りです。 +To sort by a single property or key, pass its name as a string: ```twig -{{ tag.title|lower|replace('/[^\\w]+/', '-') }} -``` - -使用される正確な時刻のフォーマットは、現在のアプリケーションのローケルに依存します。異なるローケルの時刻のフォーマットを使用したい場合、`locale` パラメータを利用します。 - -```php -{{ 42.1|round }} → 42 -{{ 42.9|round }} → 43 +{% set entries = entries|multisort('title') %} ``` -## `parseRefs` - -`timezone` パラメータを使用して、出力される時刻のタイムゾーンをカスタマイズできます。 +To sort by multiple properties or keys, pass them in as an array. For example, this will sort entries by their post date first, and then by their title: ```twig -{{ entry.postDate|rss }} +{% set entries = entries|multisort(['postDate', 'title']) %} ``` -## `pascal` - -経由で、人が読めるタイムスタンプとして日付をフォーマットします。 +An arrow function can be passed instead, if the values that should be sorted by don’t exist as a property or key on the array elements. ```twig -{{ "foo bar"|snake }} -{# Outputs: foo_bar #} +{% set entries = entries|multisort(e => e.author.fullName) %} ``` -## `percentage` - -[Craft::t()](api:yii\BaseYii::t()) でメッセージを翻訳します。 +The values will be sorted in ascending order by default. You can switch to descending order with the `direction` param: ```twig -{{ entry.postDate|time }} → 10:00:00 AM +{% set entries = entries|multisort('title', direction=SORT_DESC) %} ``` -## `replace` - -カテゴリの指定がない場合、デフォルトで `site` になります。 +You can also customize which sorting behavior is used, with the `sortFlag` param. For example, to sort items numerically, use `SORT_NUMERIC`: ```twig -{{ entry.postDate|time('short') }} → 10:00 AM +{% set entries = entries|multisort('id', sortFlag=SORT_NUMERIC) %} ``` -## `round` - -::: tip -これがどのように機能するかの詳細については、[静的メッセージの翻訳](../static-translations.md)を参照してください。 -::: - -文字列の最初の文字を大文字にします。 - -## `rss` - -文字列に含まれるそれぞれの単語の最初の文字を大文字にします。 - -配列に [array_unique()](http://php.net/manual/en/function.array-unique.php) を実行します。 +See PHP’s [sort()](https://www.php.net/manual/en/function.sort.php) documentation for the available sort flags. -## `snake` - -指定された配列のすべての値の配列を返しますが、カスタムキーは除かれます。 +When sorting by multiple properties or keys, you must set the `direction` and `sortFlag` params to arrays as well. ```twig -{{ entry.postDate|time('short', locale='en-GB') }} → 17:00 +{% set entries = entries|multisort([ + 'postDate', + 'title', +], sortFlag=[SORT_NATURAL, SORT_FLAG_CASE]) %} ``` -## `time` +## `namespace` -指定されたエレメントを除いた配列を返します。 +The `|namespace` filter can be used to namespace input names and other HTML attributes. -Tip: That’s a reference to [shish kebabs](https://en.wikipedia.org/wiki/Kebab#Shish) for those of you that don’t get the analogy. +For example, this: ```twig -{{ entry.postDate|time('short', timezone='UTC') }} → 12:00 AM +{% set html %} + +{% endset %} +{{ html|namespace('foo') }} ``` -## `timestamp` - -Returns the keys of an array. - -This works identically to Twig’s core [`keys`](https://twig.symfony.com/doc/2.x/filters/keys.html) filter. - -## `last` - -Returns the last element of an array or string. - -This works identically to Twig’s core [`last`](https://twig.symfony.com/doc/2.x/filters/last.html) filter. - -## `ucfirst` - -Lowercases the first character of a string. - -## `ucwords` +would become this: -Returns the number of elements in an array or string. +```html + +``` -This works identically to Twig’s core [`length`](https://twig.symfony.com/doc/2.x/filters/length.html) filter. +Notice how the `id` attribute changed from `title` to `foo-title`, and the `name` attribute changed from `title` to `foo[title]`. -## `unique` +## `namespaceInputId` -Runs a string through +Namepaces an element ID. -## `values` +For example, this: -Converts a value to lowercase. +```twig +{{ 'bar'|namespaceInputId('foo') }} +``` -This works identically to Twig’s core [`lower`](https://twig.symfony.com/doc/2.x/filters/lower.html) filter. +would output: -## `without` +```html +foo-bar +``` -Applies an arrow function to the elements of an array. +::: tip +If this is used within a [namespace](tags.md#namespace) tag, the namespace applied by the tag will be used by default. +::: -This works identically to Twig’s core [`map`](https://twig.symfony.com/doc/2.x/filters/map.html) filter. +## `namespaceInputName` -## `markdown` or `md` +Namepaces an input name. -Processes a string with [Markdown](https://daringfireball.net/projects/markdown/). +For example, this: ```twig -{{ "Hello world"|t('myCategory') }} +{{ 'bar'|namespaceInputName('foo') }} ``` -This filter supports two arguments: -- `flavor` は、`'original'`(デフォルト値)、`'gfm'`(GitHub-Flavored Markdown)、`'gfm-comment'`(改行が`
`に変換された GFM)、 または、`'extra'`(Markdown Extra)にできます。 -- `inlineOnly` は、`

` タグを除き、インライン要素だけを解析するかどうかを決定します。(デフォルトは `false`) - -## `merge` - -Merges an array with another array. - -This works identically to Twig’s core [`merge`](https://twig.symfony.com/doc/2.x/filters/merge.html) filter. - -## `multisort` - -Sorts an array with [ArrayHelper::multisort()](api:yii\helpers\BaseArrayHelper::multisort()). +would output: -## `nl2br` - -Inserts HTML line breaks before all newlines in a string. +```html +foo[bar] +``` -This works identically to Twig’s core [`nl2br`](https://twig.symfony.com/doc/2.x/filters/nl2br.html) filter. +::: tip +If this is used within a [namespace](tags.md#namespace) tag, the namespace applied by the tag will be used by default. +::: ## `number` @@ -511,23 +651,23 @@ Formats a number according to the user’s preferred language. You can optionally pass `false` to it if you want group symbols to be omitted (e.g. commas in English). ```twig -{{ "Hello world"|t }} -``` +{{ 1000000|number }} +{# Output: 1,000,000 #} -## `number_format` - -Formats numbers. It is a wrapper around PHP’s [number_format()](https://secure.php.net/number_format) function: - -This works identically to Twig’s core [`number_format`](https://twig.symfony.com/doc/2.x/filters/number_format.html) filter. +{{ 1000000|number(false) }} +{# Output: 1000000 #} +``` ## `parseRefs` Parses a string for [reference tags](../reference-tags.md). ```twig -{% set arr1 = {foo: "Foo", bar: "Bar"} %} -{% set arr2 = arr1|values %} -{# arr2 = ["Foo", "Bar"] #} +{% set content %} + {entry:blog/hello-world:link} was my first blog post. Pretty geeky, huh? +{% endset %} + +{{ content|parseRefs|raw }} ``` ## `pascal` @@ -535,9 +675,8 @@ Parses a string for [reference tags](../reference-tags.md). Returns a string formatted in “PascalCase” (AKA “UpperCamelCase”). ```twig -{% set entries = craft.entries.section('articles').limit(3).find %} -{% set firstEntry = entries[0] %} -{% set remainingEntries = entries|without(firstEntry) %} +{{ 'foo bar'|pascal }} +{# Output: FooBar #} ``` ## `percentage` @@ -567,17 +706,21 @@ If you want to replace an existing element of the same type, pass `'replace'` as {# Output:

Lorem

#} ``` -## `raw` +## `purify` -Marks a value as being “safe”, which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it. +Runs the given text through HTML Purifier. -This works identically to Twig’s core [`raw`](https://twig.symfony.com/doc/2.x/filters/raw.html) filter. +```twig +{{ user.bio|purify }} +``` -## `reduce` +You can specify a custom HTML Purifier config file as well: -Iteratively reduces a sequence or a mapping to a single value using an arrow function, so as to reduce it to a single value. The arrow function receives the return value of the previous iteration and the current value of the sequence or mapping. +```twig +{{ user.bio|purify('user_bio') }} +``` -This works identically to Twig’s core [`reduce`](https://twig.symfony.com/doc/2.x/filters/reduce.html) filter. +That will configure HTML Purifier based on the settings defined by `config/htmlpurifier/user_bio.json`. ## `replace` @@ -608,18 +751,6 @@ You can also use a regular expression to search for matches by starting and endi {{ tag.title|lower|replace('/[^\\w]+/', '-') }} ``` -## `reverse` - -Reverses an array or string. - -This works identically to Twig’s core [`reverse`](https://twig.symfony.com/doc/2.x/filters/reverse.html) filter. - -## `round` - -Rounds a number to a given precision. - -This works identically to Twig’s core [`round`](https://twig.symfony.com/doc/2.x/filters/round.html) filter. - ## `rss` Outputs a date in the format required for RSS feeds (`D, d M Y H:i:s O`). @@ -628,12 +759,6 @@ Outputs a date in the format required for RSS feeds (`D, d M Y H:i:s O`). {{ entry.postDate|rss }} ``` -## `slice` - -Extracts a slice of an array or string. - -This works identically to Twig’s core [`slice`](https://twig.symfony.com/doc/2.x/filters/slice.html) filter. - ## `snake` Returns a string formatted in “snake_case”. @@ -643,30 +768,6 @@ Returns a string formatted in “snake_case”. {# Output: foo_bar #} ``` -## `sort` - -Sorts an array. - -This works identically to Twig’s core [`sort`](https://twig.symfony.com/doc/2.x/filters/sort.html) filter. - -## `spaceless` - -Removes whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text. - -This works identically to Twig’s core [`spaceless`](https://twig.symfony.com/doc/2.x/filters/spaceless.html) filter. - -## `split` - -Splits a string by the given delimiter and returns a list of string. - -This works identically to Twig’s core [`split`](https://twig.symfony.com/doc/2.x/filters/split.html) filter. - -## `striptags` - -Strips SGML/XML tags and replace adjacent whitespace by one space. - -This works identically to Twig’s core [`striptags`](https://twig.symfony.com/doc/2.x/filters/striptags.html) filter. - ## `time` Outputs the time of day for a timestamp or [DateTime](http://php.net/manual/en/class.datetime.php) object. @@ -685,11 +786,11 @@ Craft provides some special format keywords that will output locale-specific tim Possible `format` values are: -| フォーマット | 実例 | -| ------------------ | -------------- | -| `short` | 5:00 PM | -| `medium` _(デフォルト)_ | 5:00:00 PM | -| `long` | 5:00:00 PM PDT | +| Format | Example | +| -------------------- | -------------- | +| `short` | 5:00 PM | +| `medium` _(default)_ | 5:00:00 PM | +| `long` | 5:00:00 PM PDT | The current application locale will be used by default. If you want to format the date and time for a different locale, use the `locale` argument: @@ -709,17 +810,10 @@ You can customize the timezone the time is output in, using the `timezone` param Formats a date as a human-readable timestamp, via . -## `title` - -Returns a titlecased version of the value. Words will start with uppercase letters, all remaining characters are lowercase. - -This works identically to Twig’s core [`title`](https://twig.symfony.com/doc/2.x/filters/title.html) filter. - -## `trim` - -Strips whitespace (or other characters) from the beginning and end of a string - -This works identically to Twig’s core [`trim`](https://twig.symfony.com/doc/2.x/filters/trim.html) filter. +```twig +{{ now|timestamp }} +{# Output: 9:00:00 AM #} +``` ## `translate` or `t` @@ -743,25 +837,20 @@ See [Static Message Translations](../static-translations.md) for a full explanat Capitalizes the first character of a string. -## `ucwords` - -Capitalizes the first character of each word in a string. +```twig +{{ 'foobar'|ucfirst }} +{# Output: Foobar #} +``` ## `unique` Runs an array through [array_unique()](http://php.net/manual/en/function.array-unique.php). -## `upper` - -Converts a value to uppercase. - -This works identically to Twig’s core [`upper`](https://twig.symfony.com/doc/2.x/filters/upper.html) filter. - -## `url_encode` - -Percent-encodes a given string as URL segment or an array as query string. - -This works identically to Twig’s core [`url_encode`](https://twig.symfony.com/doc/2.x/filters/url_encode.html) filter. +```twig +{% set array = ['Larry', 'Darryl', 'Darryl'] %} +{{ array|unique }} +{# Result: ['Larry', 'Darryl'] #} +``` ## `values` diff --git a/ja/dev/functions.md b/ja/dev/functions.md index e34d6f645cb..5acd66c3cad 100644 --- a/ja/dev/functions.md +++ b/ja/dev/functions.md @@ -1,6 +1,52 @@ # ファンクション -[Twig に付随する](https://twig.symfony.com/doc/functions/index.html)テンプレートファンクションに加えて、Craft がいくつか独自のものを提供します。 +The following [functions](https://twig.symfony.com/doc/2.x/templates.html#functions) are available to Twig templates in Craft: + +| Function | Description | +| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| [actionInput](#actioninput) | Outputs a hidden `action` input. | +| [actionUrl](#actionurl) | Generates a controller action URL. | +| [alias](#alias) | Parses a string as an alias. | +| [attr](#attr) | Generates HTML attributes. | +| [attribute](https://twig.symfony.com/doc/2.x/functions/attribute.html) | Accesses a dynamic attribute of a variable. | +| [beginBody](#beginbody) | Outputs scripts and styles that were registered for the “begin body” position. | +| [block](https://twig.symfony.com/doc/2.x/functions/block.html) | Prints a block’s output. | +| [ceil](#ceil) | Rounds a number up. | +| [className](#classname) | Returns the fully qualified class name of a given object. | +| [clone](#clone) | Clones an object. | +| [combine](#combine) | Combines two arrays into one. | +| [constant](https://twig.symfony.com/doc/2.x/functions/constant.html) | Returns the constant value for a given string. | +| [create](#create) | Creates a new object. | +| [csrfInput](#csrfinput) | Returns a hidden CSRF token input. | +| [cpUrl](#cpurl) | Generates a control panel URL. | +| [cycle](https://twig.symfony.com/doc/2.x/functions/cycle.html) | Cycles on an array of values. | +| [date](https://twig.symfony.com/doc/2.x/functions/date.html) | Creates a date. | +| [dump](https://twig.symfony.com/doc/2.x/functions/dump.html) | Dumps information about a variable. | +| [endBody](#endbody) | Outputs scripts and styles that were registered for the “end body” position. | +| [expression](#expression) | Creates a database expression object. | +| [floor](#floor) | Rounds a number down. | +| [getenv](#getenv) | Returns the value of an environment variable. | +| [gql](#gql) | Executes a GraphQL query against the full schema. | +| [parseEnv](#parseenv) | Parses a string as an environment variable or alias. | +| [head](#head) | Outputs scripts and styles that were registered for the “head” position. | +| [hiddenInput](#hiddeninput) | Outputs a hidden input. | +| [include](https://twig.symfony.com/doc/2.x/functions/include.html) | Returns the rendered content of a template. | +| [input](#input) | Outputs an HTML input. | +| [max](https://twig.symfony.com/doc/2.x/functions/max.html) | Returns the biggest value in an array. | +| [min](https://twig.symfony.com/doc/2.x/functions/min.html) | Returns the lowest value in an array. | +| [parent](https://twig.symfony.com/doc/2.x/functions/parent.html) | Returns the parent block’s output. | +| [plugin](#plugin) | Returns a plugin instance by its handle. | +| [random](https://twig.symfony.com/doc/2.x/functions/random.html) | Returns a random value. | +| [range](https://twig.symfony.com/doc/2.x/functions/range.html) | Returns a list containing an arithmetic progression of integers. | +| [redirectInput](#redirectinput) | Outputs a hidden `redirect` input. | +| [seq](#seq) | Outputs the next or current number in a sequence. | +| [shuffle](#shuffle) | Randomizes the order of the items in an array. | +| [siteUrl](#siteurl) | Generates a front-end URL. | +| [svg](#svg) | Outputs an SVG document. | +| [source](https://twig.symfony.com/doc/2.x/functions/source.html) | Returns the content of a template without rendering it. | +| [tag](#tag) | Outputs an HTML tag. | +| [template_from_string](https://twig.symfony.com/doc/2.x/functions/template_from_string.html) | Loads a template from a string. | +| [url](#url) | Generates a URL. | ## `actionInput( actionPath )` @@ -17,9 +63,21 @@ ``` -## `alias( string )` +## `actionUrl` -「begin body」に登録されたスクリプトやスタイルを出力します。`` タグの直後に配置する必要があります。 +Returns a controller action URL, automatically accounting for relative vs. absolute format and the active setting. + +### 引数 + +The `actionUrl()` function has the following arguments: + +* **`path`** – 結果となる URL がサイトで指すべきパス。それは、ベースサイト URL に追加されます。 +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). +* **`scheme`** – URL が使用するスキーム(`'http'` または `'https'`)。デフォルト値は、現在のリクエストが SSL 経由で配信されているかどうかに依存します。そうでなければ、サイト URL のスキームが使用され、SSL 経由なら `https` が使用されます。 + +## `alias` + +Passes a string through [Craft::getAlias()](api:yii\BaseYii::getAlias()), which will check if the string begins with an [alias](https://www.yiiframework.com/doc/guide/2.0/en/concept-aliases). (See [Configuration](../config/README.md#aliases) for more info.) ```twig @@ -30,38 +88,32 @@ ``` -## `beginBody()` +## `attr` -整数値に切り上げます。 +Generates a list of HTML attributes based on the given [hash](twig-primer.md#hashes), using . ```twig {{ ceil(42.1) }} → 43 ``` -## `ceil( num )` - -指定されたオブジェクトの完全修飾クラス名を返します。 - -指定されたオブジェクトのクローンを作成します。 +## `beginBody` -## `className( object )` - -与えられたクラス名やオブジェクト設定に基づいて新しいオブジェクトインスタンスを作成します。サポートされる引数の詳細については、 を参照してください。 +Outputs any scripts and styles that were registered for the “begin body” position. It should be placed right after your `` tag. ```twig {% set query = craft.entries.section('news') %} {% set articles = clone(query).type('articles') %} ``` -## `clone( object )` +## `block` -不可視の CSRF トークン入力欄を返します。CSRF 保護が有効になっているすべてのサイトでは、POST 経由で送信するそれぞれのフォームにこれを含めなければなりません。 +Prints a block’s output. -「end body」に登録されたスクリプトやスタイルを出力します。`` タグの直前に配置する必要があります。 +This works identically to Twig’s core [`block`](https://twig.symfony.com/doc/2.x/functions/block.html) function. -## `create( type )` +## `ceil` -データベースクエリで使用するための新しい オブジェクトを作成して返します。 +Rounds a number up. ```twig {# Pass in a class name #} @@ -75,18 +127,18 @@ }) %} ``` -## `csrfInput()` +## `className` -整数値に切り捨てます。 +Returns the fully qualified class name of a given object. ```twig
{{ csrfInput() }}
``` -## `endBody()` +## `clone` -環境変数の値を返します。 +Clones a given object. ```twig @@ -97,122 +149,173 @@ ``` -## `expression( expression, params, config )` +## `combine` -文字列が環境変数(`$VARIABLE_NAME`)、および / または、エイリアス(`@aliasName`)を参照しているかどうかを確認し、参照されている値を返します。 +Combines two arrays into one, using the first array to define the keys, and the second array to define the values. -「head」に登録されたスクリプトやスタイルを出力します。`` タグの直前に配置する必要があります。 +```twig +{% set arr1 = ['a', 'b', 'c'] %} +{% set arr2 = ['foo', 'bar', 'baz'] %} +{% set arr3 = combine(arr1, arr2) %} +{# arr3 will now be `{a: 'foo', b: 'bar', c: 'baz'}` #} +``` -## `floor( num )` +## `constant` -ハンドルに従ってプラグインインスタンスを返します。そのハンドルでインストールされ有効化されているプラグインがない場合、`null` を返します。 +Returns the constant value for a given string. -```twig -{{ floor(42.9) }} → 42 -``` +This works identically to Twig’s core [`constant`](https://twig.symfony.com/doc/2.x/functions/constant.html) function. -## `getenv( name )` +## `create` -`` を入力するためのショートカットです。 +Creates a new object instance based on a given class name or object configuration. See for a full explanation of supported arguments. ```twig -{{ getenv('MAPS_API_KEY') }} +{# Pass in a class name #} +{% set cookie = create('yii\\web\\Cookie') %} + +{# Or a full object configuration hash #} +{% set cookie = create({ + class: 'yii\\web\\cookie', + name: 'foo', + value: 'bar' +}) %} ``` -`name` で定義されたシーケンスの次または現在の番号を出力します。 +## `cpUrl` + +Returns a control panel URL, automatically accounting for relative vs. absolute format and the active setting. ```twig - - {{ siteName }} - {{ head() }} - +Visit control panel settings ``` -## `parseEnv( str )` - -ファンクションが呼び出されるたびに、与えられたシーケンスは自動的にインクリメントされます。 +### 引数 -オプションで特定の長さにゼロ詰めした数値にすることができます。 +The `cpUrl()` function has the following arguments: -## `head()` +* **`path`** – The path that the resulting URL should point to on your site. It will be appended to your base site URL. +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). +* **`scheme`** – Which scheme the URL should use (`'http'` or `'https'`). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, then `https` will be used. -インクリメントせずにシーケンスの現在の数字を表示するには、`next` 引数に `false` をセットします。 +## `csrfInput` -配列内のエレメントの順序をランダム化します。 +Returns a hidden CSRF Token input. All sites that have CSRF Protection enabled must include this in each form that submits via POST. -## `plugin( handle )` +```twig +{{ csrfInput() }} +``` -サイト上のページへの URL を作成するため _だけ_ という点を除けば、[url()](#url-path-params-scheme-mustshowscriptname) と似ています。 +You can optionally set additional attributes on the tag by passing an `options` argument. -`siteUrl()` ファンクションは、次の引数を持っています。 +```twig +{{ csrfInput({ + id: 'csrf-input' +}) }} +``` -## `redirectInput( url )` +## `endBody` -SVG 文書を出力します。 +Outputs any scripts and styles that were registered for the “end body” position. It should be placed right before your `` tag. ```twig -{{ plugin('commerce').version }} + +

{{ page.name }}

+ {{ page.body }} + + {{ endBody() }} + ``` -## `seq( name, length, next )` +## `expression` -次のものを渡すことができます。 +Creates and returns a new object, for use in database queries. ```twig -

This entry has been read {{ seq('hits:' ~ entry.id) }} times.

+{% set entries = craft.entries() + .andWhere(expression('[[authorId]] = :authorId', {authorId: currentUser.id})) + .all() %} ``` -## `shuffle( array )` +## `floor` -ファンクションにアセットまたは生のマークアップを渡した場合、デフォルトでは SVG は [svg-sanitizer](https://github.com/darylldoyle/svg-sanitizer) を使用して潜在的に悪意のあるスクリプトをサニタイズし、ドキュメント内の ID や class 名が DOM の他の ID や class 名と衝突しないよう名前空間を付加します。引数 `sanitize`、および、`namespace` を使用して、これらの動作を無効にできます。 +Rounds a number down. ```twig -{{ now|date('Y') ~ '-' ~ seq('orderNumber:' ~ now|date('Y'), 5) }} -{# outputs: 2018-00001 #} +{{ floor(42.9) }} +{# Output: 42 #} ``` -## `siteUrl( path, params, scheme, siteId )` +## `getenv` -引数 `class` を使用して、ルートの `` ノードに追加する独自の class 名を指定することもできます。 +Returns the value of an environment variable. ```twig -
{{ entry.title }}
-

{{ seq('hits:' ~ entry.id, next=false) }} views

+{{ getenv('MAPS_API_KEY') }} ``` -## `svg( svg, sanitize, namespace, class )` +## `gql` -URL を返します。 +Executes a GraphQL query against the full schema. -## `url( path, params, scheme, mustShowScriptName )` +```twig +{% set result = gql('{ + entries (section: "news", limit: 2, orderBy: "dateCreated DESC") { + postDate @formatDateTime (format: "Y-m-d") + title + url + ... on news_article_Entry { + shortDescription + featuredImage { + url @transform (width: 300, immediately: true) + altText + } + } + } +}') %} -`url()` ファンクションは、次の引数を持っています。 +{% for entry in result.data %} +

{{ entry.title }}

+

{{ entry.postDate }}

-```twig -{% set promos = shuffle(homepage.promos) %} + {% set image = entry.featuredImage[0] %} + {{ image.altText }} -{% for promo in promos %} -
-

{{ promo.title }}

-

{{ promo.description }}

- {{ promo.ctaLabel }} -
+ {{ entry.shortDescription|markdown }} +

Continue reading…

{% endfor %} ``` +## `parseEnv` + +Checks if a string references an environment variable (`$VARIABLE_NAME`) and/or an alias (`@aliasName`), and returns the referenced value. + +## `head` + +Outputs any scripts and styles that were registered for the “head” position. It should be placed right before your `` tag. + +```twig + + {{ siteName }} + {{ head() }} + +``` + ## `hiddenInput` -::: tip -クエリ文字列パラメータを追加、および / または、絶対 URL にスキームを適用するために、`url()` ファンクションを使用することができます。 +Generates an HTML input tag. ```twig -Contact Us +{{ hiddenInput('entryId', entry.id) }} +{# Output: #} ``` -::: +You can optionally set additional attributes on the tag by passing an `options` argument. ```twig -{{ svg(image, sanitize=false, namespace=false) }} +{{ hiddenInput('entryId', entry.id, { + id: 'entry-id-input' +}) }} ``` ## `include` @@ -226,13 +329,16 @@ This works identically to Twig’s core [`include`](https://twig.symfony.com/doc Generates an HTML input tag. ```twig -{{ svg('@webroot/icons/lemon.svg', class='lemon-icon') }} +{{ input('email', 'email-input', '') }} +{# Output: #} ``` You can optionally set additional attributes on the tag by passing an `options` argument. ```twig -Contact Us +{{ input('email', 'email-input', '', { + id: 'custom-input' +}) }} ``` ## `max` @@ -247,33 +353,14 @@ Returns the lowest value in an array. This works identically to Twig’s core [`min`](https://twig.symfony.com/doc/2.x/functions/min.html) function. -## `parent` - -Returns the parent block’s output. - -This works identically to Twig’s core [`parent`](https://twig.symfony.com/doc/2.x/functions/parent.html) function. - ## `plugin` Returns a plugin instance by its handle, or `null` if no plugin is installed and enabled with that handle. ```twig -{{ url('http://my-project.com', 'foo=1', 'https') }} -{# Outputs: "https://my-project.com?foo=1" #} +{{ plugin('commerce').version }} ``` -## `random` - -Returns a random value. - -This works identically to Twig’s core [`random`](https://twig.symfony.com/doc/2.x/functions/random.html) function. - -## `range` - -Returns a list containing an arithmetic progression of integers. - -This works identically to Twig’s core [`range`](https://twig.symfony.com/doc/2.x/functions/range.html) function. - ## `redirectInput` Shortcut for typing ``. @@ -319,9 +406,10 @@ To view the current number in the sequence without incrementing it, set the `nex Randomizes the order of the elements within an array. ```twig -{% set promos = shuffle(homepage.promos) %} +{% set promos = craft.entries.section('promos').all() %} +{% set shuffledPromos = shuffle(promos) %} -{% for promo in promos %} +{% for promo in shuffledPromos %}

{{ promo.title }}

{{ promo.description }}

@@ -338,14 +426,14 @@ Similar to [url()](#url-path-params-scheme-mustshowscriptname), except _only_ fo Contact Us ``` -### 引数 +### Arguments The `siteUrl()` function has the following arguments: * **`path`** – 結果となる URL がサイトで指すべきパス。それは、ベースサイト URL に追加されます。 -* **`params`** – URL に追加するクエリ文字列パラメータ。これは文字列(例:`'foo=1&bar=2'`)またはオブジェクト(例:`{foo:'1', bar:'2'}`)が利用可能です。 +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). * **`scheme`** – URL が使用するスキーム(`'http'` または `'https'`)。デフォルト値は、現在のリクエストが SSL 経由で配信されているかどうかに依存します。そうでなければ、サイト URL のスキームが使用され、SSL 経由なら `https` が使用されます。 -* **`siteId`** – URL が指すべきサイト ID。デフォルトでは、現在のサイトが使用されます。 +* **`siteId`** – The ID of the site that the URL should point to. By default the current site will be used. ## `svg` @@ -353,7 +441,7 @@ Outputs an SVG document. You can pass the following things into it: -- SVG ファイルのパス。 +- An SVG file path. ```twig {{ svg('@webroot/icons/lemon.svg') }} @@ -363,16 +451,16 @@ You can pass the following things into it: ```twig {% set image = entry.myAssetsField.one() %} - {% if image and image.extension == 'svg' %} - {{ svg(image) }} - {% endif %} + {% if image and image.extension == 'svg' %} + {{ svg(image) }} + {% endif %} ``` -- 生の SVG マークアップ。 +- Raw SVG markup. ```twig {% set image = include('_includes/icons/lemon.svg') %} - {{ svg(image) }} + {{ svg(image) }} ``` By default, if you pass an asset or raw markup into the function, the SVG will be sanitized of potentially malicious scripts using [svg-sanitizer](https://github.com/darylldoyle/svg-sanitizer), and any IDs or class names within the document will be namespaced so they don’t conflict with other IDs or class names in the DOM. You can disable those behaviors using the `sanitize` and `namespace` arguments: @@ -424,12 +512,6 @@ If `html` is included in the attributes argument (and `text` isn’t), its value All other keys passed to the second argument will be set as attributes on the tag, using . -## `template_from_string` - -Loads a template from a string. - -This works identically to Twig’s core [`template_from_string`](https://twig.symfony.com/doc/2.x/functions/template_from_string.html) function. - ## `url` Returns a URL. @@ -438,14 +520,14 @@ Returns a URL. Contact Us ``` -### 引数 +### Arguments The `url()` function has the following arguments: -* **`path`** – 結果となる URL がサイトで指すべきパス。それは、ベースサイト URL に追加されます。 -* **`params`** – URL に追加するクエリ文字列パラメータ。これは文字列(例:`'foo=1&bar=2'`)またはオブジェクト(例:`{foo:'1', bar:'2'}`)が利用可能です。 -* **`scheme`** – URL が使用するスキーム(`'http'` または `'https'`)。デフォルト値は、現在のリクエストが SSL 経由で配信されているかどうかに依存します。そうでなければ、サイト URL のスキームが使用され、SSL 経由なら `https` が使用されます。 -* **`mustShowScriptName`** – ここに `true` がセットされている場合、「index.php」を含めた URL が返され、コンフィグ設定の は無視されます。(ブラウザのアドレスバーに表示されない URL と .htaccess ファイルのリダイレクトとの衝突を避けたいような、Ajax 経由の POST リクエストで使用される URL の場合に有用です。) +* **`path`** – The path that the resulting URL should point to on your site. It will be appended to your base site URL. +* **`params`** – Any query string parameters that should be appended to the URL. This can be either a string (e.g. `'foo=1&bar=2'`) or a [hash](twig-primer.md#hashes) (e.g. `{foo:'1', bar:'2'}`). +* **`scheme`** – Which scheme the URL should use (`'http'` or `'https'`). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, then `https` will be used. +* **`mustShowScriptName`** – If this is set to `true`, then the URL returned will include “index.php”, disregarding the config setting. (This can be useful if the URL will be used by POST requests over Ajax, where the URL will not be shown in the browser’s address bar, and you want to avoid a possible collision with your site’s .htaccess file redirect.) ::: tip You can use the `url()` function for appending query string parameters and/or enforcing a scheme on an absolute URL: diff --git a/ja/dev/global-variables.md b/ja/dev/global-variables.md index c541098b9cf..828297b900c 100644 --- a/ja/dev/global-variables.md +++ b/ja/dev/global-variables.md @@ -1,6 +1,37 @@ # グローバル変数 -ありとあらゆるテンプレートでは、次の変数を読み込むことができます。 +The following [global variables](https://twig.symfony.com/doc/2.x/templates.html#global-variables) are available to Twig templates in Craft: + +| Variable | Description | +| --------------------------------------------- | --------------------------------------------------------------------------- | +| `_self` | The current template name. | +| `_context` | The currently-defined variables. | +| `_charset` | The current charset. | +| [craft](#craft) | A object. | +| [currentSite](#currentsite) | The requested site. | +| [currentUser](#currentuser) | The currently logged-in user. | +| [devMode](#devmode) | Whether Dev Mode is enabled. | +| [Global set variables](#global-set-variables) | Variables for each of the global sets. | +| [loginUrl](#loginurl) | The URL to the front-end Login page. | +| [logoutUrl](#logouturl) | The URL to the front-end Logout page. | +| [now](#now) | The current date/time. | +| [POS_BEGIN](#pos-begin) | The [craft\web\View::POS_BEGIN](api:craft\web\View#constants) constant. | +| [POS_END](#pos-end) | The [craft\web\View::POS_END](api:craft\web\View#constants) constant. | +| [POS_HEAD](#pos-head) | The [craft\web\View::POS_HEAD](api:craft\web\View#constants) constant. | +| [POS_LOAD](#pos-load) | The [craft\web\View::POS_LOAD](api:craft\web\View#constants) constant. | +| [POS_READY](#pos-ready) | The [craft\web\View::POS_READY](api:craft\web\View#constants) constant. | +| [siteName](#sitename) | The name of the current site. | +| [siteUrl](#siteurl) | The base URL of the current site. | +| [SORT_ASC](#sort-asc) | The `SORT_ASC` PHP constant. | +| [SORT_DESC](#sort-desc) | The `SORT_DESC` PHP constant. | +| [SORT_FLAG_CASE](#sort-flag-case) | The `SORT_FLAG_CASE` PHP constant. | +| [SORT_LOCALE_STRING](#sort-locale-string) | The `SORT_LOCALE_STRING` PHP constant. | +| [SORT_NATURAL](#sort-natural) | The `SORT_NATURAL` PHP constant. | +| [SORT_NUMERIC](#sort-numeric) | The `SORT_NUMERIC` PHP constant. | +| [SORT_REGULAR](#sort-regular) | The `SORT_REGULAR` PHP constant. | +| [SORT_STRING](#sort-string) | The `SORT_STRING` PHP constant.T | +| [systemName](#systemname) | The system name. | +| [view](#view) | The app’s `view` component. | ## `craft` diff --git a/ja/dev/headless.md b/ja/dev/headless.md index ee12e54f379..04eda1cd7a9 100644 --- a/ja/dev/headless.md +++ b/ja/dev/headless.md @@ -4,22 +4,24 @@ Craft のテンプレートシステムは、Craft のコンテンツを取得 Craft を通常のウェブサイト(または、それに加える)の代わりにコンテンツ API として動作するという意味でのヘッドレス CMS として使用する場合、いくつかの方法があります。 +To see exactly what enabling Headless Mode does, see the [`headlessMode` config setting](../config/config-settings.md#headlessmode). + ::: tip -Craft をヘッドレス CMS として使用する方法について学ぶために、CraftQuest の [Headless Craft CMS](https://craftquest.io/courses/headless-craft) コースをチェックしてください。 +Check out CraftQuest’s [Headless Craft CMS](https://craftquest.io/courses/headless-craft) course to learn more about using Craft as a headless CMS. ::: ## GraphQL -Mark Huot 氏による [CraftQL](https://github.com/markhuot/craftql) プラグンは、設定なしの [GraphQL](https://graphql.org/) サーバーをインストールされた Craft に追加します。 +Craft comes with a built-in, self-generating [GraphQL API](../graphql.md). ## JSON API -ファーストパーティの [Element API](https://github.com/craftcms/element-api) は、コンテンツのための読み取り専用の [JSON API](http://jsonapi.org/) を作成する簡単な方法です。 +The first-party [Element API](https://github.com/craftcms/element-api) offers a simple way to create a read-only [JSON API](http://jsonapi.org/) for your content. ## REST API -Craft で REST API を作成する方法を詳しく知るために、Nate Iler 氏の Dot All 2017 のプレゼンテーション [How to Create a Full REST API](http://dotall.com/sessions/how-to-create-a-full-rest-api-with-craft-3) を見てください。 +Watch Nate Iler’s [How to Create a Full REST API](http://dotall.com/sessions/how-to-create-a-full-rest-api-with-craft-3) presentation from Dot All 2017 for an in-depth look at how to create a REST API with Craft. ## カスタムなもの -モジュールやプラグインは、新しい HTTP エンドポイントを提供するためのカスタムのフロントエンド[コントローラー](https://www.yiiframework.com/doc/guide/2.0/en/structure-controllers)を定義できます。 はじめるには、[Craft の拡張](../extend/README.md)を参照してください。 +Modules and plugins can define custom front-end [controllers](https://www.yiiframework.com/doc/guide/2.0/en/structure-controllers) that provide new HTTP endpoints. See [Extending Craft](../extend/README.md) to get started. diff --git a/ja/dev/tags.md b/ja/dev/tags.md index 84f031a09dc..6d0ba4daeb0 100644 --- a/ja/dev/tags.md +++ b/ja/dev/tags.md @@ -1,16 +1,711 @@ # タグ -[Twig に付随する](https://twig.symfony.com/doc/tags/index.html)テンプレートタグに加えて、Craft がいくつか独自のものを提供します。 - -- [cache](tags/cache.md) -- [css](tags/css.md) -- [exit](tags/exit.md) -- [header](tags/header.md) -- [hook](tags/hook.md) -- [js](tags/js.md) -- [nav](tags/nav.md) -- [paginate](tags/paginate.md) -- [redirect](tags/redirect.md) -- [requireLogin](tags/requirelogin.md) -- [requirePermission](tags/requirepermission.md) -- [switch](tags/switch.md) +The following [tags](https://twig.symfony.com/doc/2.x/templates.html#control-structure) are available to Twig templates in Craft: + +| Tag | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------ | +| [apply](https://twig.symfony.com/doc/2.x/tags/apply.html) | Applies Twig filters to the nested template code. | +| [autoescape](https://twig.symfony.com/doc/2.x/tags/autoescape.html) | Controls the escaping strategy for the nested template code. | +| [block](https://twig.symfony.com/doc/2.x/tags/block.html) | Defines a template block. | +| [cache](#cache) | Caches a portion of your template. | +| [css](#css) | Registers a `