code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
falcon Testing Testing
=======
Reference
---------
Functional testing framework for Falcon apps and Falcon itself.
Falcon’s testing module contains various test classes and utility functions to support functional testing for both Falcon-based apps and the Falcon framework itself.
The testing framework supports both unittest and pytest:
```
# -----------------------------------------------------------------
# unittest
# -----------------------------------------------------------------
from falcon import testing
import myapp
class MyTestCase(testing.TestCase):
def setUp(self):
super(MyTestCase, self).setUp()
# Assume the hypothetical `myapp` package has a
# function called `create()` to initialize and
# return a `falcon.API` instance.
self.app = myapp.create()
class TestMyApp(MyTestCase):
def test_get_message(self):
doc = {u'message': u'Hello world!'}
result = self.simulate_get('/messages/42')
self.assertEqual(result.json, doc)
# -----------------------------------------------------------------
# pytest
# -----------------------------------------------------------------
from falcon import testing
import pytest
import myapp
# Depending on your testing strategy and how your application
# manages state, you may be able to broaden the fixture scope
# beyond the default 'function' scope used in this example.
@pytest.fixture()
def client():
# Assume the hypothetical `myapp` package has a function called
# `create()` to initialize and return a `falcon.API` instance.
return testing.TestClient(myapp.create())
def test_get_message(client):
doc = {u'message': u'Hello world!'}
result = client.simulate_get('/messages/42')
assert result.json == doc
```
`class falcon.testing.Result(iterable, status, headers)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#Result)
Encapsulates the result of a simulated WSGI request.
| Parameters: | * **iterable** (*iterable*) – An iterable that yields zero or more bytestrings, per PEP-3333
* **status** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – An HTTP status string, including status code and reason string
* **headers** ([list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.7)")) – A list of (header\_name, header\_value) tuples, per PEP-3333
|
`status`
HTTP status string given in the response
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`status_code`
The code portion of the HTTP status string
| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") |
`headers`
A case-insensitive dictionary containing all the headers in the response, except for cookies, which may be accessed via the `cookies` attribute.
Note
Multiple instances of a header in the response are currently not supported; it is unspecified which value will “win” and be represented in `headers`.
| Type: | CaseInsensitiveDict |
`cookies`
A dictionary of [`falcon.testing.Cookie`](#falcon.testing.Cookie "falcon.testing.Cookie") values parsed from the response, by name.
| Type: | [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)") |
`encoding`
Text encoding of the response body, or `None` if the encoding can not be determined.
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`content`
Raw response body, or `bytes` if the response body was empty.
| Type: | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.7)") |
`text`
Decoded response body of type `unicode` under Python 2.7, and of type `str` otherwise. If the content type does not specify an encoding, UTF-8 is assumed.
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`json`
Deserialized JSON body. Will be `None` if the body has no content to deserialize. Otherwise, raises an error if the response is not valid JSON.
| Type: | JSON serializable |
`class falcon.testing.Cookie(morsel)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#Cookie)
Represents a cookie returned by a simulated request.
| Parameters: | **morsel** – A `Morsel` object from which to derive the cookie data. |
`name`
The cookie’s name.
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`value`
The value of the cookie.
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`expires`
Expiration timestamp for the cookie, or `None` if not specified.
| Type: | [datetime.datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.7)") |
`path`
The path prefix to which this cookie is restricted, or `None` if not specified.
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`domain`
The domain to which this cookie is restricted, or `None` if not specified.
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`max_age`
The lifetime of the cookie in seconds, or `None` if not specified.
| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") |
`secure`
Whether or not the cookie may only only be transmitted from the client via HTTPS.
| Type: | [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)") |
`http_only`
Whether or not the cookie may only be included in unscripted requests from the client.
| Type: | [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)") |
`falcon.testing.simulate_request(app, method='GET', path='/', query_string=None, headers=None, body=None, json=None, file_wrapper=None, wsgierrors=None, params=None, params_csv=True, protocol='http', host='falconframework.org', remote_addr=None, extras=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_request)
Simulates a request to a WSGI application.
Performs a request against a WSGI application. Uses [`wsgiref.validate`](https://docs.python.org/3/library/wsgiref.html#module-wsgiref.validate "(in Python v3.7)") to ensure the response is valid WSGI.
| Keyword Arguments: |
| | * **app** ([callable](https://docs.python.org/3/library/functions.html#callable "(in Python v3.7)")) – The WSGI application to call
* **method** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – An HTTP method to use in the request (default: ‘GET’)
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request (default: ‘/’). Note The path may contain a query string. However, neither `query_string` nor `params` may be specified in this case.
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **query\_string** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A raw query string to include in the request (default: `None`). If specified, overrides `params`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **body** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: `None`). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
* **json** (*JSON serializable*) – A JSON document to serialize as the body of the request (default: `None`). If specified, overrides `body` and the Content-Type header in `headers`.
* **file\_wrapper** ([callable](https://docs.python.org/3/library/functions.html#callable "(in Python v3.7)")) – Callable that returns an iterable, to be used as the value for *wsgi.file\_wrapper* in the environ (default: `None`). This can be used to test high-performance file transmission when `resp.stream` is set to a file-like object.
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **wsgierrors** ([io](https://docs.python.org/3/library/io.html#module-io "(in Python v3.7)")) – The stream to use as *wsgierrors* (default `sys.stderr`)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
| Returns: | The result of the request |
| Return type: | [`Result`](#falcon.testing.Result "falcon.testing.Result") |
`falcon.testing.simulate_get(app, path, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_get)
Simulates a GET request to a WSGI application.
Equivalent to:
```
simulate_request(app, 'GET', path, **kwargs)
```
| Parameters: | * **app** (*callable*) – The WSGI application to call
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request. Note The path may contain a query string. However, neither `query_string` nor `params` may be specified in this case.
|
| Keyword Arguments: |
| | * **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **query\_string** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A raw query string to include in the request (default: `None`). If specified, overrides `params`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **file\_wrapper** ([callable](https://docs.python.org/3/library/functions.html#callable "(in Python v3.7)")) – Callable that returns an iterable, to be used as the value for *wsgi.file\_wrapper* in the environ (default: `None`). This can be used to test high-performance file transmission when `resp.stream` is set to a file-like object.
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
`falcon.testing.simulate_head(app, path, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_head)
Simulates a HEAD request to a WSGI application.
Equivalent to:
```
simulate_request(app, 'HEAD', path, **kwargs)
```
| Parameters: | * **app** (*callable*) – The WSGI application to call
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request. Note The path may contain a query string. However, neither `query_string` nor `params` may be specified in this case.
|
| Keyword Arguments: |
| | * **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **query\_string** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A raw query string to include in the request (default: `None`). If specified, overrides `params`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
`falcon.testing.simulate_post(app, path, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_post)
Simulates a POST request to a WSGI application.
Equivalent to:
```
simulate_request(app, 'POST', path, **kwargs)
```
| Parameters: | * **app** (*callable*) – The WSGI application to call
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request
|
| Keyword Arguments: |
| | * **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **body** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: `None`). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
* **json** (*JSON serializable*) – A JSON document to serialize as the body of the request (default: `None`). If specified, overrides `body` and the Content-Type header in `headers`.
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
`falcon.testing.simulate_put(app, path, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_put)
Simulates a PUT request to a WSGI application.
Equivalent to:
```
simulate_request(app, 'PUT', path, **kwargs)
```
| Parameters: | * **app** (*callable*) – The WSGI application to call
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request
|
| Keyword Arguments: |
| | * **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **body** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: `None`). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
* **json** (*JSON serializable*) – A JSON document to serialize as the body of the request (default: `None`). If specified, overrides `body` and the Content-Type header in `headers`.
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
`falcon.testing.simulate_options(app, path, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_options)
Simulates an OPTIONS request to a WSGI application.
Equivalent to:
```
simulate_request(app, 'OPTIONS', path, **kwargs)
```
| Parameters: | * **app** (*callable*) – The WSGI application to call
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request
|
| Keyword Arguments: |
| | * **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
`falcon.testing.simulate_patch(app, path, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_patch)
Simulates a PATCH request to a WSGI application.
Equivalent to:
```
simulate_request(app, 'PATCH', path, **kwargs)
```
| Parameters: | * **app** (*callable*) – The WSGI application to call
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request
|
| Keyword Arguments: |
| | * **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **body** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: `None`). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
* **json** (*JSON serializable*) – A JSON document to serialize as the body of the request (default: `None`). If specified, overrides `body` and the Content-Type header in `headers`.
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
`falcon.testing.simulate_delete(app, path, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#simulate_delete)
Simulates a DELETE request to a WSGI application.
Equivalent to:
```
simulate_request(app, 'DELETE', path, **kwargs)
```
| Parameters: | * **app** (*callable*) – The WSGI application to call
* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The URL path to request
|
| Keyword Arguments: |
| | * **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a `str` or something that can be converted into a `str`, or a list of such values. If a `list`, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
* **params\_csv** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – Set to `False` to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to `True`.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional headers to include in the request (default: `None`)
* **protocol** – The protocol to use for the URL scheme (default: ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’)
* **extras** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Additional CGI variables to add to the WSGI `environ` dictionary for the request (default: `None`)
|
`class falcon.testing.TestClient(app, headers=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient)
Simulates requests to a WSGI application.
This class provides a contextual wrapper for Falcon’s `simulate_*` test functions. It lets you replace this:
```
simulate_get(app, '/messages')
simulate_head(app, '/messages')
```
with this:
```
client = TestClient(app)
client.simulate_get('/messages')
client.simulate_head('/messages')
```
Note
The methods all call `self.simulate_request()` for convenient overriding of request preparation by child classes.
| Parameters: | **app** (*callable*) – A WSGI application to target when simulating requests |
| Keyword Arguments: |
| | **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Default headers to set on every request (default `None`). These defaults may be overridden by passing values for the same headers to one of the `simulate_*()` methods. |
`simulate_delete(path='/', **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_delete)
Simulates a DELETE request to a WSGI application.
(See also: [`falcon.testing.simulate_delete()`](#falcon.testing.simulate_delete "falcon.testing.simulate_delete"))
`simulate_get(path='/', **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_get)
Simulates a GET request to a WSGI application.
(See also: [`falcon.testing.simulate_get()`](#falcon.testing.simulate_get "falcon.testing.simulate_get"))
`simulate_head(path='/', **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_head)
Simulates a HEAD request to a WSGI application.
(See also: [`falcon.testing.simulate_head()`](#falcon.testing.simulate_head "falcon.testing.simulate_head"))
`simulate_options(path='/', **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_options)
Simulates an OPTIONS request to a WSGI application.
(See also: [`falcon.testing.simulate_options()`](#falcon.testing.simulate_options "falcon.testing.simulate_options"))
`simulate_patch(path='/', **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_patch)
Simulates a PATCH request to a WSGI application.
(See also: [`falcon.testing.simulate_patch()`](#falcon.testing.simulate_patch "falcon.testing.simulate_patch"))
`simulate_post(path='/', **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_post)
Simulates a POST request to a WSGI application.
(See also: [`falcon.testing.simulate_post()`](#falcon.testing.simulate_post "falcon.testing.simulate_post"))
`simulate_put(path='/', **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_put)
Simulates a PUT request to a WSGI application.
(See also: [`falcon.testing.simulate_put()`](#falcon.testing.simulate_put "falcon.testing.simulate_put"))
`simulate_request(*args, **kwargs)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/client.html#TestClient.simulate_request)
Simulates a request to a WSGI application.
Wraps [`falcon.testing.simulate_request()`](#falcon.testing.simulate_request "falcon.testing.simulate_request") to perform a WSGI request directly against `self.app`. Equivalent to:
```
falcon.testing.simulate_request(self.app, *args, **kwargs)
```
`class falcon.testing.TestCase(methodName='runTest')` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/test_case.html#TestCase)
Extends [`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest "(in Python v3.7)") to support WSGI functional testing.
Note
If available, uses `testtools` in lieu of [`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest "(in Python v3.7)").
This base class provides some extra plumbing for unittest-style test cases, to help simulate WSGI calls without having to spin up an actual web server. Various simulation methods are derived from [`falcon.testing.TestClient`](#falcon.testing.TestClient "falcon.testing.TestClient").
Simply inherit from this class in your test case classes instead of [`unittest.TestCase`](https://docs.python.org/3/library/unittest.html#unittest.TestCase "(in Python v3.7)") or `testtools.TestCase`.
`app`
A WSGI application to target when simulating requests (default: `falcon.API()`). When testing your application, you will need to set this to your own instance of `falcon.API`. For example:
```
from falcon import testing
import myapp
class MyTestCase(testing.TestCase):
def setUp(self):
super(MyTestCase, self).setUp()
# Assume the hypothetical `myapp` package has a
# function called `create()` to initialize and
# return a `falcon.API` instance.
self.app = myapp.create()
class TestMyApp(MyTestCase):
def test_get_message(self):
doc = {u'message': u'Hello world!'}
result = self.simulate_get('/messages/42')
self.assertEqual(result.json, doc)
```
| Type: | [object](https://docs.python.org/3/library/functions.html#object "(in Python v3.7)") |
`setUp()` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/test_case.html#TestCase.setUp)
Hook method for setting up the test fixture before exercising it.
`class falcon.testing.SimpleTestResource(status=None, body=None, json=None, headers=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/resource.html#SimpleTestResource)
Mock resource for functional testing of framework components.
This class implements a simple test resource that can be extended as needed to test middleware, hooks, and the Falcon framework itself.
Only noop `on_get()` and `on_post()` responders are implemented; when overriding these, or adding additional responders in child classes, they can be decorated with the [`falcon.testing.capture_responder_args()`](#falcon.testing.capture_responder_args "falcon.testing.capture_responder_args") hook in order to capture the *req*, *resp*, and *params* arguments that are passed to the responder. Responders may also be decorated with the `falcon.testing.set_resp_defaults()` hook in order to set *resp* properties to default *status*, *body*, and *header* values.
| Keyword Arguments: |
| | * **status** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – Default status string to use in responses
* **body** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – Default body string to use in responses
* **json** (*JSON serializable*) – Default JSON document to use in responses. Will be serialized to a string and encoded as UTF-8. Either *json* or *body* may be specified, but not both.
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Default set of additional headers to include in responses
|
`called`
Whether or not a req/resp was captured.
| Type: | [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)") |
`captured_req`
The last Request object passed into any one of the responder methods.
| Type: | [falcon.Request](request_and_response#falcon.Request "falcon.Request") |
`captured_resp`
The last Response object passed into any one of the responder methods.
| Type: | [falcon.Response](request_and_response#falcon.Response "falcon.Response") |
`captured_kwargs`
The last dictionary of kwargs, beyond `req` and `resp`, that were passed into any one of the responder methods.
| Type: | [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)") |
`class falcon.testing.StartResponseMock` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/srmock.html#StartResponseMock)
Mock object representing a WSGI `start_response` callable.
`call_count`
Number of times `start_response` was called.
| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") |
`status`
HTTP status line, e.g. ‘785 TPS Cover Sheet not attached’.
| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)") |
`headers`
Raw headers list passed to `start_response`, per PEP-333.
| Type: | [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.7)") |
`headers_dict`
Headers as a case-insensitive `dict`-like object, instead of a `list`.
| Type: | [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)") |
`falcon.testing.capture_responder_args(req, resp, resource, params)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/resource.html#capture_responder_args)
Before hook for capturing responder arguments.
Adds the following attributes to the hooked responder’s resource class:
* captured\_req
* captured\_resp
* captured\_kwargs
`falcon.testing.rand_string(min, max)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/helpers.html#rand_string)
Returns a randomly-generated string, of a random length.
| Parameters: | * **min** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – Minimum string length to return, inclusive
* **max** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – Maximum string length to return, inclusive
|
`falcon.testing.create_environ(path='/', query_string='', protocol='HTTP/1.1', scheme='http', host='falconframework.org', port=None, headers=None, app='', body='', method='GET', wsgierrors=None, file_wrapper=None, remote_addr=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/helpers.html#create_environ)
Creates a mock PEP-3333 environ `dict` for simulating WSGI requests.
| Keyword Arguments: |
| | * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The path for the request (default ‘/’)
* **query\_string** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The query string to simulate, without a leading ‘?’ (default ‘’)
* **protocol** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The HTTP protocol to simulate (default ‘HTTP/1.1’). If set to ‘HTTP/1.0’, the Host header will not be added to the environment.
* **scheme** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – URL scheme, either ‘http’ or ‘https’ (default ‘http’)
* **host** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – Hostname for the request (default ‘falconframework.org’)
* **port** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’).
* **headers** ([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – Headers as a `dict` or an iterable yielding (*key*, *value*) `tuple`’s
* **app** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – Value for the `SCRIPT_NAME` environ variable, described in PEP-333: ‘The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This may be an empty string, if the application corresponds to the “root” of the server.’ (default ‘’)
* **body** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The body of the request (default ‘’). Accepts both byte strings and Unicode strings. Unicode strings are encoded as UTF-8 in the request.
* **method** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – The HTTP method to use (default ‘GET’)
* **wsgierrors** ([io](https://docs.python.org/3/library/io.html#module-io "(in Python v3.7)")) – The stream to use as *wsgierrors* (default `sys.stderr`)
* **file\_wrapper** – Callable that returns an iterable, to be used as the value for *wsgi.file\_wrapper* in the environ.
* **remote\_addr** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – Remote address for the request (default ‘127.0.0.1’)
|
`falcon.testing.redirected(stdout=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, stderr=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/helpers.html#redirected)
A context manager to temporarily redirect stdout or stderr
e.g.:
with redirected(stderr=os.devnull): …
`falcon.testing.closed_wsgi_iterable(iterable)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/testing/helpers.html#closed_wsgi_iterable)
Wraps an iterable to ensure its `close()` method is called.
Wraps the given `iterable` in an iterator utilizing a `for` loop as illustrated in [the PEP-3333 server/gateway side example](https://www.python.org/dev/peps/pep-3333/#the-server-gateway-side). Finally, if the iterable has a `close()` method, it is called upon exception or exausting iteration.
Furthermore, the first bytestring yielded from iteration, if any, is prefetched before returning the wrapped iterator in order to ensure the WSGI `start_response` function is called even if the WSGI application is a generator.
| Parameters: | **iterable** (*iterable*) – An iterable that yields zero or more bytestrings, per PEP-3333 |
| Returns: | An iterator yielding the same bytestrings as `iterable` |
| Return type: | iterator |
| programming_docs |
falcon Redirection Redirection
===========
Falcon defines a set of exceptions that can be raised within a middleware method, hook, or responder in order to trigger a 3xx (Redirection) response to the client. Raising one of these classes short-circuits request processing in a manner similar to raising an instance or subclass of [`HTTPError`](errors#falcon.HTTPError "falcon.HTTPError")
Redirects
---------
`exception falcon.HTTPMovedPermanently(location, headers=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/redirects.html#HTTPMovedPermanently)
301 Moved Permanently.
The 301 (Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI.
Note
For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 308 (Permanent Redirect) status code can be used instead.
(See also: [RFC 7231, Section 6.4.2](https://tools.ietf.org/html/rfc7231#section-6.4.2))
| Parameters: | **location** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – URI to provide as the Location header in the response. |
`exception falcon.HTTPFound(location, headers=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/redirects.html#HTTPFound)
302 Found.
The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.
Note
For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.
(See also: [RFC 7231, Section 6.4.3](https://tools.ietf.org/html/rfc7231#section-6.4.3))
| Parameters: | **location** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – URI to provide as the Location header in the response. |
`exception falcon.HTTPSeeOther(location, headers=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/redirects.html#HTTPSeeOther)
303 See Other.
The 303 (See Other) status code indicates that the server is redirecting the user agent to a *different* resource, as indicated by a URI in the Location header field, which is intended to provide an indirect response to the original request.
A 303 response to a GET request indicates that the origin server does not have a representation of the target resource that can be transferred over HTTP. However, the Location header in the response may be dereferenced to obtain a representation for an alternative resource. The recipient may find this alternative useful, even though it does not represent the original target resource.
Note
The new URI in the Location header field is not considered equivalent to the effective request URI.
(See also: [RFC 7231, Section 6.4.4](https://tools.ietf.org/html/rfc7231#section-6.4.4))
| Parameters: | **location** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – URI to provide as the Location header in the response. |
`exception falcon.HTTPTemporaryRedirect(location, headers=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/redirects.html#HTTPTemporaryRedirect)
307 Temporary Redirect.
The 307 (Temporary Redirect) status code indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI. Since the redirection can change over time, the client ought to continue using the original effective request URI for future requests.
Note
This status code is similar to 302 (Found), except that it does not allow changing the request method from POST to GET.
(See also: [RFC 7231, Section 6.4.7](https://tools.ietf.org/html/rfc7231#section-6.4.7))
| Parameters: | **location** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – URI to provide as the Location header in the response. |
`exception falcon.HTTPPermanentRedirect(location, headers=None)` [[source]](https://falcon.readthedocs.io/en/2.0.0/_modules/falcon/redirects.html#HTTPPermanentRedirect)
308 Permanent Redirect.
The 308 (Permanent Redirect) status code indicates that the target resource has been assigned a new permanent URI.
Note
This status code is similar to 301 (Moved Permanently), except that it does not allow changing the request method from POST to GET.
(See also: [RFC 7238, Section 3](https://tools.ietf.org/html/rfc7238#section-3))
| Parameters: | **location** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – URI to provide as the Location header in the response. |
requirejs Plugins Plugins
=======
* [Intro](#intro)
* [Plugin Names](#names)
* [API](#api)
+ [load](#apiload)
+ [normalize](#apinormalize)
+ [write](#apiwrite)
+ [onLayerEnd](#apionlayerend)
+ [writeFile](#apiwritefile)
+ [pluginBuilder](#apipluginbuilder)
Intro
------
RequireJS allows you to write loader plugins that can load different types of resources as dependencies, and even include the dependencies in optimized builds.
Examples of existing loader plugins are the [text!](api#text) and [i18n!](api#i18n) plugins. The text! plugin handles loading text, and the i18n plugin handles loading a JavaScript object that is made up from objects from a few different modules. The object contains localized strings.
The RequireJS wiki has a longer [list of plugins](https://github.com/requirejs/requirejs/wiki/Plugins).
Plugin Names
-------------
Loader plugins are just another module, but they implement a specific API. Loader plugins can also participate in the optimizer optimizations, allowing the resources they load to be inlined in an optimized build.
**Note**: the plugin and its dependencies should be able to run in non-browser environments like Node and Nashorn. If they cannot, you should use an alternate [plugin builder](#apipluginbuilder) module that can run in those environments so that they can participate in optimization builds.
You can reference your plugin by putting its module name before a ! in the dependency. For instance, if you create a plugin with the name "foo.js", you would use it like so:
```
require(['foo!something/for/foo'], function (something) {
//something is a reference to the resource
//'something/for/foo' that was loaded by foo.js.
});
```
So, the plugin's module name comes before the ! separator. The part after the ! separator is called the **resource name**. The resource name may look like a normal module name. The plugin's module name can be any valid module name, so for instance, you could use a relative indicator:
```
require(['./foo!something/for/foo'], function (something) {
});
```
Or, if it was inside a package or directory, say bar/foo.js:
```
require(['bar/foo!something/for/foo'], function (something) {
});
```
API
----
RequireJS will load the plugin module first, then pass the rest of the dependency name to a load() method on the plugin. There are also some methods to help with module name normalization and for making use of the plugin as part of the [optimizer](optimization).
The complete Plugin API:
* **[load](#apiload)**: A function that is called to load a resource. This is the only mandatory API method that needs to be implemented for the plugin to be useful.
* **[normalize](#apinormalize)**: A function to normalize the resource name. This is useful in providing optimal caching and optimization, but only needed if the resource name is not a module name.
* **[write](#apiwrite)**: used by the optimizer to indicate when the plugin should write out a representation of the resource in the optimized file.
* **[pluginBuilder](#apipluginbuilder)**: A module name string for a module that should be used in the optimizer to do optimization work. That module is used instead of the plugin module when the optimizer runs.
### load: function (name, parentRequire, onload, config)
load is a function, and it will be called with the following arguments:
* **name**: String. The name of the resource to load. This is the part after the ! separator in the name. So, if a module asks for 'foo!something/for/foo', the foo module's load function will receive 'something/for/foo' as the name.
* **parentRequire**: Function. A local "require" function to use to load other modules. This function will resolve relative module names relative to the module name that asked for this plugin resource. If the loader plugin wants to `require()` something relative to its own ID, it can ask for a `require` in its own `define` call. This require function has some utilities on it:
+ **parentRequire.toUrl(moduleResource)**:where moduleResource is a module name plus an extension. For instance "view/templates/main.html". It will return a full path to the resource, obeying any RequireJS configuration.
+ **parentRequire.defined(moduleName)**: Returns true if the module has already been loaded and defined. Used to be called require.isDefined before RequireJS 0.25.0.
+ **parentRequire.specified(moduleName)**: Returns true if the module has already been requested or is in the process of loading and should be available at some point.
* **onload**: Function. A function to call with the value for name. This tells the loader that the plugin is done loading the resource. **onload.error()** can be called, passing an error object to it, if the plugin detects an error condition that means the resource will fail to load correctly.
* **config**: Object. A configuration object. This is a way for the optimizer and the web app to pass configuration information to the plugin. The i18n! plugin uses this to get the current locale, if the web app wants to force a specific locale. The optimizer will set an **isBuild** property in the config to true if this plugin (or pluginBuilder) is being called as part of an optimizer build.
An example plugin that does not do anything interesting, just does a normal require to load a JS module:
```
define({
load: function (name, req, onload, config) {
//req has the same API as require().
req([name], function (value) {
onload(value);
});
}
});
```
Some plugins may need to evaluate some JavaScript that was retrieved as text, and use that evaluated JavaScript as the value for the resource. There is a function off the onload() argument, **onload.fromText()**, that can be used to evaluate the JavaScript. eval() is used by RequireJS to evaluate that JavaScript, and RequireJS will do the right work for any anonymous define() call in the evaluated text, and use that define() module as the value for the resource.
Arguments for onload.fromText() (RequireJS 2.1.0 and later):
* **text**: String. The string of JavaScript to evaluate.
An example plugin's load function that uses onload.fromText():
```
define({
load: function (name, req, onload, config) {
var url = req.toUrl(name + '.customFileExtension'),
text;
//Use a method to load the text (provided elsewhere)
//by the plugin
fetchText(url, function (text) {
//Transform the text as appropriate for
//the plugin by using a transform()
//method provided elsewhere in the plugin.
text = transform(text);
//Have RequireJS execute the JavaScript within
//the correct environment/context, and trigger the load
//call for this resource.
onload.fromText(text);
});
}
});
```
Before RequireJS 2.1.0, onload.fromText accepted a moduleName as the first argument: `onload.fromText(moduleName, text)`, and the loader plugin had to manually call `require([moduleName], onload)` after the onload.fromText() call.
**Build considerations**: The optimizer traces dependencies **synchronously** to simplify the optimization logic. This is different from how require.js in the browser works, and it means that only plugins that can satisfy their dependencies synchronously should participate in the optimization steps that allow inlining of loader plugin values. Otherwise, the plugin should just call load() immediately if `config.isBuild` is true:
```
define({
load: function (name, req, onload, config) {
if (config.isBuild) {
//Indicate that the optimizer should not wait
//for this resource any more and complete optimization.
//This resource will be resolved dynamically during
//run time in the web browser.
onload();
} else {
//Do something else that can be async.
}
}
});
```
Some plugins may do an async operation in the browser, but opt to complete the resource load synchronously when run in Node/Nashorn. This is what the text plugin does. If you just want to run AMD modules and load plugin dependencies using [amdefine](http://github.com/jrburke/amdefine) in Node, those also need to complete synchronously to match Node's synchronous module system.
### normalize: function (name, normalize)
**normalize** is called to normalize the name used to identify a resource. Some resources could use relative paths, and need to be normalized to the full path. normalize is called with the following arguments:
* **name**: String. The resource name to normalize.
* **normalize**: Function. A function that can be called to normalize a regular module name.
An example: suppose there is an **index!** plugin that will load a module name given an index. This is a contrived example, just to illustrate the concept. A module may reference an index! resource like so:
```
define(['index!2?./a:./b:./c'], function (indexResource) {
//indexResource will be the module that corresponds to './c'.
});
```
In this case, the normalized names the './a', './b', and './c' will be determined relative to the module asking for this resource. Since RequireJS does not know how to inspect the 'index!2?./a:./b:./c' to normalize the names for './a', './b', and './c', it needs to ask the plugin. This is the purpose of the normalize call.
By properly normalizing the resource name, it allows the loader to cache the value effectively, and to properly build an optimized build layer in the optimizer.
The **index!** plugin could be written like so:
```
(function () {
//Helper function to parse the 'N?value:value:value'
//format used in the resource name.
function parse(name) {
var parts = name.split('?'),
index = parseInt(parts[0], 10),
choices = parts[1].split(':'),
choice = choices[index];
return {
index: index,
choices: choices,
choice: choice
};
}
//Main module definition.
define({
normalize: function (name, normalize) {
var parsed = parse(name),
choices = parsed.choices;
//Normalize each path choice.
for (i = 0; i < choices.length; i++) {
//Call the normalize() method passed in
//to this function to normalize each
//module name.
choices[i] = normalize(choices[i]);
}
return parsed.index + '?' + choices.join(':');
},
load: function (name, req, onload, config) {
req([parse(name).choice], function (value) {
onload(value);
});
}
});
}());
```
You do not need to implement normalize if the resource name is just a regular module name. For instance, the text! plugin does not implement normalize because the dependency names look like 'text!./some/path.html'.
If a plugin does not implement normalize, then the loader will try to normalize the resource name using the normal module name rules.
### write: function (pluginName, moduleName, write)
**write** is only used by the optimizer, and it only needs to be implemented if the plugin can output something that would belong in an optimized layer. It is called with the following arguments:
* **pluginName**: String. The **normalized** name for the plugin. Most plugins will not be authored with a name (they will be anonymous plugins) so it is useful to know the normalized name for the plugin module for use in the optimized file.
* **moduleName**: String. The **normalized** resource name.
* **write**: Function. A function to be called with a string of output to write to the optimized file. This function also contains a property function, **write.asModule(moduleName, text)**. asModule can be used to write out a module that may have an anonymous define call in there that needs name insertion or/and contains implicit require("") dependencies that need to be pulled out for the optimized file. asModule is useful for text transform plugins, like a CoffeeScript plugin.
The text! plugin implements write, to write out a string value for the text file that it loaded. A snippet from that file:
```
write: function (pluginName, moduleName, write) {
//The text plugin keeps a map of strings it fetched
//during the build process, in a buildMap object.
if (moduleName in buildMap) {
//jsEscape is an internal method for the text plugin
//that is used to make the string safe
//for embedding in a JS string.
var text = jsEscape(buildMap[moduleName]);
write("define('" + pluginName + "!" + moduleName +
"', function () { return '" + text + "';});\n");
}
}
```
### onLayerEnd: function (write, data)
**onLayerEnd** is only used by the optimizer, and is only supported in 2.1.0 or later of the optimizer. It is called after the modules for the layer have been written to the layer. It is useful to use if you need some code that should go at the end of the layer, or if the plugin needs to reset some internal state.
One example: a plugin that needs to write out some utility functions at the beginning of a layer, as part of the first [write](#apiwrite) call, and the plugin needs to know when to reset the internal state to know when to write out the utilities for the next layer. If the plugin implements onLayerEnd, it can get notified when to reset its internal state.
onLayerEnd is called with the following arguments:
* **write**: Function. A function to be called with a string of output to write to the optimized layer. **Modules should not be written out** in this call. They will not be normalized correctly for coexistence with other define() calls already in the file. It is useful only for writing out non-define() code.
* **data**: Object. Information about the layer. Only has two properties:
+ **name**: the module name of the layer. May be undefined.
+ **path**: the file path of the layer. May be undefined, particularly if the output is just to a string that is consumed by another script.
### writeFile: function (pluginName, name, parentRequire, write)
**writeFile** is only used by the optimizer, and it only needs to be implemented if the plugin needs to write out an alternate version of a dependency that is handled by the plugin. It is a bit expensive to scan all modules in a project to look for all plugin dependencies, so this writeFile method will only be called if **optimizeAllPluginResources: true** is in the build profile for the RequireJS optimizer. writeFile is called with the following arguments:
* **pluginName**: String. The **normalized** name for the plugin. Most plugins will not be authored with a name (they will be anonymous plugins) so it is useful to know the normalized name for the plugin module for use in the optimized file.
* **name**: String. The **normalized** resource name.
* **parentRequire**: Function. A local "require" function. The main use of this in writeFile is for calling parentRequire.toUrl() to generate file paths that are inside the build directory.
* **write**: Function. A function to be called with two arguments:
+ **fileName**: String. The name of the file to write. You can use parentRequire.toUrl() with a relative path to generate a file name that will be inside the build output directory.
+ **text**: String. The contents of the file. Must be UTF-8 encoded. This function also contains a property function, **write.asModule(moduleName, fileName, text)**. asModule can be used to write out a module that may have an anonymous define call in there that needs name insertion or/and contains implicit require("") dependencies that need to be pulled out for the optimized file.
See the [text! plugin](https://github.com/requirejs/text) for an example of writeFile.
### pluginBuilder
**pluginBuilder** can be a string that points to another module to use instead of the current plugin when the plugin is used as part of an optimizer build.
A plugin could have very specific logic that depends on a certain environment, like the browser. However, when run inside the optimizer, the environment is very different, and the plugin may have a **write** plugin API implementation that it does not want to deliver as part of the normal plugin that is loaded in the browser. In those cases, specifying a pluginBuilder is useful.
Some notes about using a pluginBuilder:
* Do not use named modules for the plugin or the pluginBuilder. The pluginBuilder text contents are used instead of the contents of the plugin file, but that will only work if the files do not call define() with a name.
* Plugins and pluginBuilders that run as part of the build process have a very limited environment. The optimizer runs in a few different JS environments. Be careful of the environment assumptions if you want the plugin to run as part of the optimizer.
| programming_docs |
requirejs Why Web Modules? Why Web Modules?
================
* [The Problem](#1)
* [Solution](#2)
* [Script loading APIs](#3)
* [Async vs Sync](#4)
* [Script loading: XHR](#5)
* [Script loading: Web Workers](#6)
* [Script loading: document.write()](#7)
* [Script loading: head.appendchild(script)](#8)
* [Function wrapping](#9)
This page discusses why modules on the web are useful and the mechanisms that can be used on the web today to enable them. There is a separate page that talks about [the design forces](whyamd) for the particular function wrapped format used by RequireJS.
The Problem
------------
* Web sites are turning into Web apps
* Code complexity grows as the site gets bigger
* Assembly gets harder
* Developer wants discrete JS files/modules
* Deployment wants optimized code in just one or a few HTTP calls
Solution
--------
Front-end developers need a solution with:
* Some sort of #include/import/require
* Ability to load nested dependencies
* Ease of use for developer but then backed by an optimization tool that helps deployment
Script Loading APIs
-------------------
First thing to sort out is a script loading API. Here are some candidates:
* Dojo: dojo.require("some.module")
* LABjs: $LAB.script("some/module.js")
* CommonJS: require("some/module")
All of them map to loading some/path/some/module.js. Ideally we could choose the CommonJS syntax, since it is likely to get more common over time, and we want to reuse code.
We also want some sort of syntax that will allow loading plain JavaScript files that exist today -- a developer should not have to rewrite all of their JavaScript to get the benefits of script loading.
However, we need something that works well in the browser. The CommonJS require() is a synchronous call, it is expected to return the module immediately. This does not work well in the browser.
Async vs Sync
-------------
This example should illustrate the basic problem for the browser. Suppose we have an Employee object and we want a Manager object to derive from the Employee object. [Taking this example](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Details_of_the_Object_Model#Creating_the_hierarchy), we might code it up like this using our script loading API:
```
var Employee = require("types/Employee");
function Manager () {
this.reports = [];
}
//Error if require call is async
Manager.prototype = new Employee();
```
As the comment indicates above, if require() is async, this code will not work. However, loading scripts synchronously in the browser kills performance. So, what to do?
Script Loading: XHR
-------------------
It is tempting to use XMLHttpRequest (XHR) to load the scripts. If XHR is used, then we can massage the text above -- we can do a regexp to find require() calls, make sure we load those scripts, then use eval() or script elements that have their body text set to the text of the script loaded via XHR.
Using eval() to evaluate the modules is bad:
* Developers have been taught that eval() is bad.
* Some environments do not allow eval().
* It is harder to debug. Firebug and WebKit's inspector have an //@ sourceURL= convention, which helps give a name to evaled text, but this support is not universal across browsers.
* eval context is different across browsers. You might be able to use execScript in IE to help this, but it means more moving parts.
Using script tags with body text set to file text is bad:
* While debugging, the line number you get for an error does not map to the original source file.
XHR also has issues with cross-domain requests. Some browsers now have cross-domain XHR support, but it is not universal, and IE decided to create a different API object for cross-domain calls, XDomainRequest. More moving parts and more things to get wrong. In particular, you need to be sure to not send any non-standard HTTP headers or there may be another "preflight" request done to make sure the cross-domain access is allowed.
Dojo has used an XHR-based loader with eval() and, while it works, it has been a source of frustration for developers. Dojo has an xdomain loader but it requires the modules to be modified via a build step to use a function wrapper, so that script src="" tags can be used to load the modules. There are many edge cases and moving parts that create a tax on the developer.
If we are creating a new script loader, we can do better.
Script Loading: Web Workers
---------------------------
Web Workers might be another way to load scripts, but:
* It does not have strong cross browser support
* It is a message-passing API, and the scripts likely want to interact with the DOM, so it means just using the worker to fetch the script text, but pass the text back to the main window then use eval/script with text body to execute the script. This has all of the problems as XHR mentioned above.
Script Loading: document.write()
--------------------------------
document.write() can be used to load scripts -- it can load scripts from other domains and it maps to how browsers normally consume scripts, so it allows for easy debugging.
However, in the [Async vs Sync example](#4) we cannot just execute that script directly. Ideally we could know the require() dependencies before we execute the script, and make sure those dependencies are loaded first. But we do not have access to the script before it is executed.
Also, document.write() does not work after page load. A great way to get perceived performance for your site is loading code on demand, as the user needs it for their next action.
Finally, scripts loaded via document.write() will block page rendering. When looking at reaching the very best performance for your site, this is undesirable.
Script Loading: head.appendChild(script)
----------------------------------------
We can create scripts on demand and add them to the head:
```
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
script.src = url;
head.appendChild(script);
```
There is a bit more involved than just the above snippet, but that is the basic idea. This approach has the advantage over document.write in that it will not block page rendering and it works after page load.
However, it still has the [Async vs Sync example](#4) problem: ideally we could know the require() dependencies before we execute the script, and make sure those dependencies are loaded first.
Function Wrapping
-----------------
So we need to know the dependencies and make sure we load them before executing our script. The best way to do that is construct our module loading API with function wrappers. Like so:
```
define(
//The name of this module
"types/Manager",
//The array of dependencies
["types/Employee"],
//The function to execute when all dependencies have loaded. The
//arguments to this function are the array of dependencies mentioned
//above.
function (Employee) {
function Manager () {
this.reports = [];
}
//This will now work
Manager.prototype = new Employee();
//return the Manager constructor function so it can be used by
//other modules.
return Manager;
}
);
```
And this is the syntax used by RequireJS. There is also a simplified syntax if you just want to load some plain JavaScript files that do not define modules:
```
require(["some/script.js"], function() {
//This function is called after some/script.js has loaded.
});
```
This type of syntax was chosen because it is terse and allows the loader to use head.appendChild(script) type of loading.
It differs from the normal CommonJS syntax out of necessity to work well in the browser. There have been suggestions that the normal CommonJS syntax could be used with head.appendChild(script) type of loading if a server process transforms the modules to a transport format that has a function wrapper.
I believe it is important to not force the use of a runtime server process to transform code:
* It makes debugging weird, line numbers will be off vs. the source file since the server is injecting a function wrapper.
* It requires more gear. Front-end development should be possible with static files.
More details on the design forces and use cases for this function wrapping format, called Asynchronous Module Definition (AMD), can be found on the [Why AMD?](whyamd) page.
requirejs RequireJS Optimizer RequireJS Optimizer
===================
* [Requirements](#requirements)
* [Download](#download)
* [Example setup](#setup)
* [Basics](#basics)
* [Optimizing one JavaScript file](#onejs)
* [Shallow exclusions for fast development](#shallow)
* [empty: paths for network/CDN resources](#empty)
* [Optimizing one CSS file](#onecss)
* [Optimizing a whole project](#wholeproject)
* [Optimizing a multi-page project](#wholemultipage)
* [Turbo options](#turbo)
* [Integration with has.js](#hasjs)
* [Source maps](#sourcemaps)
* [All configuration options](#options)
* [Deployment techniques](#deployment)
* [Common pitfalls](#pitfalls)
RequireJS has an optimization tool that does the following
* Combines related scripts together into build layers and minifies them via [UglifyJS](https://github.com/mishoo/UglifyJS) (the default) or [Closure Compiler](https://developers.google.com/closure/compiler/) (an option when using Java).
* Optimizes CSS by inlining CSS files referenced by @import and removing comments.
The optimizer is part of the [r.js adapter for Node and Nashorn](https://github.com/requirejs/r.js), and it is designed to be run as part of a build or packaging step after you are done with development and are ready to deploy the code for your users.
The optimizer will only combine modules that are specified in arrays of string literals that are passed to top-level require and define calls, or the require('name') string literal calls in a [simplified CommonJS wrapping](whyamd#sugar). So, it will not find modules that are loaded via a variable name:
```
var mods = someCondition ? ['a', 'b'] : ['c', 'd'];
require(mods);
```
but 'a' and 'b' will be included if specified like so:
```
require(['a', 'b']);
```
or:
```
define(['a', 'b'], function (a, b) {});
```
This behavior allows dynamic loading of modules even after optimization. You can always explicitly add modules that are not found via the optimizer's static analysis by using the **include** option.
Requirements
-------------
The optimizer can be run using Node, Java with Rhino or Nashorn, or in the browser. The requirements for each option:
* **Node:** (preferred) [Node](http://nodejs.org) 0.4.0 or later.
* **Java:** [Java 1.6](http://java.com/) or later.
* **Browser:** as of 2.1.2, the optimizer can run in a web browser that has [array extras](http://dev.opera.com/articles/view/javascript-array-extras-in-detail/). While the optimizer options are the same as shown below, it is called via JavaScript instead of command line options. It is also only good for generating optimized single files, not a directory optimization. See [the browser example](https://github.com/requirejs/r.js/blob/master/tests/browser/r.html). This option is really only useful for providing web-based custom builds of your library.
For command line use, Node is the preferred execution environment. The optimizer runs **much faster** with Node.
All the example commands in this page assume Node usage, and running on a Linux/OS X command line. See the [r.js README](https://github.com/requirejs/r.js) for how to run it in Java.
Download
--------
1) You can download the tool on [the download page](http://requirejs.org/docs/download.html#rjs).
2) If you are using Node with NPM, you can install r.js globally as part of the "requirejs" package in NPM:
```
> npm install -g requirejs
> r.js -o app.build.js
```
If on Windows, you may need to type `r.js.cmd` instead of `r.js`. Or, you can use [DOSKEY](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/doskey.mspx?mfr=true):
```
DOSKEY r.js=r.js.cmd $*
```
If you want to install requirejs locally in a project as an npm package, instead of globally:
```
> npm install requirejs
```
With this local install, you can run the optimizer by running the `r.js` or `r.js.cmd` file found in the project's `node_modules/.bin` directory.
With the local install, you can also [use the optimizer via a function call](node#optimizer) inside a node program.
The rest of this page assumes that r.js is just downloaded manually from the download page. It is normally the clearest, most portable way to use the optimizer.
Example setup
-------------
The examples in this page will assume you downloaded and saved r.js in a directory that is a sibling to your project directory. The optimizer that is part of r.js can live anywhere you want, but you will likely need to adjust the paths accordingly in these examples.
Example setup:
* appdirectory
+ main.html
+ css
- common.css
- main.css
+ scripts
- require.js
- main.js
- one.js
- two.js
- three.js
* r.js (The r.js optimizer from [download page](http://requirejs.org/docs/download.html#rjs))
main.html has script tags for require.js and loads main.js via a require call, like so:
```
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>My App</h1>
</body>
</html>
```
main.js loads one.js, two.js and three.js via a require call:
```
require(["one", "two", "three"], function (one, two, three) {
});
```
main.css has content like the following:
```
@import url("common.css");
.app {
background: transparent url(../../img/app.png);
}
```
Basics
-------
**Command line arguments are interchangeable with a build profile properties**
You can either specify options on the command line:
```
node r.js -o baseUrl=. paths.jquery=some/other/jquery name=main out=main-built.js
```
or in a build profile. In a **build.js**, the same command line arguments can be specified like so:
```
({
baseUrl: ".",
paths: {
jquery: "some/other/jquery"
},
name: "main",
out: "main-built.js"
})
```
then just pass the build profile's file name to the optimizer:
```
node r.js -o build.js
```
Command line arguments take precedence over build profile settings, and you can mix them together:
```
node r.js -o build.js optimize=none
```
There is a **limitation** on the command line argument syntax. Dots are viewed as object property separators, to allow something like `paths.jquery=lib/jquery` to be transformed to the following in the optimizer:
```
paths: {
jquery: 'lib/jquery'
}
```
but this means you cannot set the value for a paths property of "core/jquery.tabs" to a value. This would not work: `paths.core/jquery.tabs=empty:`, since it would result in this incorrect structure:
```
paths: {
'core/jquery': {
tabs: 'empty:'
}
}
```
If you need to set a path like the "core/jquery.tabs" one, use a build.js file with the build options specified as a JavaScript object instead of using command line arguments.
For a list of all options, see [all configuration options](#options).
**Relative path resolution rules:**:
In general, if it is a path, it is relative to the build.js file used to hold the build options, or if just using command line arguments, relative to the current working directory. Example of properties that are file paths: **appDir**, **dir**, **mainConfigFile**, **out**, **wrap.startFile**, **wrap.endFile**.
For **baseUrl**, it is relative to **appDir**. If no appDir, then baseUrl is relative to the build.js file, or if just using command line arguments, the current working directory.
For **paths** and **packages**, they are relative to **baseUrl**, just as they are for require.js.
For properties that are module IDs, they should be module IDs, and not file paths. Examples are **name**, **include**, **exclude**, **excludeShallow**, **deps**.
**Config settings in your main JS module that is loaded in the browser at runtime **are not read by default** by the optimizer**
This is because the config settings for a build can be very different, with multiple optimization targets. So a separate set of config options need to be specified for the optimizer.
In version 1.0.5+ of the optimizer, the **[mainConfigFile](https://github.com/requirejs/r.js/blob/master/build/example.build.js#L27)** option can be used to specify the location of the runtime config. If specified with the path to your main JS file, the first `requirejs({}), requirejs.config({}), require({}), or require.config({})` found in that file will be parsed out and used as part of the configuration options passed to the optimizer:
```
mainConfigFile: 'path/to/main.js'
```
The precedence for config: command line, build profile, mainConfigFile. In other words, the mainConfigFile configuration has the lowest priority.
Optimizing one JavaScript file
-------------------------------
Use the above example setup, if you just wanted to optimize main.js, you could use this command, from inside the **appdirectory/scripts** directory:
```
node ../../r.js -o name=main out=main-built.js baseUrl=.
```
This will create a file called **appdirectory/scripts/main-built.js** that will include the contents of main.js, one.js, two.js and three.js.
Normally you should **not** save optimized files with your pristine project source. Normally you would save them to a copy of your project, but to make this example easier it is saved with the source. Change the **out=** option to any directory you like, that has a copy of your source. Then, you can change the main-built.js file name to just main.js so the HTML page will load the optimized version of the file.
If you want to include require.js with the main.js source, you can use this kind of command:
```
node ../../r.js -o baseUrl=. paths.requireLib=../../require name=main include=requireLib out=main-built.js
```
Since "require" is a reserved dependency name, you create a "requireLib" dependency and map it to the require.js file.
Once that optimization is done, you can change the script tag to reference "main-built.js" instead of "require.js", and your optimized project will only need to make one script request.
If you want to wrap your built file so it can be used in pages that do not have an AMD loader like RequireJS, see the [Optimization FAQ](http://requirejs.org/docs/faq-optimization.html).
Shallow exclusions for fast development
---------------------------------------
You can use the [one JavaScript file optimization](#onejs) approach to make your development experience faster. By optimizing all the modules in your project into one file, except the one you are currently developing, you can reload your project quickly in the browser, but still give you the option of fine grained debugging in a module.
You can do this by using the **excludeShallow** option. Using the [example setup](#example) above, assume you are currently building out or debugging two.js. You could use this optimization command:
```
node ../../r.js -o name=main excludeShallow=two out=main-built.js baseUrl=.
```
If you do not want the main-build.js file minified, pass **optimize=none** in the command above.
Then configure the HTML page to load the main-built.js file instead of main.js by configuring the path used for "main" to be "main-built":
```
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="scripts/require.js"></script>
<script>
require.config({
paths: {
//Comment out this line to go back to loading
//the non-optimized main.js source file.
"main": "main-built"
}
});
require(["main"]);
</script>
</head>
<body>
<h1>My App</h1>
</body>
</html>
```
Now, when this page is loaded, the require() for "main" will load the main-built.js file. Since excludeShallow told it just to exclude two.js, two.js will still be loaded as a separate file, allowing you to see it as a separate file in the browser's debugger, so you can set breakpoints and better track its individual changes.
empty: paths for network/CDN resources
--------------------------------------
You may have a script you want to load from a [Content Delivery Network (CDN)](http://en.wikipedia.org/wiki/Content_delivery_network) or any other server on a different domain.
The optimizer cannot load network resources, so if you want it included in the build, be sure to create a [paths config](api#config-paths) to map the file to a module name. Then, for running the optimizer, download the CDN script and pass a paths config to the optimizer that maps the module name to the local file path.
However, it is more likely that you do not want to include that resource in the build. If the script does not have any dependencies, or you do not want to include its dependencies or will be including them in another way, then you can use the special **'empty:' scheme** in the paths config to just skip the file when doing an optimization.
In your main.js file, create a paths config that gives the script a module name. This can be done even if the script does not define a module via a call to define(). paths config are just used to map short module/script IDs to an URL. This allows you to use a different paths config for the optimization. In main.js:
```
requirejs.config({
paths: {
'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min'
}
});
require(['jquery'], function ($) {
});
```
Then, when running the optimizer, use 'empty:' for the paths config:
```
node ../../r.js -o name=main out=main-built.js baseUrl=. paths.jquery=empty:
```
Or, in a [build profile](#wholeproject):
```
({
baseUrl: ".",
name: "main",
out: "main-built.js",
paths: {
jquery: "empty:"
}
})
```
Optimizing one CSS file
-----------------------
Use the above example setup, if you just wanted to optimize main.css, you could use this command, from inside the **appdirectory/css** directory:
```
node ../../r.js -o cssIn=main.css out=main-built.css
```
This will create a file called **appdirectory/css/main-build.css** that will include the contents of main.css, have the url() paths properly adjusted, and have comments removed.
See the notes for the [Optimizing one JavaScript file](#onejs) about avoiding saving optimized files in your pristine source tree. It is only done here to make the example simpler.
Note: The url() path fixing will always fix the paths relative to the **cssIn** build option path, not the **out** build option. Optimizing a whole project
--------------------------
The optimizer can take care of optimizing all the CSS and JS files in your project by using a build profile.
Create a build profile, call it app.build.js, and put it in the **scripts** directory. The app.build.js file can live anywhere, but just be sure to adjust the paths accordingly in the example below -- all paths will be relative to where the app.build.js is located. Example app.build.js:
```
({
appDir: "../",
baseUrl: "scripts",
dir: "../../appdirectory-build",
modules: [
{
name: "main"
}
]
})
```
This build profile tells RequireJS to copy all of **appdirectory** to a sibling directory called **appdirectory-build** and apply all the optimizations in the **appdirectory-build** directory. It is strongly suggested you use a different output directory than the source directory -- otherwise bad things will likely happen as the optimizer overwrites your source.
RequireJS will use **baseUrl** to resolve the paths for any module names. The **baseUrl** should be relative to **appDir**.
In the **modules** array, specify the module names that you want to optimize, in the example, "main". "main" will be mapped to **appdirectory/scripts/main.js** in your project. The build system will then trace the dependencies for main.js and inject them into the **appdirectory-build/scripts/main.js** file.
It will also optimize any CSS files it finds inside **appdirectory-build**.
To run the build, run this command from inside the **appdirectory/scripts** directory:
```
node ../../r.js -o app.build.js
```
Once the build is done, you can use **appdirectory-build** as your optimized project, ready for deployment.
Optimizing a multi-page project
-------------------------------
[requirejs/example-multipage](https://github.com/requirejs/example-multipage) is an example of a project that has multiple pages, but shares a common configuration and a common optimized build layer.
Turbo options
-------------
The default for the optimizer is to do the safest, most robust set of actions that avoid surprises after a build. However, depending on your project setup, you may want to turn off some of these features to get faster builds:
* The biggest time drain is minification. If you are just doing builds as part of a dev workflow, then set **optimize** to `"none"`.
* If doing a whole project optimization, but only want to minify the build layers specified in **modules** options and not the rest of the JS files in the build output directory, you can set **skipDirOptimize** to `true`.
* Normally each run of a whole project optimization will delete the output build directory specified by **dir** for cleanliness. Some build options, like **onBuildWrite**, will modify the output directory in a way that is hazardous to do twice over the same files. However, if you are doing simple builds with no extra file transforms besides build layer minification, then you can set **keepBuildDir** to `true` to keep the build directory between runs. Then, only files that have changed between build runs will be copied.
As of version 2.1.2, there are some speed shortcuts the optimizer will take by default if **optimize** is set to `"none"`. However, if you are using `"none"` for **optimize** and you are planning to minify the built files after the optimizer runs, then you should turn set **normalizeDirDefines** to `"all"` so that define() calls are normalized correctly to withstand minification. If you are doing minification via the **optimize** option, then you do not need to worry about setting this option.
Integration with has.js
-----------------------
[has.js](https://github.com/phiggins42/has.js) is a great tool to that adds easy feature detection for your project. There is some optimizer support for optimizing code paths for has.js tests.
If your code uses tests like the following:
```
if (has("someThing")) {
//use native someThing
} else {
//do some workaround
}
```
You can define a **has** object in the build config with true or false values for some has() tests, and the optimizer will replace the has() test with the true or false value.
If your build profile looked like so:
```
({
baseUrl: ".",
name: "hasTestModule",
out: "builds/hasTestModule.js",
has: {
someThing: true
}
})
```
Then the optimizer will transform the above code sample to:
```
if (true) {
//use native someThing
} else {
//do some workaround
}
```
Then, if you use the default optimize setting of "uglify" in r.js 0.26.0 or later, or if the **optimize** setting is set to "closure" (when [run under Java](https://github.com/requirejs/r.js)), the minifier will optimize out the dead code branch! So you can do custom builds of your code that are optimized for a set of has() tests.
Source maps
-----------
Version 2.1.6 and higher have experimental support for [source maps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/). It works for mapping minified, bundled code to unminified, separate modules and only when **optimize** is set to `"uglify2"`. optimize set to `"closure"` allows only mapping minified, bundled code to unminified bundled code (closure only available when running under Java with Rhino). The unminified files will show up in the developer tools with a ".src.js" file extension.
To enable the source map generation, set **generateSourceMaps** to `true`. Since the minifier needs to have full control over the minified file to generate the source map, the **preserveLicenseComments** should be explicitly set to `false`. [There is is a way to get some license comments in the minified source though](errors#sourcemapcomments).
The optimizer has supported [sourceURL](https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/) (by setting **useSourceUrl** to `true`), for debugging combined modules as individual files. However, that only works with non-minified code. Source maps translate a minified file to a non-minified version. It does not make sense to use useSourceUrl with generateSourceMaps since useSourceUrl needs the source values as strings, which prohibits the useful minification done in combination with generateSourceMaps.
All configuration options
-------------------------
There is an [example.build.js](https://github.com/requirejs/r.js/blob/master/build/example.build.js) file in the requirejs/build directory that details all of the allowed optimizer configuration options.
Deployment techniques
---------------------
The r.js optimizer is designed to offer some primitives that can be used for different deployment scenarios by adding other code on top of it. See the [deployment techniques wiki page](https://github.com/requirejs/r.js/wiki/Deployment-Techniques) for ideas on how to use the optimizer in that fashion.
Common pitfalls
---------------
If you are having trouble with the examples below, here are some common pitfalls that might be the source of the problem:
**Do not specify the output directory to within the source area for your JavaScript**
For instance, if your baseUrl is 'js' and your build output goes into 'js/build', there will likely be problems with extra, nested files generated on each optimization run. This guidance is only for optimizations that are not single file optimizations.
**Avoid optimization names that are outside the baseUrl**
For instance, if your baseUrl is 'js', and your optimization targets:
```
name: '../main'
```
the optimization could overwrite or place files outside the output directory. For those cases, create a **paths** config to map that file to a local name, like:
```
paths: {
main: '../main'
}
```
then use name:
```
name: 'main'
```
for the optimization target.
**Note the build limitations of shim config.** In particular, you cannot load dependencies for shimmed libraries from a CDN. See the [shim config section](api#config-shim) for more information.
| programming_docs |
requirejs RequireJS in Node RequireJS in Node
=================
* [Doesn't Node already have a module loader?](#1)
* [Can I use server modules written in the CommonJS module format?](#2)
* [How do I use it?](#3)
Doesn't Node already have a module loader?
-------------------------------------------
Yes [Node](http://nodejs.org) does. That loader uses the CommonJS module format. The CommonJS module format is [non-optimal for the browser](why), and I do not agree with [some of the trade-offs made in the CommonJS module format](http://tagneto.blogspot.com/2010/03/commonjs-module-trade-offs.html). By using RequireJS on the server, you can use one format for all your modules, whether they are running server side or in the browser. That way you can preserve the speed benefits and easy debugging you get with RequireJS in the browser, and not have to worry about extra translation costs for moving between two formats.
If you want to use define() for your modules but still run them in Node without needing to run RequireJS on the server, see [the section below](#nodeModules) about using [amdefine](https://github.com/jrburke/amdefine).
Can I use Node modules already written in the CommonJS module format?
----------------------------------------------------------------------
Yes! The Node adapter for RequireJS, called r.js, will use Node's implementation of require and Node's search paths if the module is not found with the configuration used by RequireJS, so you can continue to use your existing Node-based modules without having to do changes to them.
RequireJS will use its [Configuration Options](api#config) first to find modules. If RequireJS cannot find the module with its configuration, it is assumed to be a module that uses Node's type of modules and configuration. So, only configure module locations with RequireJS if they use the RequireJS API. For modules that expect Node's APIs and configuration/paths, just install them with a Node package manager, like [npm](http://npmjs.org/), and do not configure their locations with RequireJS.
**Best practice**: Use npm to install Node-only packages/modules into the projects **node\_modules** directory, but do not configure RequireJS to look inside the node\_modules directory. Also avoid using relative module IDs to reference modules that are Node-only modules. So, **do not** do something like **require("./node\_modules/foo/foo")**.
Other notes:
* RequireJS in Node can only load modules that are on the local disk -- fetching modules across http, for instance, is not supported at this time.
* RequireJS config options like map, packages, paths are only applied if RequireJS loads the module. If RequireJS needs to ask the node module system, the original ID is passed to Node. If you need a node module to work with a map config, inline define() calls work, as shown in [this email list thread.](https://groups.google.com/forum/#!msg/requirejs/ur_UQLr04rc/sSpM8y87VNMJ)
How do I use it?
-----------------
There are two ways to get the Node adapter:
### npm
Use [npm](http://npmjs.org) to install it:
```
npm install requirejs
```
This option will install the latest release.
### Download r.js
If you prefer to not use npm, you can get r.js directly:
* Download r.js from the [the download page](http://requirejs.org/docs/download.html#rjs) and place it in your project.
* Get the source from the [r.js repo](https://github.com/requirejs/r.js) and either generate the r.js via "node dist.js", or grab a snapshot from the **dist** directory.
### Usage
These instructions assume an npm installation of 'requirejs'. If you are using the r.js file directly, replace require('requirejs') with require('./path/to/r.js'). Basic usage is:
* require('requirejs')
* Pass the main js file's "require" function in the configuration to requirejs.
Example:
```
var requirejs = require('requirejs');
requirejs.config({
//Pass the top-level main.js/index.js require
//function to requirejs so that node modules
//are loaded relative to the top-level JS file.
nodeRequire: require
});
requirejs(['foo', 'bar'],
function (foo, bar) {
//foo and bar are loaded according to requirejs
//config, but if not found, then node's require
//is used to load the module.
});
```
Be sure to read the [notes in section 2](#2) about configuring RequireJS so that it can load node-only modules installed via npm.
To see a more complete example that loads a module via RequireJS but uses Node-native modules for other things, see the [embedded test](https://github.com/requirejs/r.js/tree/master/tests/node/embedded) in the r.js repo.
**Note:** `requirejs([], function() {})` will call the function callback asynchronously in RequireJS 2.1+ (for earlier versions it was synchronously called). However, when running in Node, module loading will be loaded using sync IO calls, and loader plugins should resolve calls to their load method synchronously. This allows sync uses of the requirejs module in node to work via requirejs('stringValue') calls:
```
//Retrieves the module value for 'a' synchronously
var a = requirejs('a')
```
### Building node modules with AMD or RequireJS
If you want to code a module so that it works with RequireJS and in Node, without requiring users of your library in Node to use RequireJS, then you can use the [amdefine](https://github.com/jrburke/amdefine) package to do this:
```
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
define(function(require) {
var dep = require('dependency');
//The value returned from the function is
//used as the module export visible to Node.
return function () {};
});
```
The RequireJS optimizer, as of version 1.0.3, will strip out the use of 'amdefine' above, so it is safe to use this module for your web-based projects too. Just be sure to use **the exact 'amdefine' if() test and contents as shown above**. Differences in spaces/line breaks are allowed. See the [amdefine project](https://github.com/jrburke/amdefine) for more information.
If you want to use RequireJS directly to code your module, and then export a module value to node so that it can be used in other Node programs without requiring that app to use RequireJS, you can use the approach listed in the next example.
It is best to set the baseUrl specifically to the directory containing the module, so that it works properly when nested inside a node\_modules heirarchy. Use the synchronous `requirejs('moduleId')` to fetch the module using the config and rules in requirejs, then use Node's module.exports to export your module value:
```
var requirejs = require('requirejs');
requirejs.config({
//Use node's special variable __dirname to
//get the directory containing this file.
//Useful if building a library that will
//be used in node but does not require the
//use of node outside
baseUrl: __dirname,
//Pass the top-level main.js/index.js require
//function to requirejs so that node modules
//are loaded relative to the top-level JS file.
nodeRequire: require
});
//foo and bar are loaded according to requirejs
//config, and if found, assumed to be an AMD module.
//If they are not found via the requirejs config,
//then node's require is used to load the module,
//and if found, the module is assumed to be a
//node-formatted module. Note: this synchronous
//style of loading a module only works in Node.
var foo = requirejs('foo');
var bar = requirejs('bar');
//Now export a value visible to Node.
module.exports = function () {};
```
### Using the optimizer as a node module
The node module also exposes the RequireJS Optimizer as an **optimize** method for using the [RequireJS optimizer](optimization) via a function call instead of a command line tool:
```
var requirejs = require('requirejs');
var config = {
baseUrl: '../appDir/scripts',
name: 'main',
out: '../build/main-built.js'
};
requirejs.optimize(config, function (buildResponse) {
//buildResponse is just a text output of the modules
//included. Load the built file for the contents.
//Use config.out to get the optimized file contents.
var contents = fs.readFileSync(config.out, 'utf8');
}, function(err) {
//optimization err callback
});
```
This allows you to build other optimization workflows, like [a web builder](https://github.com/requirejs/r.js/tree/master/build/tests/http) that can be used if you prefer to always develop with the "one script file included before the </body> tag" approach. The optimizer running in Node is fairly fast, but for larger projects that do not want to regenerate the build for every browser request, but just if you modify a script that is part of the build. You could use Node's fs.watchFile() to watch files and then trigger the build when a file changes.
### Feedback
If you find you have a problem, and want to report it, use the [r.js GitHub Issues page](http://github.com/requirejs/r.js/issues).
requirejs RequireJS API RequireJS API
=============
* [Usage](#usage)
+ [Load JavaScript Files](#jsfiles)
+ [data-main Entry Point](#data-main)
+ [Define a Module](#define)
- [Simple Name/Value Pairs](#defsimple)
- [Definition Functions](#deffunc)
- [Definition Functions with Dependencies](#defdep)
- [Define a Module as a Function](#funcmodule)
- [Define a Module with Simplified CommonJS Wrapper](#cjsmodule)
- [Define a Module with a name](#modulename)
- [Other Module Notes](#modulenotes)
- [Circular Dependencies](#circular)
- [Specify a JSONP Service Dependency](#jsonp)
- [Undefining a Module](#undef)
* [Mechanics](#mechanics)
* [Configuration Options](#config)
* [Advanced Usage](#advanced)
+ [Loading Modules from Packages](#packages)
+ [Multiversion Support](#multiversion)
+ [Loading Code After Page Load](#afterload)
+ [Web Worker Support](#webworker)
+ [Rhino Support](#rhino)
+ [Nashorn Support](#nashorn)
+ [Handling Errors](#errors)
* [Loader Plugins](#plugins)
+ [Specify a Text File Dependency](#text)
+ [Page Load Event Support/DOM Ready](#pageload)
+ [Define an I18N Bundle](#i18n)
Usage
------
### Load JavaScript Files
RequireJS takes a different approach to script loading than traditional <script> tags. While it can also run fast and optimize well, the primary goal is to encourage modular code. As part of that, it encourages using **module IDs** instead of URLs for script tags.
RequireJS loads all code relative to a [baseUrl](#config-baseUrl). The baseUrl is normally set to the same directory as the script used in a data-main attribute for the top level script to load for a page. The [data-main attribute](#data-main) is a special attribute that require.js will check to start script loading. This example will end up with a baseUrl of **scripts**:
```
<!--This sets the baseUrl to the "scripts" directory, and
loads a script that will have a module ID of 'main'-->
<script data-main="scripts/main.js" src="scripts/require.js"></script>
```
Or, baseUrl can be set manually via the [RequireJS config](#config). If there is no explicit config and data-main is not used, then the default baseUrl is the directory that contains the HTML page running RequireJS.
RequireJS also assumes by default that all dependencies are scripts, so it does not expect to see a trailing ".js" suffix on module IDs. RequireJS will automatically add it when translating the module ID to a path. With the [paths config](#config-paths), you can set up locations of a group of scripts. All of these capabilities allow you to use smaller strings for scripts as compared to traditional <script> tags.
There may be times when you do want to reference a script directly and not conform to the "baseUrl + paths" rules for finding it. If a module ID has one of the following characteristics, the ID will not be passed through the "baseUrl + paths" configuration, and just be treated like a regular URL that is relative to the document:
* Ends in ".js".
* Starts with a "/".
* Contains an URL protocol, like "http:" or "https:".
In general though, it is best to use the baseUrl and "paths" config to set paths for module IDs. By doing so, it gives you more flexibility in renaming and configuring the paths to different locations for optimization builds.
Similarly, to avoid a bunch of configuration, it is best to avoid deep folder hierarchies for scripts, and instead either keep all the scripts in baseUrl, or if you want to separate your library/vendor-supplied code from your app code, use a directory layout like this:
* www/
+ index.html
+ js/
- app/
* sub.js
- lib/
* jquery.js
* canvas.js
- app.js
- require.js
in index.html:
```
<script data-main="js/app.js" src="js/require.js"></script>
```
and in app.js:
```
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
app: '../app'
}
});
// Start the main app logic.
requirejs(['jquery', 'canvas', 'app/sub'],
function ($, canvas, sub) {
//jQuery, canvas and the app/sub module are all
//loaded and can be used here now.
});
```
Notice as part of that example, vendor libraries like jQuery did not have their version numbers in their file names. It is recommended to store that version info in a separate text file if you want to track it, or if you use a tool like [volo](https://github.com/volojs/volo), it will stamp the package.json with the version information but keep the file on disk as "jquery.js". This allows you to have the very minimal configuration instead of having to put an entry in the "paths" config for each library. For instance, configure "jquery" to be "jquery-1.7.2".
Ideally the scripts you load will be modules that are defined by calling [define()](#define). However, you may need to use some traditional/legacy "browser globals" scripts that do not express their dependencies via define(). For those, you can use the [shim config](#config-shim). To properly express their dependencies.
If you do not express the dependencies, you will likely get loading errors since RequireJS loads scripts asynchronously and out of order for speed.
### data-main Entry Point
The data-main attribute is a special attribute that require.js will check to start script loading:
```
<!--when require.js loads it will inject another script tag
(with async attribute) for scripts/main.js-->
<script data-main="scripts/main" src="scripts/require.js"></script>
```
You will typically use a data-main script to [set configuration options](#config) and then load the first application module. Note: the script tag require.js generates for your data-main module includes the [async attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async). This means that **you cannot assume that the load and execution of your data-main script will finish prior to other scripts referenced later in the same page.**
For example, this arrangement will fail randomly when the require.config path for the 'foo' module has not been set prior to it being require()'d later:
```
<script data-main="scripts/main" src="scripts/require.js"></script>
<script src="scripts/other.js"></script>
```
```
// contents of main.js:
require.config({
paths: {
foo: 'libs/foo-1.1.3'
}
});
```
```
// contents of other.js:
// This code might be called before the require.config() in main.js
// has executed. When that happens, require.js will attempt to
// load 'scripts/foo.js' instead of 'scripts/libs/foo-1.1.3.js'
require(['foo'], function(foo) {
});
```
If you want to do `require()` calls in the HTML page, then it is best to not use data-main. data-main is only intended for use when the page just has one main entry point, the data-main script. For pages that want to do inline `require()` calls, it is best to nest those inside a `require()` call for the configuration:
```
<script src="scripts/require.js"></script>
<script>
require(['scripts/config'], function() {
// Configuration loaded now, safe to do other require calls
// that depend on that config.
require(['foo'], function(foo) {
});
});
</script>
```
### Define a Module
A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module. Modules in RequireJS are an extension of the [Module Pattern](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth), with the benefit of not needing globals to refer to other modules.
The RequireJS syntax for modules allows them to be loaded as fast as possible, even out of order, but evaluated in the correct dependency order, and since global variables are not created, it makes it possible to [load multiple versions of a module in a page](#multiversion).
(If you are familiar with or are using CommonJS modules, then please also see [CommonJS Notes](commonjs) for information on how the RequireJS module format maps to CommonJS modules).
There should only be **one** module definition per file on disk. The modules can be grouped into optimized bundles by the [optimization tool](optimization).
#### Simple Name/Value Pairs
If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():
```
//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});
```
#### Definition Functions
If the module does not have dependencies, but needs to use a function to do some setup work, then define itself, pass a function to define():
```
//my/shirt.js now does setup work
//before returning its module definition.
define(function () {
//Do setup work here
return {
color: "black",
size: "unisize"
}
});
```
#### Definition Functions with Dependencies
If the module has dependencies, the first argument should be an array of dependency names, and the second argument should be a definition function. The function will be called to define the module once all dependencies have loaded. The function should return an object that defines the module. The dependencies will be passed to the definition function as function arguments, listed in the same order as the order in the dependency array:
```
//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large",
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);
```
In this example, a my/shirt module is created. It depends on my/cart and my/inventory. On disk, the files are structured like this:
* my/cart.js
* my/inventory.js
* my/shirt.js
The function call above specifies two arguments, "cart" and "inventory". These are the modules represented by the "./cart" and "./inventory" module names.
The function is not called until the my/cart and my/inventory modules have been loaded, and the function receives the modules as the "cart" and "inventory" arguments.
Modules that define globals are explicitly discouraged, so that multiple versions of a module can exist in a page at a time (see **Advanced Usage**). Also, the order of the function arguments should match the order of the dependencies.
The return object from the function call defines the "my/shirt" module. By defining modules in this way, "my/shirt" does not exist as a global object.
#### Define a Module as a Function
Modules do not have to return objects. Any valid return value from a function is allowed. Here is a module that returns a function as its module definition:
```
//A module definition inside foo/title.js. It uses
//my/cart and my/inventory modules from before,
//but since foo/title.js is in a different directory than
//the "my" modules, it uses the "my" in the module dependency
//name to find them. The "my" part of the name can be mapped
//to any directory, but by default, it is assumed to be a
//sibling to the "foo" directory.
define(["my/cart", "my/inventory"],
function(cart, inventory) {
//return a function to define "foo/title".
//It gets or sets the window title.
return function(title) {
return title ? (window.title = title) :
inventory.storeName + ' ' + cart.name;
}
}
);
```
#### Define a Module with Simplified CommonJS Wrapper
If you wish to reuse some code that was written in the traditional [CommonJS module format](http://wiki.commonjs.org/wiki/Modules/1.1.1) it may be difficult to re-work to the array of dependencies used above, and you may prefer to have direct alignment of dependency name to the local variable used for that dependency. You can use the [simplified CommonJS wrapper](commonjs) for those cases:
```
define(function(require, exports, module) {
var a = require('a'),
b = require('b');
//Return the module value
return function () {};
}
);
```
This wrapper relies on Function.prototype.toString() to give a useful string value of the function contents. This does not work on some devices like the PS3 and some older Opera mobile browsers. Use the [optimizer](optimization) to pull out the dependencies in the array format for use on those devices.
More information is available on the [CommonJS page](commonjs), and in the ["Sugar" section in the Why AMD page](whyamd#sugar).
#### Define a Module with a Name
You may encounter some define() calls that include a name for the module as the first argument to define():
```
//Explicitly defines the "foo/title" module:
define("foo/title",
["my/cart", "my/inventory"],
function(cart, inventory) {
//Define foo/title object in here.
}
);
```
These are normally generated by the [optimization tool](optimization). You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.
#### Other Module Notes
**One module per file.**: Only one module should be defined per JavaScript file, given the nature of the module name-to-file-path lookup algorithm. You shoud only use the [optimization tool](optimization) to group multiple modules into optimized files.
**Relative module names inside define()**: For require("./relative/name") calls that can happen inside a define() function call, be sure to ask for "require" as a dependency, so that the relative name is resolved correctly:
```
define(["require", "./relative/name"], function(require) {
var mod = require("./relative/name");
});
```
Or better yet, use the shortened syntax that is available for use with [translating CommonJS](commonjs) modules:
```
define(function(require) {
var mod = require("./relative/name");
});
```
This form will use Function.prototype.toString() to find the require() calls, and add them to the dependency array, along with "require", so the code will work correctly with relative paths.
Relative paths are really useful if you are creating a few modules inside a directory, so that you can share the directory with other people or other projects, and you want to be able to get a handle on the sibling modules in that directory without having to know the directory's name.
**Relative module names are relative to other names, not paths**: The loader stores modules by their name and not by their path internally. So for relative name references, those are resolved relative to the module name making the reference, then that module name, or ID, is converted to a path if needs to be loaded. Example code for a 'compute' package that has a 'main' and 'extras' modules in it:
```
* lib/
* compute/
* main.js
* extras.js
```
where the main.js module looks like this:
```
define(["./extras"], function(extras) {
//Uses extras in here.
});
```
If this was the paths config:
```
require.config({
baseUrl: 'lib',
paths: {
'compute': 'compute/main'
}
});
```
And a `require(['compute'])` is done, then lib/compute/main.js will have the module name of 'compute'. When it asks for './extras', that is resolved relative to 'compute', so 'compute/./extras', which normalizes to just 'extras'. Since there is no paths config for that module name, the path generated will be for 'lib/extras.js', which is incorrect.
For this case, [packages config](#packages) is a better option, since it allows setting the main module up as 'compute', but internally the loader will store the module with the ID of 'compute/main' so that the relative reference for './extras' works.
Another option is to construct a module at lib/compute.js that is just `define(['./compute/main'], function(m) { return m; });`, then there is no need for paths or packages config.
Or, do not set that paths or packages config and do the top level require call as `require(['compute/main'])`.
**Generate URLs relative to module**: You may need to generate an URL that is relative to a module. To do so, ask for "require" as a dependency and then use require.toUrl() to generate the URL:
```
define(["require"], function(require) {
var cssUrl = require.toUrl("./style.css");
});
```
**Console debugging**: If you need to work with a module you already loaded via a `require(["module/name"], function(){})` call in the JavaScript console, then you can use the require() form that just uses the string name of the module to fetch it:
```
require("module/name").callSomeFunction()
```
Note this only works if "module/name" was previously loaded via the async version of require: `require(["module/name"])`. If using a relative path, like './module/name', those only work inside define
#### Circular Dependencies
If you define a circular dependency ("a" needs "b" and "b" needs "a"), then in this case when "b"'s module function is called, it will get an undefined value for "a". "b" can fetch "a" later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up "a"):
```
//Inside b.js:
define(["require", "a"],
function(require, a) {
//"a" in this case will be null if "a" also asked for "b",
//a circular dependency.
return function(title) {
return require("a").doSomething();
}
}
);
```
Normally you should not need to use require() to fetch a module, but instead rely on the module being passed in to the function as an argument. Circular dependencies are rare, and usually a sign that you might want to rethink the design. However, sometimes they are needed, and in that case, use require() as specified above.
If you are familiar with CommonJS modules, you could instead use **exports** to create an empty object for the module that is available immediately for reference by other modules. By doing this on both sides of a circular dependency, you can then safely hold on to the the other module. This only works if each module is exporting an object for the module value, not a function:
```
//Inside b.js:
define(function(require, exports, module) {
//If "a" has used exports, then we have a real
//object reference here. However, we cannot use
//any of "a"'s properties until after "b" returns a value.
var a = require("a");
exports.foo = function () {
return a.bar();
};
});
```
Or, if you are using the dependency array approach, ask for the special ['exports' dependency:](https://github.com/requirejs/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic)
```
//Inside b.js:
define(['a', 'exports'], function(a, exports) {
//If "a" has used exports, then we have a real
//object reference here. However, we cannot use
//any of "a"'s properties until after "b" returns a value.
exports.foo = function () {
return a.bar();
};
});
```
#### Specify a JSONP Service Dependency
[JSONP](http://en.wikipedia.org/wiki/JSON#JSONP) is a way of calling some services in JavaScript. It works across domains and it is an established approach to calling services that just require an HTTP GET via a script tag.
To use a JSONP service in RequireJS, specify "define" as the callback parameter's value. This means you can get the value of a JSONP URL as if it was a module definition.
Here is an example that calls a JSONP API endpoint. In this example, the JSONP callback parameter is called "callback", so "callback=define" tells the API to wrap the JSON response in a "define()" wrapper:
```
require(["http://example.com/api/data.json?callback=define"],
function (data) {
//The data object will be the API response for the
//JSONP data call.
console.log(data);
}
);
```
This use of JSONP should be limited to JSONP services for initial application setup. If the JSONP service times out, it means other modules you define via define() may not get executed, so the error handling is not robust.
**Only JSONP return values that are JSON objects are supported**. A JSONP response that is an array, a string or a number will not work.
This functionality should not be used for long-polling JSONP connections -- APIs that deal with real time streaming. Those kinds of APIs should do more script cleanup after receiving each response, and RequireJS will only fetch a JSONP URL once -- subsequent uses of the same URL as a dependency in a require() or define() call will get a cached value.
Errors in loading a JSONP service are normally surfaced via timeouts for the service, since script tag loading does not give much detail into network problems. To detect errors, you can override requirejs.onError() to get errors. There is more information in the [Handling Errors](#errors) section.
#### Undefining a Module
There is a global function, **requirejs.undef()**, that allows undefining a module. It will reset the loader's internal state to forget about the previous definition of the module.
**However**, it will not remove the module from other modules that are already defined and got a handle on that module as a dependency when they executed. So it is really only useful to use in error situations when no other modules have gotten a handle on a module value, or as part of any future module loading that may use that module. See the [errback section](#errbacks) for an example.
If you want to do more sophisticated dependency graph analysis for undefining work, the semi-private [onResourceLoad API](https://github.com/requirejs/requirejs/wiki/Internal-API:-onResourceLoad) may be helpful.
Mechanics
----------
RequireJS loads each dependency as a script tag, using head.appendChild().
RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions once the dependencies for those functions have been called. Note that the dependencies for a given module definition function could be called in any order, due to their sub-dependency relationships and network load order.
Using RequireJS in a server-side JavaScript environment that has synchronous loading should be as easy as redefining require.load(). The build system does this, the require.load method for that environment can be found in build/jslib/requirePatch.js.
In the future, this code may be pulled into the require/ directory as an optional module that you can load in your env to get the right load behavior based on the host environment.
Configuration Options
----------------------
When using require() in the top-level HTML page (or top-level script file that does not define a module), a configuration object can be passed as the first option:
```
<script src="scripts/require.js"></script>
<script>
require.config({
baseUrl: "/another/path",
paths: {
"some": "some/v1.0"
},
waitSeconds: 15
});
require( ["some/module", "my/module", "a.js", "b.js"],
function(someModule, myModule) {
//This function will be called when all the dependencies
//listed above are loaded. Note that this function could
//be called before the page is loaded.
//This callback is optional.
}
);
</script>
```
You may also call require.config from your [data-main Entry Point](api#data-main), but be aware that the data-main script is loaded asynchronously. Avoid other entry point scripts which wrongly assume that data-main and its require.config will always execute prior to their script loading.
Also, you can define the config object as the global variable `require` **before** require.js is loaded, and have the values applied automatically. This example specifies some dependencies to load as soon as require.js defines require():
```
<script>
var require = {
deps: ["some/module1", "my/module2", "a.js", "b.js"],
callback: function(module1, module2) {
//This function will be called when all the dependencies
//listed above in deps are loaded. Note that this
//function could be called before the page is loaded.
//This callback is optional.
}
};
</script>
<script src="scripts/require.js"></script>
```
**Note:** It is best to use `var require = {}` and do not use `window.require = {}`, it will not behave correctly in IE.
There are [some patterns for separating the config from main module loading](https://github.com/requirejs/requirejs/wiki/Patterns-for-separating-config-from-the-main-module).
Supported configuration options:
**[baseUrl](#config-baseUrl)**: the root path to use for all module lookups. So in the above example, "my/module"'s script tag will have a src="/another/path/my/module.js". baseUrl is **not** used when loading plain .js files (indicated by a dependency string [starting with a slash, has a protocol, or ends in .js](#jsfiles)), those strings are used as-is, so a.js and b.js will be loaded from the same directory as the HTML page that contains the above snippet.
If no baseUrl is explicitly set in the configuration, the default value will be the location of the HTML page that loads require.js. If a **data-main** attribute is used, that path will become the baseUrl.
The baseUrl can be a URL on a different domain as the page that will load require.js. RequireJS script loading works across domains. The only restriction is on text content loaded by text! plugins: those paths should be on the same domain as the page, at least during development. The optimization tool will inline text! plugin resources so after using the optimization tool, you can use resources that reference text! plugin resources from another domain.
**[paths](#config-paths)**: path mappings for module names not found directly under baseUrl. The path settings are assumed to be relative to baseUrl, unless the paths setting starts with a "/" or has a URL protocol in it ("like http:"). Using the above sample config, "some/module"'s script tag will be src="/another/path/some/v1.0/module.js".
The path that is used for a module name should **not** include an extension, since the path mapping could be for a directory. The path mapping code will automatically add the .js extension when mapping the module name to a path. If [require.toUrl()](#modulenotes-urls) is used, it will add the appropriate extension, if it is for something like a text template.
When run in a browser, [paths fallbacks](#pathsfallbacks) can be specified, to allow trying a load from a CDN location, but falling back to a local location if the CDN location fails to load.
**[bundles](#config-bundles)**: Introduced in RequireJS 2.1.10: allows configuring multiple module IDs to be found in another script. Example:
```
requirejs.config({
bundles: {
'primary': ['main', 'util', 'text', 'text!template.html'],
'secondary': ['text!secondary.html']
}
});
require(['util', 'text'], function(util, text) {
//The script for module ID 'primary' was loaded,
//and that script included the define()'d
//modules for 'util' and 'text'
});
```
That config states: modules 'main', 'util', 'text' and 'text!template.html' will be found by loading module ID 'primary'. Module 'text!secondary.html' can be found by loading module ID 'secondary'.
This only sets up where to find a module inside a script that has multiple define()'d modules in it. It does not automatically bind those modules to the bundle's module ID. The bundle's module ID is just used for locating the set of modules.
Something similar is possible with paths config, but it is much wordier, and the paths config route does not allow loader plugin resource IDs in its configuration, since the paths config values are path segments, not IDs.
bundles config is useful if doing a build and that build target was not an existing module ID, or if you have loader plugin resources in built JS files that should not be loaded by the loader plugin. **Note that the keys and values are module IDs**, not path segments. They are absolute module IDs, not a module ID prefix like [paths config](#config-paths) or [map config](#config-map). Also, bundle config is different from map config in that map config is a one-to-one module ID relationship, where bundle config is for pointing multiple module IDs to a bundle's module ID.
As of RequireJS 2.2.0, the optimizer can generate the bundles config and insert it into the top level requirejs.config() call. See the [bundlesConfigOutFile](https://github.com/requirejs/r.js/blob/98a9949480d68a781c8d6fc4ce0a07c16a2c8a2a/build/example.build.js#L641) build config option for more details.
**[shim](#config-shim)**: Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.
Here is an example. It requires RequireJS 2.1.0+, and assumes backbone.js, underscore.js and jquery.js have been installed in the baseUrl directory. If not, then you may need to set a paths config for them:
```
requirejs.config({
//Remember: only use shim config for non-AMD scripts,
//scripts that do not already call define(). The shim
//config will not work correctly if used on AMD scripts,
//in particular, the exports and init config will not
//be triggered, and the deps config will be confusing
//for those cases.
shim: {
'backbone': {
//These script dependencies should be loaded before loading
//backbone.js
deps: ['underscore', 'jquery'],
//Once loaded, use the global 'Backbone' as the
//module value.
exports: 'Backbone'
},
'underscore': {
exports: '_'
},
'foo': {
deps: ['bar'],
exports: 'Foo',
init: function (bar) {
//Using a function allows you to call noConflict for
//libraries that support it, and do other cleanup.
//However, plugins for those libraries may still want
//a global. "this" for the function will be the global
//object. The dependencies will be passed in as
//function arguments. If this function returns a value,
//then that value is used as the module export value
//instead of the object found via the 'exports' string.
//Note: jQuery registers as an AMD module via define(),
//so this will not work for jQuery. See notes section
//below for an approach for jQuery.
return this.Foo.noConflict();
}
}
}
});
//Then, later in a separate file, call it 'MyModel.js', a module is
//defined, specifying 'backbone' as a dependency. RequireJS will use
//the shim config to properly load 'backbone' and give a local
//reference to this module. The global Backbone will still exist on
//the page too.
define(['backbone'], function (Backbone) {
return Backbone.Model.extend({});
});
```
In RequireJS 2.0.\*, the "exports" property in the shim config could have been a function instead of a string. In that case, it functioned the same as the "init" property as shown above. The "init" pattern is used in RequireJS 2.1.0+ so a string value for `exports` can be used for [enforceDefine](#config-enforceDefine), but then allow functional work once the library is known to have loaded.
For "modules" that are just jQuery or Backbone plugins that do not need to export any module value, the shim config can just be an array of dependencies:
```
requirejs.config({
shim: {
'jquery.colorize': ['jquery'],
'jquery.scroll': ['jquery'],
'backbone.layoutmanager': ['backbone']
}
});
```
Note however if you want to get 404 load detection in IE so that you can use paths fallbacks or errbacks, then a string exports value should be given so the loader can check if the scripts actually loaded (a return from init is **not** used for `enforceDefine` checking):
```
requirejs.config({
shim: {
'jquery.colorize': {
deps: ['jquery'],
exports: 'jQuery.fn.colorize'
},
'jquery.scroll': {
deps: ['jquery'],
exports: 'jQuery.fn.scroll'
},
'backbone.layoutmanager': {
deps: ['backbone']
exports: 'Backbone.LayoutManager'
}
}
});
```
**Important notes for "shim" config:**
* The shim config only sets up code relationships. To load modules that are part of or use shim config, a normal require/define call is needed. Setting shim by itself does not trigger code to load.
* Only use other "shim" modules as dependencies for shimmed scripts, or AMD libraries that have no dependencies and call define() after they also create a global (like jQuery or lodash). Otherwise, if you use an AMD module as a dependency for a shim config module, after a build, that AMD module may not be evaluated until after the shimmed code in the build executes, and an error will occur. The ultimate fix is to upgrade all the shimmed code to have optional AMD define() calls.
* If it is not possible to upgrade the shimmed code to use AMD define() calls, as of RequireJS 2.1.11, the optimizer has a [wrapShim build option](https://github.com/requirejs/r.js/blob/b8a6982d2923ae8389355edaa50d2b7f8065a01a/build/example.build.js#L68) that will try to automatically wrap the shimmed code in a define() for a build. This changes the scope of shimmed dependencies, so it is not guaranteed to always work, but, for example, for shimmed dependencies that depend on an AMD version of Backbone, it can be helpful.
* The init function will **not** be called for AMD modules. For example, you cannot use a shim init function to call jQuery's noConflict. See [Mapping Modules to use noConflict](jquery#noconflictmap) for an alternate approach to jQuery.
* Shim config is not supported when running AMD modules in node via RequireJS (it works for optimizer use though). Depending on the module being shimmed, it may fail in Node because Node does not have the same global environment as browsers. As of RequireJS 2.1.7, it will warn you in the console that shim config is not supported, and it may or may not work. If you wish to suppress that message, you can pass `requirejs.config({ suppress: { nodeShim: true }});`.
**Important optimizer notes for "shim" config**:
* You should use the [mainConfigFile build option](optimization#mainConfigFile) to specify the file where to find the shim config. Otherwise the optimizer will not know of the shim config. The other option is to duplicate the shim config in the build profile.
* Do not mix CDN loading with shim config in a build. Example scenario: you load jQuery from the CDN but use the shim config to load something like the stock version of Backbone that depends on jQuery. When you do the build, be sure to inline jQuery in the built file and do not load it from the CDN. Otherwise, Backbone will be inlined in the built file and it will execute before the CDN-loaded jQuery will load. This is because the shim config just delays loading of the files until dependencies are loaded, but does not do any auto-wrapping of define. After a build, the dependencies are already inlined, the shim config cannot delay execution of the non-define()'d code until later. define()'d modules do work with CDN loaded code after a build because they properly wrap their source in define factory function that will not execute until dependencies are loaded. So the lesson: shim config is a stop-gap measure for non-modular code, legacy code. define()'d modules are better.
* For local, multi-file builds, the above CDN advice also applies. For any shimmed script, its dependencies **must** be loaded before the shimmed script executes. This means either building its dependencies directly in the buid layer that includes the shimmed script, or loading its dependencies with a `require([], function (){})` call, then doing a nested `require([])` call for the build layer that has the shimmed script.
* If you are using uglifyjs to minify the code, **do not** set the uglify option `toplevel` to true, or if using the command line **do not** pass `-mt`. That option mangles the global names that shim uses to find exports.
**[map](#config-map)**: For the given module prefix, instead of loading the module with the given ID, substitute a different module ID.
This sort of capability is really important for larger projects which may have two sets of modules that need to use two different versions of 'foo', but they still need to cooperate with each other.
This is not possible with the [context-backed multiversion support](#multiversion). In addition, the [paths config](#config-paths) is only for setting up root paths for module IDs, not for mapping one module ID to another one.
map example:
```
requirejs.config({
map: {
'some/newmodule': {
'foo': 'foo1.2'
},
'some/oldmodule': {
'foo': 'foo1.0'
}
}
});
```
If the modules are laid out on disk like this:
* foo1.0.js
* foo1.2.js
* some/
+ newmodule.js
+ oldmodule.js
When 'some/newmodule' does `require('foo')` it will get the foo1.2.js file, and when 'some/oldmodule' does `require('foo')` it will get the foo1.0.js file.
This feature only works well for scripts that are real AMD modules that call define() and register as anonymous modules. Also, **only use absolute module IDs** for map config. Relative IDs (like `'../some/thing'`) do not work.
There is also support for a "\*" map value which means "for all modules loaded, use this map config". If there is a more specific map config, that one will take precedence over the star config. Example:
```
requirejs.config({
map: {
'*': {
'foo': 'foo1.2'
},
'some/oldmodule': {
'foo': 'foo1.0'
}
}
});
```
Means that for any module except "some/oldmodule", when "foo" is wanted, use "foo1.2" instead. For "some/oldmodule" only, use "foo1.0" when it asks for "foo".
**Note:** when doing builds with map config, the map config needs to be fed to the optimizer, and the build output must still contain a requirejs config call that sets up the map config. The optimizer does not do ID renaming during the build, because some dependency references in a project could depend on runtime variable state. So the optimizer does not invalidate the need for a map config after the build.
**[config](#config-moduleconfig)**: There is a common need to pass configuration info to a module. That configuration info is usually known as part of the application, and there needs to be a way to pass that down to a module. In RequireJS, that is done with the **config** option for requirejs.config(). Modules can then read that info by asking for the special dependency "module" and calling **module.config()**. Example:
```
requirejs.config({
config: {
'bar': {
size: 'large'
},
'baz': {
color: 'blue'
}
}
});
//bar.js, which uses simplified CJS wrapping:
//http://requirejs.org/docs/whyamd.html#sugar
define(function (require, exports, module) {
//Will be the value 'large'
var size = module.config().size;
});
//baz.js which uses a dependency array,
//it asks for the special module ID, 'module':
//https://github.com/requirejs/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic
define(['module'], function (module) {
//Will be the value 'blue'
var color = module.config().color;
});
```
For passing config to a [package](#packages), target the main module in the package, not the package ID:
```
requirejs.config({
//Pass an API key for use in the pixie package's
//main module.
config: {
'pixie/index': {
apiKey: 'XJKDLNS'
}
},
//Set up config for the "pixie" package, whose main
//module is the index.js file in the pixie folder.
packages: [
{
name: 'pixie',
main: 'index'
}
]
});
```
**[packages](#config-packages)**: configures loading modules from CommonJS packages. See the [packages topic](#packages) for more information.
**[nodeIdCompat](#config-nodeIdCompat)**: Node treats module ID `example.js` and `example` the same. By default these are two different IDs in RequireJS. If you end up using modules installed from npm, then you may need to set this config value to `true` to avoid resolution issues. This option only applies to treating the ".js" suffix differently, it does not do any other node resolution and evaluation matching such as .json file handling (JSON handling needs a 'json!' loader plugin anyway). Available in 2.1.10 and greater.
**[waitSeconds](#config-waitSeconds)**: The number of seconds to wait before giving up on loading a script. Setting it to 0 disables the timeout. The default is 7 seconds.
**[context](#config-context)**: A name to give to a loading context. This allows require.js to load multiple versions of modules in a page, as long as each top-level require call specifies a unique context string. To use it correctly, see the [Multiversion Support](#multiversion) section.
**[deps](#config-deps)**: An array of dependencies to load. Useful when require is defined as a config object before require.js is loaded, and you want to specify dependencies to load as soon as require() is defined. Using deps is just like doing a `require([])` call, but done as soon as the loader has processed the configuration. **It does not block** any other require() calls from starting their requests for modules, it is just a way to specify some modules to load asynchronously as part of a config block.
**[callback](#config-callback)**: A function to execute after **deps** have been loaded. Useful when require is defined as a config object before require.js is loaded, and you want to specify a function to require after the configuration's **deps** array has been loaded.
**[enforceDefine](#config-enforceDefine)**: If set to true, an error will be thrown if a script loads that does not call define() or have a shim exports string value that can be checked. See [Catching load failures in IE](#ieloadfail) for more information.
**[xhtml](#config-xhtml)**: If set to true, document.createElementNS() will be used to create script elements.
**[urlArgs](#config-urlArgs)**: Extra query string arguments appended to URLs that RequireJS uses to fetch resources. Most useful to cache bust when the browser or server is not configured correctly. Example cache bust setting for urlArgs:
```
urlArgs: "bust=" + (new Date()).getTime()
```
As of RequireJS 2.2.0, urlArgs can be a function. If a function, it will receive the module ID and the URL as parameters, and it should return a string that will be added to the end of the URL. Return an empty string if no args. Be sure to take care of adding the '?' or '&' depending on the existing state of the URL. Example:
```
requirejs.config({
urlArgs: function(id, url) {
var args = 'v=1';
if (url.indexOf('view.html') !== -1) {
args = 'v=2'
}
return (url.indexOf('?') === -1 ? '?' : '&') + args;
}
});
```
During development it can be useful to use this, however **be sure** to remove it before deploying your code.
**[scriptType](#config-scriptType)**: Specify the value for the type="" attribute used for script tags inserted into the document by RequireJS. Default is "text/javascript". To use Firefox's JavaScript 1.8 features, use "text/javascript;version=1.8".
**[skipDataMain](#config-skipDataMain)**: Introduced in RequireJS 2.1.9: If set to `true`, skips the [data-main attribute scanning](#data-main) done to start module loading. Useful if RequireJS is embedded in a utility library that may interact with other RequireJS library on the page, and the embedded version should not do data-main loading.
Advanced Usage
---------------
### Loading Modules from Packages
RequireJS supports loading modules that are in a [CommonJS Packages](http://wiki.commonjs.org/wiki/Packages/1.1) directory structure, but some additional configuration needs to be specified for it to work. Specifically, there is support for the following CommonJS Packages features:
* A package can be associated with a module name/prefix.
* The package config can specify the following properties for a specific package:
+ **name**: The name of the package (used for the module name/prefix mapping)
+ **location**: The location on disk. Locations are relative to the baseUrl configuration value, unless they contain a protocol or start with a front slash (/).
+ **main**: The name of the module inside the package that should be used when someone does a require for "packageName". The default value is "main", so only specify it if it differs from the default. The value is relative to the package folder.
**IMPORTANT NOTES**
* While the packages can have the CommonJS directory layout, the modules themselves should be in a module format that RequireJS can understand. Exception to the rule: if you are using the r.js Node adapter, the modules can be in the traditional CommonJS module format. You can use the [CommonJS converter tool](commonjs#autoconversion) if you need to convert traditional CommonJS modules into the async module format that RequireJS uses.
* Only one version of a package can be used in a project context at a time. You can use RequireJS [multiversion support](#multiversion) to load two different module contexts, but if you want to use Package A and B in one context and they depend on different versions of Package C, then that will be a problem. This may change in the future.
If you use a similar project layout as specified in the [Start Guide](http://requirejs.org/docs/start.html), the start of your web project would look something like this (Node/Rhino-based projects are similar, just use the contents of the **scripts** directory as the top-level project directory):
* project-directory/
+ project.html
+ scripts/
- require.js
Here is how the example directory layout looks with two packages, **cart** and **store**:
* project-directory/
+ project.html
+ scripts/
- cart/
* main.js
- store/
* main.js
* util.js
- main.js
- require.js
**project.html** will have a script tag like this:
```
<script data-main="scripts/main" src="scripts/require.js"></script>
```
This will instruct require.js to load scripts/main.js. **main.js** uses the "packages" config to set up packages that are relative to require.js, which in this case are the source packages "cart" and "store":
```
//main.js contents
//Pass a config object to require
require.config({
"packages": ["cart", "store"]
});
require(["cart", "store", "store/util"],
function (cart, store, util) {
//use the modules as usual.
});
```
A require of "cart" means that it will be loaded from **scripts/cart/main.js**, since "main" is the default main module setting supported by RequireJS. A require of "store/util" will be loaded from **scripts/store/util.js**.
If the "store" package did not follow the "main.js" convention, and looked more like this:
* project-directory/
+ project.html
+ scripts/
- cart/
* main.js
- store/
* store.js
* util.js
- main.js
- package.json
- require.js
Then the RequireJS configuration would look like so:
```
require.config({
packages: [
"cart",
{
name: "store",
main: "store"
}
]
});
```
To avoid verbosity, it is strongly suggested to always use packages that use "main" convention in their structure.
### Multiversion Support
As mentioned in [Configuration Options](#config), multiple versions of a module can be loaded in a page by using different "context" configuration options. require.config() returns a require function that will use the context configuration. Here is an example that loads two different versions of the alpha and beta modules (this example is taken from one of the test files):
```
<script src="../require.js"></script>
<script>
var reqOne = require.config({
context: "version1",
baseUrl: "version1"
});
reqOne(["require", "alpha", "beta",],
function(require, alpha, beta) {
log("alpha version is: " + alpha.version); //prints 1
log("beta version is: " + beta.version); //prints 1
setTimeout(function() {
require(["omega"],
function(omega) {
log("version1 omega loaded with version: " +
omega.version); //prints 1
}
);
}, 100);
});
var reqTwo = require.config({
context: "version2",
baseUrl: "version2"
});
reqTwo(["require", "alpha", "beta"],
function(require, alpha, beta) {
log("alpha version is: " + alpha.version); //prints 2
log("beta version is: " + beta.version); //prints 2
setTimeout(function() {
require(["omega"],
function(omega) {
log("version2 omega loaded with version: " +
omega.version); //prints 2
}
);
}, 100);
});
</script>
```
Note that "require" is specified as a dependency for the module. This allows the require() function that is passed to the function callback to use the right context to load the modules correctly for multiversion support. If "require" is not specified as a dependency, then there will likely be an error.
### Loading Code After Page Load
The example above in the **Multiversion Support** section shows how code can later be loaded by nested require() calls.
### Web Worker Support
As of release 0.12, RequireJS can be run inside a Web Worker. Just use importScripts() inside a web worker to load require.js (or the JS file that contains the require() definition), then call require.
You will likely need to set the **baseUrl** [configuration option](#config) to make sure require() can find the scripts to load.
You can see an example of its use by looking at one of the files used in [the unit test](http://github.com/requirejs/requirejs/blob/master/tests/workers.js).
### Rhino Support
RequireJS can be used in Rhino via the [r.js adapter](http://requirejs.org/docs/download.html#rjs). See [the r.js README](https://github.com/requirejs/r.js/blob/master/README.html) for more information.
### Nashorn Support
As of RequireJS 2.1.16, RequireJS can be used in [Nashorn](http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html), Java 8+'s JavaScript engine, via the [r.js adapter](http://requirejs.org/docs/download.html#rjs). See [the r.js README](https://github.com/requirejs/r.js/blob/master/README.html) for more information.
### Handling Errors
The general class of errors are 404s for scripts (not found), network timeouts or errors in the scripts that are loaded. RequireJS has a few tools to deal with them: require-specific errbacks, a "paths" array config, and a global requirejs.onError.
The error object passed to errbacks and the global requirejs.onError function will usually contain two custom properties:
* **requireType**: A string value with a general classification, like "timeout", "nodefine", "scripterror".
* **requireModules**: an array of module names/URLs that timed out.
If you get an error with a requireModules, it probably means other modules that depend on the modules in that requireModules array are not defined.
#### Catching load failures in IE
Internet Explorer has a set of problems that make it difficult to detect load failures for errbacks/paths fallbacks:
* script.onerror does not work in IE 6-8. There is no way to know if loading a script generates a 404, worse, it triggers the onreadystatechange with a complete state even in a 404 case.
* script.onerror does work in IE 9+, but it has a bug where it does not fire script.onload event handlers right after execution of script, so it cannot support the standard method of allowing anonymous AMD modules. So script.onreadystatechange is still used. However, onreadystatechange fires with a complete state before the script.onerror function fires.
So it is very difficult with IE to allow both anonymous AMD modules, which are a core benefit of AMD modules, and reliable detect errors.
However, if you are in a project that you know uses define() to declare all of its modules, or it uses the [shim](#config-shim) config to specify string exports for anything that does not use define(), then if you set the [enforceDefine](#config-enforceDefine) config value to true, the loader can confirm if a script load by checking for the define() call or the existence of the shim's exports global value.
So if you want to support Internet Explorer, catch load errors, and have modular code either through direct define() calls or shim config, always set **enforceDefine** to be true. See the next section for an example.
**NOTE**: If you do set enforceDefine: true, and you use data-main="" to load your main JS module, then that main JS module **must call define()** instead of require() to load the code it needs. The main JS module can still call require/requirejs to set config values, but for loading modules it should use define().
If you then also use [almond](https://github.com/requirejs/almond) to build your code without require.js, be sure to use the [insertRequire](https://github.com/requirejs/r.js/blob/master/build/example.build.js#L413) build setting to insert a require call for the main module -- that serves the same purpose of the initial require() call that data-main does.
#### require([]) errbacks
Errbacks, when used with [requirejs.undef()](#undef), will allow you to detect if a module fails to load, undefine that module, reset the config to a another location, then try again.
A common use case for this is to use a CDN-hosted version of a library, but if that fails, switch to loading the file locally:
```
requirejs.config({
enforceDefine: true,
paths: {
jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min'
}
});
//Later
require(['jquery'], function ($) {
//Do something with $ here
}, function (err) {
//The errback, error callback
//The error has a list of modules that failed
var failedId = err.requireModules && err.requireModules[0];
if (failedId === 'jquery') {
//undef is function only on the global requirejs object.
//Use it to clear internal knowledge of jQuery. Any modules
//that were dependent on jQuery and in the middle of loading
//will not be loaded yet, they will wait until a valid jQuery
//does load.
requirejs.undef(failedId);
//Set the path to jQuery to local path
requirejs.config({
paths: {
jquery: 'local/jquery'
}
});
//Try again. Note that the above require callback
//with the "Do something with $ here" comment will
//be called if this new attempt to load jQuery succeeds.
require(['jquery'], function () {});
} else {
//Some other error. Maybe show message to the user.
}
});
```
With `requirejs.undef()`, if you later set up a different config and try to load the same module, the loader will still remember which modules needed that dependency and finish loading them when the newly configured module loads.
**Note**: errbacks only work with callback-style require calls, not define() calls. define() is only for declaring modules.
#### paths config fallbacks
The above pattern for detecting a load failure, undef()ing a module, modifying paths and reloading is a common enough request that there is also a shorthand for it. The paths config allows array values:
```
requirejs.config({
//To get timely, correct error triggers in IE, force a define/shim exports check.
enforceDefine: true,
paths: {
jquery: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min',
//If the CDN location fails, load from this location
'lib/jquery'
]
}
});
//Later
require(['jquery'], function ($) {
});
```
This above code will try the CDN location, but if that fails, fall back to the local lib/jquery.js location.
**Note**: paths fallbacks only work for exact module ID matches. This is different from normal paths config which can apply to any part of a module ID prefix segment. Fallbacks are targeted more for unusual error recovery, not a generic path search path solution, since those are inefficient in the browser.
#### Global requirejs.onError function
To detect errors that are not caught by local errbacks, you can override requirejs.onError():
```
requirejs.onError = function (err) {
console.log(err.requireType);
if (err.requireType === 'timeout') {
console.log('modules: ' + err.requireModules);
}
throw err;
};
```
Loader Plugins
---------------
RequireJS supports [loader plugins](plugins). This is a way to support dependencies that are not plain JS files, but are still important for a script to have loaded before it can do its work. The RequireJS wiki has [a list of plugins](https://github.com/requirejs/requirejs/wiki/Plugins). This section talks about some specific plugins that are maintained alongside RequireJS:
### Specify a Text File Dependency
It is nice to build HTML using regular HTML tags, instead of building up DOM structures in script. However, there is no good way to embed HTML in a JavaScript file. The best that can be done is using a string of HTML, but that can be hard to manage, particularly for multi-line HTML.
RequireJS has a plugin, text.js, that can help with this issue. It will automatically be loaded if the text! prefix is used for a dependency. See the [text.js README](https://github.com/requirejs/text) for more information.
### Page Load Event Support/DOM Ready
It is possible when using RequireJS to load scripts quickly enough that they complete before the DOM is ready. Any work that tries to interact with the DOM should wait for the DOM to be ready. For modern browsers, this is done by waiting for the DOMContentLoaded event.
However, not all browsers in use support DOMContentLoaded. The domReady module implements a cross-browser method to determine when the DOM is ready. [Download the module](http://requirejs.org/docs/download.html#domReady) and use it in your project like so:
```
require(['domReady'], function (domReady) {
domReady(function () {
//This function is called once the DOM is ready.
//It will be safe to query the DOM and manipulate
//DOM nodes in this function.
});
});
```
Since DOM ready is a common application need, ideally the nested functions in the API above could be avoided. The domReady module also implements the [Loader Plugin API](plugins), so you can use the loader plugin syntax (notice the **!** in the domReady dependency) to force the require() callback function to wait for the DOM to be ready before executing.
```
domReady
```
will return the current document when used as a loader plugin:
```
require(['domReady!'], function (doc) {
//This function is called once the DOM is ready,
//notice the value for 'domReady!' is the current
//document.
});
```
**Note:** If the document takes a while to load (maybe it is a very large document, or has HTML script tags loading large JS files that block DOM completion until they are done), using domReady as a loader plugin may result in a RequireJS "timeout" error. If this is a problem either increase the [waitSeconds](#config-waitSeconds) configuration, or just use domReady as a module and call domReady() inside the require() callback.
### Define an I18N Bundle
Once your web app gets to a certain size and popularity, localizing the strings in the interface and providing other locale-specific information becomes more useful. However, it can be cumbersome to work out a scheme that scales well for supporting multiple locales.
RequireJS allows you to set up a basic module that has localized information without forcing you to provide all locale-specific information up front. It can be added over time, and only strings/values that change between locales can be defined in the locale-specific file.
i18n bundle support is provided by the i18n.js plugin. It is automatically loaded when a module or dependency specifies the i18n! prefix (more info below). [Download the plugin](http://requirejs.org/docs/download.html#i18n) and put it in the same directory as your app's main JS file.
To define a bundle, put it in a directory called "nls" -- the i18n! plugin assumes a module name with "nls" in it indicates an i18n bundle. The "nls" marker in the name tells the i18n plugin where to expect the locale directories (they should be immediate children of the nls directory). If you wanted to provide a bundle of color names in your "my" set of modules, create the directory structure like so:
* my/nls/colors.js
The contents of that file should look like so:
```
//my/nls/colors.js contents:
define({
"root": {
"red": "red",
"blue": "blue",
"green": "green"
}
});
```
An object literal with a property of "root" defines this module. That is all you have to do to set the stage for later localization work.
You can then use the above module in another module, say, in a my/lamps.js file:
```
//Contents of my/lamps.js
define(["i18n!my/nls/colors"], function(colors) {
return {
testMessage: "The name for red in this locale is: " + colors.red
}
});
```
The my/lamps module has one property called "testMessage" that uses colors.red to show the localized value for the color red.
Later, when you want to add a specific translation to a file, say for the fr-fr locale, change my/nls/colors to look like so:
```
//Contents of my/nls/colors.js
define({
"root": {
"red": "red",
"blue": "blue",
"green": "green"
},
"fr-fr": true
});
```
Then define a file at my/nls/fr-fr/colors.js that has the following contents:
```
//Contents of my/nls/fr-fr/colors.js
define({
"red": "rouge",
"blue": "bleu",
"green": "vert"
});
```
RequireJS will use the browser's navigator.languages, navigator.language or navigator.userLanguage property to determine what locale values to use for my/nls/colors, so your app does not have to change. If you prefer to set the locale, you can use the [module config](#config-moduleconfig) to pass the locale to the plugin:
```
requirejs.config({
config: {
//Set the config for the i18n
//module ID
i18n: {
locale: 'fr-fr'
}
}
});
```
**Note** that RequireJS will always use a lowercase version of the locale, to avoid case issues, so all of the directories and files on disk for i18n bundles should use lowercase locales.
RequireJS is also smart enough to pick the right locale bundle, the one that most closely matches the ones provided by my/nls/colors. For instance, if the locale is "en-us", then the "root" bundle will be used. If the locale is "fr-fr-paris" then the "fr-fr" bundle will be used.
RequireJS also combines bundles together, so for instance, if the french bundle was defined like so (omitting a value for red):
```
//Contents of my/nls/fr-fr/colors.js
define({
"blue": "bleu",
"green": "vert"
});
```
Then the value for red in "root" will be used. This works for all locale pieces. If all the bundles listed below were defined, then RequireJS will use the values in the following priority order (the one at the top takes the most precedence):
* my/nls/fr-fr-paris/colors.js
* my/nls/fr-fr/colors.js
* my/nls/fr/colors.js
* my/nls/colors.js
If you prefer to not include the root bundle in the top level module, you can define it like a normal locale bundle. In that case, the top level module would look like:
```
//my/nls/colors.js contents:
define({
"root": true,
"fr-fr": true,
"fr-fr-paris": true
});
```
and the root bundle would look like:
```
//Contents of my/nls/root/colors.js
define({
"red": "red",
"blue": "blue",
"green": "green"
});
```
| programming_docs |
requirejs How to use RequireJS with jQuery How to use RequireJS with jQuery
================================
* [Introduction](#intro)
* [Global Functions](#globalvars)
* [Module Name](#modulename)
* [Example using shim config](#shimconfig)
* [Example loading jquery from a CDN](#cdnconfig)
* [Mapping Modules to use noConflict](#noconflictmap)
* [The previous example with a concatenated require-jquery file](#oldexample)
Introduction
-------------
While RequireJS loads jQuery just like any other dependency, jQuery's wide use and extensive plugin ecosystem mean you'll likely have other scripts in your project that also depend on jQuery. You might approach your jQuery RequireJS configuration differently depending on whether you are starting a new project or whether you are adapting existing code.
Global Functions
-----------------
jQuery registers itself as the global variables "$" and "jQuery", even when it detects AMD/RequireJS. The AMD approach advises against the use of global functions, but the decision to turn off these jQuery globals hinges on whether you have non-AMD code that depends on them. jQuery has a [noConflict function](http://api.jquery.com/jQuery.noConflict/) that supports releasing control of the global variables and this can be automated in your requirejs.config, as we will see [later](#noconflictmap).
Module Name
------------
jQuery defines [named AMD module](api#modulename) 'jquery' (all lower case) when it detects AMD/RequireJS. To reduce confusion, we recommend using 'jquery' as the module name in your requirejs.config.
Example:
```
requirejs.config({
baseUrl: 'js/lib',
paths: {
// the left side is the module ID,
// the right side is the path to
// the jQuery file, relative to baseUrl.
// Also, the path should NOT include
// the '.js' file extension. This example
// is using jQuery 1.9.0 located at
// js/lib/jquery-1.9.0.js, relative to
// the HTML page.
jquery: 'jquery-1.9.0'
}
});
```
The other (recommended) solution is to just name the file 'jquery.js' and place it in the baseUrl directory. Then the above paths entry is not needed.
You can avoid lots of configuration lines by placing the files according to the default ID-to-path convention of `baseUrl + moduleID + '.js'`. The examples below show how to set baseUrl to be the directory for third-party, library code, and use one extra paths config for your app code.
So to reiterate, you will likely get an error if you refer to jQuery with another module name, like `'lib/jquery'`. **This example will not work**:
```
// THIS WILL NOT WORK
define(['lib/jquery'], function ($) {...});
```
It will not work, since jQuery registers itself with the name of 'jquery' and not 'lib/jquery'. In general, explicitly naming modules in the define() call are discouraged, but [jQuery has some special constraints](https://github.com/requirejs/requirejs/wiki/Updating-existing-libraries#anon).
Example using shim config
--------------------------
This example shows how to use the [shim config](api#config-shim) to specify dependencies for jQuery plugins that do not call [define()](api#define). This example is useful if you have an existing jQuery project you want to convert and do not want to modify the sources of the jQuery plugins to call define().
#### [Example using jQuery with shim config](http://github.com/requirejs/example-jquery-shim)
Example loading jquery from a CDN
----------------------------------
This is an example on how to load an optimize your code while loading jQuery from a [Content Delivery Network](http://en.wikipedia.org/wiki/Content_delivery_network) (CDN). This example requires all your jQuery plugins to call [define()](api#define) to properly express their dependencies. [Shim config](api#config-shim) does not work after optimization builds with CDN resources.
#### [Example using jQuery from a CDN](http://github.com/requirejs/example-jquery-cdn)
Mapping Modules to use noConflict
----------------------------------
If **all of your modules** (including any third party jQuery plugins or library code that depend on jQuery) are AMD compatible and you want to avoid having $ or jQuery in the global namespace when they call `requirejs(['jquery'])`, you can use the [map config](api#config-map) to map the use of jQuery to a module that calls noConflict and returns that value of jQuery for the 'jquery' module ID.
You can use this example with the CDN example above -- the shim example will not work since shimmed libraries need a global jQuery.
```
requirejs.config({
// Add this map config in addition to any baseUrl or
// paths config you may already have in the project.
map: {
// '*' means all modules will get 'jquery-private'
// for their 'jquery' dependency.
'*': { 'jquery': 'jquery-private' },
// 'jquery-private' wants the real jQuery module
// though. If this line was not here, there would
// be an unresolvable cyclic dependency.
'jquery-private': { 'jquery': 'jquery' }
}
});
// and the 'jquery-private' module, in the
// jquery-private.js file:
define(['jquery'], function (jq) {
return jq.noConflict( true );
});
```
This means that any module which uses jQuery will need to use the AMD return value rather than depending on the global $:
```
requirejs(['jquery'], function( $ ) {
console.log( $ ) // OK
});
requirejs(['jquery'], function( jq ) {
console.log( jq ) // OK
});
requirejs(['jquery'], function( ) {
console.log( $ ) // UNDEFINED!
});
```
The previous example with a concatenated require-jquery file
-------------------------------------------------------------
Previously, we've been pointing to an example using a special require-jquery file, which consisted of require.js and jQuery concatenated. This is no longer the recommended way to use jQuery with require.js, but if you're looking for the (no longer maintained) example, [you can find require-jquery here](https://github.com/requirejs/require-jquery).
Latest Release: [2.3.5](http://requirejs.org/docs/download.html) Open source: [new BSD or MIT licensed](https://github.com/requirejs/requirejs/blob/master/LICENSE) web design by [Andy Chung](http://andychung.me/) © 2011-2017
requirejs Common Errors Common Errors
=============
* [Mismatched anonymous define() modules ...](#mismatch)
* [Load timeout for modules: ...](#timeout)
* [Error evaluating module ...](#defineerror)
* [Module name ... has not been loaded yet for context: ...](#notloaded)
* [Invalid require call](#requireargs)
* [No define call for ...](#nodefine)
* [Script error](#scripterror)
* [No matching script interactive for ...](#interactive)
* [Path is not supported: ...](#pathnotsupported)
* [Cannot use preserveLicenseComments and generateSourceMaps together](#sourcemapcomments)
* [importScripts failed for ...](#importscripts)
This page lists errors that are generated by RequireJS. If the following information does not fix the problem, you can ask on the [RequireJS list](https://groups.google.com/group/requirejs) or [open an issue](https://github.com/requirejs/requirejs/issues). In either case it is best to have an example or detailed explanation of the problem, hopefully with steps to reproduce.
Mismatched anonymous define() modules ...
-----------------------------------------
If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.
If you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.
If you use the loader plugins or anonymous modules (modules that call define() with no string ID) but do not use the RequireJS optimizer to combine files together, this error can occur. The optimizer knows how to name anonymous modules correctly so that they can be combined with other modules in an optimized file.
If you use `var define;` at the top of your file for jshint/jslint purposes, this will cause a problem for the optimizer because it avoids parsing files that declare a `define` variable, since that may indicate a script that was created by a concatenation of some scripts that use a local define.
To avoid the error:
* Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.
* If you manually code an HTML script tag, be sure it only includes named modules, and that an anonymous module that will have the same name as one of the modules in that file is not loaded.
* If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer.
* If the problem is the `var define` lint approach, use `/*global define */` (no space before "global") comment style instead.
Load timeout for modules: ...
-----------------------------
Likely causes and fixes:
* There was a script error in one of the listed modules. If there is no script error in the browser's error console, and if you are using Firebug, try loading the page in another browser like Chrome or Safari. Sometimes script errors do not show up in Firebug.
* The path configuration for a module is incorrect. Check the "Net" or "Network" tab in the browser's developer tools to see if there was a 404 for an URL that would map to the module name. Make sure the script file is in the right place. In some cases you may need to use the [paths configuration](api#config) to fix the URL resolution for the script.
* The paths config was used to set two module IDs to the same file, and that file only has one anonymous module in it. If module IDs "something" and "lib/something" are both configured to point to the same "scripts/libs/something.js" file, and something.js only has one anonymous module in it, this kind of timeout error can occur. The fix is to make sure all module ID references use the same ID (either choose "something" or "lib/something" for all references), or use [map config](api#config-map).
Error evaluating module ...
---------------------------
An error occured when the define() function was called for the module given in the error message. It is an error with the code logic inside the define function. The error could happen inside a require callback.
In Firefox and WebKit browsers, a line number and file name will be indicated in the error. It can be used to locate the source of the problem. Better isolation of the error can be done by using a debugger to place a breakpoint in the file that contains the error.
Module name ... has not been loaded yet for context: ...
--------------------------------------------------------
This occurs when there is a require('name') call, but the 'name' module has not been loaded yet.
If the error message includes **Use require([])**, then it was a top-level require call (not a require call inside a define() call) that should be using the async, callback version of require to load the code:
```
//If this code is not in a define call,
//DO NOT use require('foo'), but use the async
//callback version:
require(['foo'], function (foo) {
//foo is now loaded.
});
```
If you are using the simplified define wrapper, make sure you have **require** as the first argument to the definition function:
```
define(function (require) {
var namedModule = require('name');
});
```
If you are listing dependencies in the dependency array, make sure that **require** and **name** are in the dependency array:
```
define(['require', 'name'], function (require) {
var namedModule = require('name');
});
```
In particular, **the following will not work**:
```
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
```
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. If a dependency array is given to define(), then requirejs assumes that all dependencies are listed in that array, and it will not scan the factory function for other dependencies. So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
If part of a require() callback, all the dependencies need to be listed in the array:
```
require(['require', 'name'], function (require) {
var namedModule = require('name');
});
```
Be sure that **require('name')** only occurs inside a define() definition function or a require() callback function, never in the global space by its own.
**In the RequreJS 1.0.x releases**, there [is a bug](https://github.com/requirejs/requirejs/issues/265) with having a space between the require and parens in WebKit browsers when using the simplified CommonJS wrapping (no dependency array):
```
define(function (require) {
//Notice the space between require and the arguments.
var namedModule = require ('name');
});
```
The workaround is to just remove the space. This is fixed in the 2.0 code, and may be backported to the 1.0.x series if a 1.0.9 release is done.
Invalid require call
--------------------
This occurs when there is a call like:
```
require('dependency', function (dependency) {});
```
Asynchronously loading dependencies should use an array to list the dependencies:
```
require(['dependency'], function (dependency) {});
```
No define call for ...
----------------------
This occurs when [enforceDefine is set to true](#), and a script that is loaded either:
* Did not call define() to declare a module.
* Or was part of a [shim config](api#config-shim) that specified a string `exports` property that can be checked to verify loading, and that check failed.
* Or was part of a [shim config](api#config-shim) that did not set a string value for the `exports` config option.
Or, if the error shows up only in IE and not in other browsers (which may generate a [Script error](#scripterror), the script probably:
* Threw a JavaScript syntax/evaluation error.
* Or there was a 404 error in IE where the script failed to load.
Those IE behaviors result in [IE's quirks in detecting script errors](api#ieloadfail).
To fix it:
* If the module calls define(), make sure the define call was reached by debugging in a script debugger.
* If part of a shim config, make sure the shim config's exports check is correct.
* If in IE, check for an HTTP 404 error or a JavaScript sytnax error by using a script debugger.
Script error
------------
This occurs when the script.onerror function is triggered in a browser. This usually means there is a JavaScript syntax error or other execution problem running the script. To fix it, examine the script that generated the error in a script debugger.
This error may not show up in IE, just other browsers, and instead, in IE you may see the [No define call for ...](#nodefine) error when you see "Script error". This is due to [IE's quirks in detecting script errors](api#ieloadfail).
No matching script interactive for ...
--------------------------------------
This error only shows up in some IE browsers. Most likely caused by loading a script that calls define() but was loaded in a plain script tag or via some other call, like an eval() of a JavaScript string.
To avoid the error, be sure to load all scripts that call define via the RequireJS API.
Path is not supported: ...
--------------------------
This error occurs when the optimizer encounters a path to a module or script which is a network path. The optimizer only allows building with local resources. To fix it:
Make sure you reference the network dependency as a module name, not as a full URL, so that it can be mapped to a different during the build:
```
//DO NOT DO THIS
require(['http://some.domain.dom/path/to/dependency.js'],
function (dependency) {});
//Rather, do this:
require.config({
paths: {
'dependency': 'http://some.domain.dom/path/to/dependency'
}
});
require(['dependency'], function (dependency) {});
```
If you want to include this dependency in the built/optimized file, download the JS file and in the build profile for the optimizer, put in a paths config that points to that local file.
If you want to **exclude** that file from being included, and just need to map "dependency" for the build (otherwise it will not build), then use the special "empty:" paths config:
```
//Inside the build profile
{
paths: {
'dependency': 'empty:'
}
}
```
Cannot use preserveLicenseComments and generateSourceMaps together
------------------------------------------------------------------
In the r.js optimizer, **preserveLicenseComments** works as a pre- and post-processing step on a JS file. Various kinds of license comments are found, pulled out of the JS source, then that modified source is passed to the minifier. When the minifier is done, the comments are added to the top of the file by the r.js optimizer.
However, for the minifier to accurately construct a source map, the minified source cannot be modified in any way, so **preserveLicenseComments** is incompatible with **generateSourceMaps**. generateSourceMaps was introduced in version 2.1.2 of the optimizer.
The default for the optimizer is for **preserveLicenseComments** to be true. So if using **generateSourceMaps**, then explicitly set **preserveLicenseComments** to false. If you want to preserve some license comments, you can manually modify the license comments in the JS source to use the JSDoc-style `@license` comment. See "[Annotating JavaScript for the Closure Compiler](https://developers.google.com/closure/compiler/docs/js-for-compiler#tag-license)" for more information. That same format works for UglifyJS2.
importScripts failed for ...
----------------------------
When RequireJS is used in a [Web Worker](https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers), [importScripts](https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers#Importing_scripts_and_libraries) is used to load modules. If that call failed for some reason, this error is generated.
requirejs CommonJS Notes CommonJS Notes
==============
* [Introduction](#intro)
* [Manual Conversion](#manualconversion)
* [Conversion Tool](#autoconversion)
* [Setting Exported Value](#exports)
* [Alternative Syntax](#altsyntax)
* [Loading Modules from CommonJS Packages](#packages)
* [Optimization Tool](#optimize)
Introduction
------------
[CommonJS](http://www.commonjs.org/) defines [a module format](http://wiki.commonjs.org/wiki/Modules/1.1.1). Unfortunately, it was defined without giving browsers equal footing to other JavaScript environments. Because of that, there are CommonJS spec proposals for [Transport formats](http://wiki.commonjs.org/wiki/Modules/Transport) and an [asynchronous require](http://wiki.commonjs.org/wiki/Modules/Async/A).
RequireJS tries to keep with the spirit of CommonJS, with using string names to refer to dependencies, and to avoid modules defining global objects, but still allow coding a module format that works well natively in the browser. RequireJS implements the [Asynchronous Module Definition](http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition) (formerly Transport/C) proposal.
If you have modules that are in the traditional CommonJS module format, then you can easily convert them to work with RequireJS. Not all modules will convert cleanly to the new format. Types of modules that may not convert well:
* Modules that use conditional code to do a require call, like if(someCondition) require('a1') else require('a2');
* Some types of circular dependencies.
Manual Conversion
-----------------
If you just have a few modules to convert, then all you need to do is wrap the module in this code:
```
define(function(require, exports, module) {
//Put traditional CommonJS module content here
});
```
**IMPORTANT**: The function arguments should always be listed as **require, exports, module**, with those exact names and in that exact order, otherwise chaos will ensue. You can leave off exports and module from the list, but if they are needed, they need to be specified in the exact order illustrated here.
Conversion Tool
---------------
If you have many modules to convert, the [r.js project](https://github.com/requirejs/r.js) has a converter tool built into the r.js file. Give it the path to the directory you want to convert and an output directory:
```
node r.js -convert path/to/commonjs/modules/ path/to/output
```
There are a small number of CommonJS modules do not work well as define()-wrapped modules. See the [r.js README](https://github.com/requirejs/r.js)
for more information. Setting Exported Value
----------------------
There are some CommonJS systems, mainly Node, that allow setting the exported value by assigning the exported value as module.exports. That idiom is supported by RequireJS, but there is another, easier way -- just return the value from the function passed to **define**:
```
define(function (require) {
var foo = require('foo');
//Define this module as exporting a function
return function () {
foo.doSomething();
};
});
```
With this approach, then you normally do not need the exports and module function arguments, so you can leave them off the module definition.
Alternative Syntax
------------------
Instead of using require() to get dependencies inside the function passed to define(), you can also specify them via a dependency array argument to define(). The order of the names in the dependency array match the order of arguments passed to the definition function passed to define(). So the above example that uses the module **foo**:
```
define(['foo'], function (foo) {
return function () {
foo.doSomething();
};
});
```
See the [API docs](index) for more information on that syntax.
Loading Modules from CommonJS Packages
--------------------------------------
Modules in CommonJS packages can be loaded by RequireJS by setting up the RequireJS configuration to know about the location and package attributes. See the [packages API section](api#packages) for more information.
Optimization Tool
-----------------
RequireJS has an optimization tool that can combine module definitions together into optimized bundles for browser delivery. It works as a command-line tool that you use as part of code deployment. See the [optimization docs](optimization) for more information.
| programming_docs |
requirejs Why AMD? Why AMD?
========
* [Module Purposes](#purposes)
* [The Web Today](#today)
* [CommonJS](#commonjs)
* [AMD](#amd)
* [Module Definition](#definition)
* [Named Modules](#namedmodules)
* [Sugar](#sugar)
* [CommonJS Compatibility](#commonjscompat)
* [AMD Used Today](#amdtoday)
* [What You Can Do](#youcando)
This page talks about the design forces and use of the [Asynchronous Module Definition (AMD) API](https://github.com/amdjs/amdjs-api/wiki/AMD) for JavaScript modules, the module API supported by RequireJS. There is a different page that talks about [general approach to modules on the web](why).
Module Purposes
----------------
What are JavaScript modules? What is their purpose?
* **Definition**: how to encapsulate a piece of code into a useful unit, and how to register its capability/export a value for the module.
* **Dependency References**: how to refer to other units of code.
The Web Today
--------------
```
(function () {
var $ = this.jQuery;
this.myExample = function () {};
}());
```
How are pieces of JavaScript code defined today?
* Defined via an immediately executed factory function.
* References to dependencies are done via global variable names that were loaded via an HTML script tag.
* The dependencies are very weakly stated: the developer needs to know the right dependency order. For instance, The file containing Backbone cannot come before the jQuery tag.
* It requires extra tooling to substitute a set of script tags into one tag for optimized deployment.
This can be difficult to manage on large projects, particularly as scripts start to have many dependencies in a way that may overlap and nest. Hand-writing script tags is not very scalable, and it leaves out the capability to load scripts on demand.
CommonJS
---------
```
var $ = require('jquery');
exports.myExample = function () {};
```
The original [CommonJS (CJS) list](http://groups.google.com/group/commonjs) participants decided to work out a module format that worked with today's JavaScript language, but was not necessarily bound to the limitations of the browser JS environment. The hope was to use some stop-gap measures in the browser and hopefully influence the browser makers to build solutions that would enable their module format to work better natively. The stop-gap measures:
* Either use a server to translate CJS modules to something usable in the browser.
* Or use XMLHttpRequest (XHR) to load the text of modules and do text transforms/parsing in browser.
The CJS module format only allowed one module per file, so a "transport format" would be used for bundling more than one module in a file for optimization/bundling purposes.
With this approach, the CommonJS group was able to work out dependency references and how to deal with circular dependencies, and how to get some properties about the current module. However, they did not fully embrace some things in the browser environment that cannot change but still affect module design:
* network loading
* inherent asynchronicity
It also meant they placed more of a burden on web developers to implement the format, and the stop-gap measures meant debugging was worse. eval-based debugging or debugging multiple files that are concatenated into one file have practical weaknesses. Those weaknesses may be addressed in browser tooling at some point in the future, but the end result: using CommonJS modules in the most common of JS environments, the browser, is non-optimal today.
AMD
----
```
define(['jquery'] , function ($) {
return function () {};
});
```
The AMD format comes from wanting a module format that was better than today's "write a bunch of script tags with implicit dependencies that you have to manually order" and something that was easy to use directly in the browser. Something with good debugging characteristics that did not require server-specific tooling to get started. It grew out of Dojo's real world experience with using XHR+eval and wanting to avoid its weaknesses for the future.
It is an improvement over the web's current "globals and script tags" because:
* Uses the CommonJS practice of string IDs for dependencies. Clear declaration of dependencies and avoids the use of globals.
* IDs can be mapped to different paths. This allows swapping out implementation. This is great for creating mocks for unit testing. For the above code sample, the code just expects something that implements the jQuery API and behavior. It does not have to be jQuery.
* Encapsulates the module definition. Gives you the tools to avoid polluting the global namespace.
* Clear path to defining the module value. Either use "return value;" or the CommonJS "exports" idiom, which can be useful for circular dependencies.
It is an improvement over CommonJS modules because:
* It works better in the browser, it has the least amount of gotchas. Other approaches have problems with debugging, cross-domain/CDN usage, file:// usage and the need for server-specific tooling.
* Defines a way to include multiple modules in one file. In CommonJS terms, the term for this is a "transport format", and that group has not agreed on a transport format.
* Allows setting a function as the return value. This is really useful for constructor functions. In CommonJS this is more awkward, always having to set a property on the exports object. Node supports module.exports = function () {}, but that is not part of a CommonJS spec.
Module Definition
------------------
Using JavaScript functions for encapsulation has been documented as the [module pattern](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth):
```
(function () {
this.myGlobal = function () {};
}());
```
That type of module relies on attaching properties to the global object to export the module value, and it is difficult to declare dependencies with this model. The dependencies are assumed to be immediately available when this function executes. This limits the loading strategies for the dependencies.
AMD addresses these issues by:
* Register the factory function by calling define(), instead of immediately executing it.
* Pass dependencies as an array of string values, do not grab globals.
* Only execute the factory function once all the dependencies have been loaded and executed.
* Pass the dependent modules as arguments to the factory function.
```
//Calling define with a dependency array and a factory function
define(['dep1', 'dep2'], function (dep1, dep2) {
//Define the module value by returning a value.
return function () {};
});
```
Named Modules
--------------
Notice that the above module does not declare a name for itself. This is what makes the module very portable. It allows a developer to place the module in a different path to give it a different ID/name. The AMD loader will give the module an ID based on how it is referenced by other scripts.
However, tools that combine multiple modules together for performance need a way to give names to each module in the optimized file. For that, AMD allows a string as the first argument to define():
```
//Calling define with module ID, dependency array, and factory function
define('myModule', ['dep1', 'dep2'], function (dep1, dep2) {
//Define the module value by returning a value.
return function () {};
});
```
You should avoid naming modules yourself, and only place one module in a file while developing. However, for tooling and performance, a module solution needs a way to identify modules in built resources.
Sugar
------
The above AMD example works in all browsers. However, there is a risk of mismatched dependency names with named function arguments, and it can start to look a bit strange if your module has many dependencies:
```
define([ "require", "jquery", "blade/object", "blade/fn", "rdapi",
"oauth", "blade/jig", "blade/url", "dispatch", "accounts",
"storage", "services", "widgets/AccountPanel", "widgets/TabButton",
"widgets/AddAccount", "less", "osTheme", "jquery-ui-1.8.7.min",
"jquery.textOverflow"],
function (require, $, object, fn, rdapi,
oauth, jig, url, dispatch, accounts,
storage, services, AccountPanel, TabButton,
AddAccount, less, osTheme) {
});
```
To make this easier, and to make it easy to do a simple wrapping around CommonJS modules, this form of define is supported, sometimes referred to as "simplified CommonJS wrapping":
```
define(function (require) {
var dependency1 = require('dependency1'),
dependency2 = require('dependency2');
return function () {};
});
```
The AMD loader will parse out the require('') calls by using Function.prototype.toString(), then internally convert the above define call into this:
```
define(['require', 'dependency1', 'dependency2'], function (require) {
var dependency1 = require('dependency1'),
dependency2 = require('dependency2');
return function () {};
});
```
This allows the loader to load dependency1 and dependency2 asynchronously, execute those dependencies, then execute this function.
Not all browsers give a usable Function.prototype.toString() results. As of October 2011, the PS 3 and older Opera Mobile browsers do not. Those browsers are more likely to need an optimized build of the modules for network/device limitations, so just do a build with an optimizer that knows how to convert these files to the normalized dependency array form, like the [RequireJS optimizer](optimization).
Since the number of browsers that cannot support this toString() scanning is very small, it is safe to use this sugared form for all your modules, particularly if you like to line up the dependency names with the variables that will hold their module values.
CommonJS Compatibility
-----------------------
Even though this sugared form is referred to as the "simplified CommonJS wrapping", it is not 100% compatible with CommonJS modules. However, the cases that are not supported would likely break in the browser anyway, since they generally assume synchronous loading of dependencies.
Most CJS modules, around 95% based on my (thoroughly unscientific) personal experience, are perfectly compatible with the simplified CommonJS wrapping.
The modules that break are ones that do a dynamic calculation of a dependency, anything that does not use a string literal for the require() call, and anything that does not look like a declarative require() call. So things like this fail:
```
//BAD
var mod = require(someCondition ? 'a' : 'b');
//BAD
if (someCondition) {
var a = require('a');
} else {
var a = require('a1');
}
```
These cases are handled by the [callback-require](https://github.com/amdjs/amdjs-api/wiki/require), `require([moduleName], function (){})` normally present in AMD loaders.
The AMD execution model is better aligned with how ECMAScript Harmony modules are being specified. The CommonJS modules that would not work in an AMD wrapper will also not work as a Harmony module. AMD's code execution behavior is more future compatible.
Verbosity vs. Usefulness
------------------------
One of the criticisms of AMD, at least compared to CJS modules, is that it requires a level of indent and a function wrapping.
But here is the plain truth: the perceived extra typing and a level of indent to use AMD does not matter. Here is where your time goes when coding:
* Thinking about the problem.
* Reading code.
Your time coding is mostly spent thinking, not typing. While fewer words are generally preferable, there is a limit to that approach paying off, and the extra typing in AMD is not that much more.
Most web developers use a function wrapper anyway, to avoid polluting the page with globals. Seeing a function wrapped around functionality is a very common sight and does not add to the reading cost of a module.
There are also hidden costs with the CommonJS format:
* the tooling dependency cost
* edge cases that break in browsers, like cross-domain access
* worse debugging, a cost that continues to add up over time
AMD modules require less tooling, there are fewer edge case issues, and better debugging support.
What is important: being able to actually share code with others. AMD is the lowest energy pathway to that goal.
Having a working, easy to debug module system that works in today's browsers means getting real world experience in making the best module system for JavaScript in the future.
AMD and its related APIs, have helped show the following for any future JS module system:
* **Returning a function as the module value**, particularly a constructor function, leads to better API design. Node has module.exports to allow this, but being able to use "return function (){}" is much cleaner. It means not having to get a handle on "module" to do module.exports, and it is a clearer code expression.
* **Dynamic code loading** (done in AMD systems via [require([], function (){})](https://github.com/amdjs/amdjs-api/wiki/require)) is a basic requirement. CJS talked about it, had some proposals, but it was not fully embraced. Node does not have any support for this need, instead relying on the synchronous behavior of require(''), which is not portable to the web.
* **[Loader plugins](plugins)** are incredibly useful. It helps avoid the nested brace indenting common in callback-based programming.
* **Selectively mapping one module** to load from another location makes it easy to provide mock objects for testing.
* There should only be at most **one IO action for each module**, and it should be straightforward. Web browsers are not tolerant of multiple IO lookups to find a module. This argues against the multiple path lookups that Node does now, and avoiding the use of a package.json "main" property. Just use module names that map easily to one location based on the project's location, using a reasonable default convention that does not require verbose configuration, but allow for simple configuration when needed.
* It is best if there is an **"opt-in" call** that can be done so that older JS code can participate in the new system.
If a JS module system cannot deliver on the above features, it is at a significant disadvantage when compared to AMD and its related APIs around [callback-require](https://github.com/amdjs/amdjs-api/wiki/require), [loader plugins](https://github.com/amdjs/amdjs-api/wiki/Loader-Plugins), and paths-based module IDs.
AMD Used Today
---------------
As of mid-October 2011, AMD already has good adoption on the web:
* [jQuery](http://jquery.com/) 1.7
* [Dojo](http://dojotoolkit.org/) 1.7
* [EmbedJS](http://uxebu.github.com/embedjs/)
* [Ender](http://enderjs.com/)-associated modules like [bonzo](https://github.com/ded/bonzo), [qwery](https://github.com/ded/qwery), [bean](https://github.com/fat/bean) and [domready](https://github.com/ded/domready)
* Used by [Firebug](http://getfirebug.com/) 1.8+
* The simplified CommonJS wrapper can be used in [Jetpack/Add-on SDK](https://addons.mozilla.org/en-US/developers/docs/sdk/1.1/) for Firefox
* Used for parts of sites on [the BBC](http://www.bbc.co.uk/) (observed by looking at the source, not an official recommendation of AMD/RequireJS)
What You Can Do
----------------
**If you write applications:**
* Give an AMD loader a try. You have some choices:
+ [RequireJS](http://requirejs.org)
+ [curl](https://github.com/cujojs/curl)
+ [lsjs](https://github.com/zazl/lsjs)
+ [Dojo](http://dojotoolkit.org/) 1.7+
* If you want to use AMD but still use the **load one script at the bottom of the HTML page** approach:
+ Use the [RequireJS optimizer](optimization) either in command line mode or as an [HTTP service](https://github.com/requirejs/r.js/blob/master/build/tests/http/httpBuild.js) with the [almond AMD shim](https://github.com/requirejs/almond).
**If you are a script/library author**:
* [Optionally call define()](https://github.com/umdjs/umd) if it is available. The nice thing is you can still code your library without relying on AMD, just participate if it is available. This allows consumers of your modules to:
+ avoid dumping global variables in the page
+ use more options for code loading, delayed loading
+ use existing AMD tooling to optimize their project
+ participate in a workable module system for JS in the browser today.
**If you write code loaders/engines/environments for JavaScript:**
* Implement [the AMD API](https://github.com/amdjs/amdjs-api/wiki/AMD). There is [a discussion list](https://groups.google.com/group/amd-implement) and [compatibility tests](https://github.com/amdjs/amdjs-tests). By implementing AMD, you will reduce multi-module system boilerplate and help prove out a workable JavaScript module system on the web. This can be fed back into the ECMAScript process to build better native module support.
* Also support [callback-require](https://github.com/amdjs/amdjs-api/wiki/require) and [loader plugins](https://github.com/amdjs/amdjs-api/wiki/Loader-Plugins). Loader plugins are a great way to reduce the nested callback syndrome that can be common in callback/async-style code.
requirejs How to use RequireJS with Dojo How to use RequireJS with Dojo
==============================
As of Dojo 1.8, Dojo has converted their modules to AMD modules. However, Dojo uses some loader plugins, and the loader plugin APIs are still in draft mode for AMD. So while some modules from Dojo can be used with RequireJS, it will be difficult to use all of Dojo. It is best to use Dojo's AMD loader until [ticket 15616](http://bugs.dojotoolkit.org/ticket/15616) has been resolved.
async async async
=====
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with [Node.js](http://nodejs.org) and installable via `npm install --save async`, it can also be used directly in the browser.
Source: [index.js](https://caolan.github.io/async/v3/index.js.html), [line 40](https://caolan.github.io/async/v3/index.js.html#line40) See: [AsyncFunction](https://caolan.github.io/async/v3/global.html) Collections
===========
A collection of `async` functions for manipulating collections, such as arrays and objects.
Source: [index.js](https://caolan.github.io/async/v3/index.js.html), [line 50](https://caolan.github.io/async/v3/index.js.html#line50) Methods
-------
###
(static) concat(coll, iteratee, callbackopt)
```
import concat from 'async/concat';
```
Applies `iteratee` to each item in `coll`, concatenating the results. Returns the concatenated list. The `iteratee`s are called in parallel, and the results are concatenated as they return. The results array will be returned in the original order of `coll` passed to the `iteratee` function.
Alias: flatMap #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function to apply to each item in `coll`, which should use an array as its result. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished, or an error occurs. Results is an array containing the concatenated results of the `iteratee` function. Invoked with (err, results). |
#### Returns:
A Promise, if no callback is passed
#### Example
```
async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
// files is now a list of filenames that exist in the 3 directories
});
```
Source: [concat.js](https://caolan.github.io/async/v3/concat.js.html), [line 4](https://caolan.github.io/async/v3/concat.js.html#line4) ###
(static) concatLimit(coll, limit, iteratee, callbackopt)
```
import concatLimit from 'async/concatLimit';
```
The same as [`concat`](#concat) but runs a maximum of `limit` async operations at a time.
Alias: flatMapLimit #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function to apply to each item in `coll`, which should use an array as its result. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished, or an error occurs. Results is an array containing the concatenated results of the `iteratee` function. Invoked with (err, results). |
#### Returns:
A Promise, if no callback is passed
Source: [concatLimit.js](https://caolan.github.io/async/v3/concatLimit.js.html), [line 5](https://caolan.github.io/async/v3/concatLimit.js.html#line5) See: [async.concat](#concat)
###
(static) concatSeries(coll, iteratee, callbackopt)
```
import concatSeries from 'async/concatSeries';
```
The same as [`concat`](#concat) but runs only a single async operation at a time.
Alias: flatMapSeries #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function to apply to each item in `coll`. The iteratee should complete with an array an array of results. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished, or an error occurs. Results is an array containing the concatenated results of the `iteratee` function. Invoked with (err, results). |
#### Returns:
A Promise, if no callback is passed
Source: [concatSeries.js](https://caolan.github.io/async/v3/concatSeries.js.html), [line 4](https://caolan.github.io/async/v3/concatSeries.js.html#line4) See: [async.concat](#concat)
###
(static) detect(coll, iteratee, callbackopt)
```
import detect from 'async/detect';
```
Returns the first value in `coll` that passes an async truth test. The `iteratee` is applied in parallel, meaning the first iteratee to return `true` will fire the detect `callback` with that result. That means the result might not be the first item in the original `coll` (in terms of order) that passes the test. If order within the original `coll` is important, then look at [`detectSeries`](#detectSeries).
Alias: find #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A truth test to apply to each item in `coll`. The iteratee must complete with a boolean value as its result. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called as soon as any iteratee returns `true`, or after all the `iteratee` functions have finished. Result will be the first item in the array that passes the truth test (iteratee) or the value `undefined` if none passed. Invoked with (err, result). |
#### Returns:
A Promise, if no callback is passed
#### Example
```
async.detect(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, result) {
// result now equals the first file in the list that exists
});
```
Source: [detect.js](https://caolan.github.io/async/v3/detect.js.html), [line 5](https://caolan.github.io/async/v3/detect.js.html#line5) ###
(static) detectLimit(coll, limit, iteratee, callbackopt)
```
import detectLimit from 'async/detectLimit';
```
The same as [`detect`](#detect) but runs a maximum of `limit` async operations at a time.
Alias: findLimit #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A truth test to apply to each item in `coll`. The iteratee must complete with a boolean value as its result. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called as soon as any iteratee returns `true`, or after all the `iteratee` functions have finished. Result will be the first item in the array that passes the truth test (iteratee) or the value `undefined` if none passed. Invoked with (err, result). |
#### Returns:
a Promise if no callback is passed
Source: [detectLimit.js](https://caolan.github.io/async/v3/detectLimit.js.html), [line 5](https://caolan.github.io/async/v3/detectLimit.js.html#line5) See: [async.detect](#detect)
###
(static) detectSeries(coll, iteratee, callbackopt)
```
import detectSeries from 'async/detectSeries';
```
The same as [`detect`](#detect) but runs only a single async operation at a time.
Alias: findSeries #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A truth test to apply to each item in `coll`. The iteratee must complete with a boolean value as its result. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called as soon as any iteratee returns `true`, or after all the `iteratee` functions have finished. Result will be the first item in the array that passes the truth test (iteratee) or the value `undefined` if none passed. Invoked with (err, result). |
#### Returns:
a Promise if no callback is passed
Source: [detectSeries.js](https://caolan.github.io/async/v3/detectSeries.js.html), [line 5](https://caolan.github.io/async/v3/detectSeries.js.html#line5) See: [async.detect](#detect)
###
(static) each(coll, iteratee, callbackopt) → {Promise}
```
import each from 'async/each';
```
Applies the function `iteratee` to each item in `coll`, in parallel. The `iteratee` is called with an item from the list, and a callback for when it has finished. If the `iteratee` passes an error to its `callback`, the main `callback` (for the `each` function) is immediately called with the error.
Note, that since this function applies `iteratee` to each item in parallel, there is no guarantee that the iteratee functions will complete in order.
Alias: forEach #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. Invoked with (item, callback). The array index is not passed to the iteratee. If you need the index, use `eachOf`. |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). |
#### Returns:
a promise, if a callback is omitted
Type Promise #### Example
```
// assuming openFiles is an array of file names and saveFile is a function
// to save the modified contents of that file:
async.each(openFiles, saveFile, function(err){
// if any of the saves produced an error, err would equal that error
});
// assuming openFiles is an array of file names
async.each(openFiles, function(file, callback) {
// Perform operation on file here.
console.log('Processing file ' + file);
if( file.length > 32 ) {
console.log('This file name is too long');
callback('File name too long');
} else {
// Do work to process file here
console.log('File processed');
callback();
}
}, function(err) {
// if any of the file processing produced an error, err would equal that error
if( err ) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('A file failed to process');
} else {
console.log('All files have been processed successfully');
}
});
```
Source: [each.js](https://caolan.github.io/async/v3/each.js.html), [line 6](https://caolan.github.io/async/v3/each.js.html#line6) ###
(static) eachLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import eachLimit from 'async/eachLimit';
```
The same as [`each`](#each) but runs a maximum of `limit` async operations at a time.
Alias: forEachLimit #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The array index is not passed to the iteratee. If you need the index, use `eachOfLimit`. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). |
#### Returns:
a promise, if a callback is omitted
Type Promise Source: [eachLimit.js](https://caolan.github.io/async/v3/eachLimit.js.html), [line 6](https://caolan.github.io/async/v3/eachLimit.js.html#line6) See: [async.each](#each)
###
(static) eachOf(coll, iteratee, callbackopt) → {Promise}
```
import eachOf from 'async/eachOf';
```
Like [`each`](#each), except that it passes the key (or index) as the second argument to the iteratee.
Alias: forEachOf #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function to apply to each item in `coll`. The `key` is the item's key, or index in the case of an array. Invoked with (item, key, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). |
#### Returns:
a promise, if a callback is omitted
Type Promise #### Example
```
var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
var configs = {};
async.forEachOf(obj, function (value, key, callback) {
fs.readFile(__dirname + value, "utf8", function (err, data) {
if (err) return callback(err);
try {
configs[key] = JSON.parse(data);
} catch (e) {
return callback(e);
}
callback();
});
}, function (err) {
if (err) console.error(err.message);
// configs is now a map of JSON data
doSomethingWith(configs);
});
```
Source: [eachOf.js](https://caolan.github.io/async/v3/eachOf.js.html), [line 42](https://caolan.github.io/async/v3/eachOf.js.html#line42) See: [async.each](#each)
###
(static) eachOfLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import eachOfLimit from 'async/eachOfLimit';
```
The same as [`eachOf`](#eachOf) but runs a maximum of `limit` async operations at a time.
Alias: forEachOfLimit #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The `key` is the item's key, or index in the case of an array. Invoked with (item, key, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). |
#### Returns:
a promise, if a callback is omitted
Type Promise Source: [eachOfLimit.js](https://caolan.github.io/async/v3/eachOfLimit.js.html), [line 5](https://caolan.github.io/async/v3/eachOfLimit.js.html#line5) See: [async.eachOf](#eachOf)
###
(static) eachOfSeries(coll, iteratee, callbackopt) → {Promise}
```
import eachOfSeries from 'async/eachOfSeries';
```
The same as [`eachOf`](#eachOf) but runs only a single async operation at a time.
Alias: forEachOfSeries #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. Invoked with (item, key, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). |
#### Returns:
a promise, if a callback is omitted
Type Promise Source: [eachOfSeries.js](https://caolan.github.io/async/v3/eachOfSeries.js.html), [line 4](https://caolan.github.io/async/v3/eachOfSeries.js.html#line4) See: [async.eachOf](#eachOf)
###
(static) eachSeries(coll, iteratee, callbackopt) → {Promise}
```
import eachSeries from 'async/eachSeries';
```
The same as [`each`](#each) but runs only a single async operation at a time.
Note, that unlike [`each`](#each), this function applies iteratee to each item in series and therefore the iteratee functions will complete in order.
Alias: forEachSeries #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The array index is not passed to the iteratee. If you need the index, use `eachOfSeries`. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). |
#### Returns:
a promise, if a callback is omitted
Type Promise Source: [eachSeries.js](https://caolan.github.io/async/v3/eachSeries.js.html), [line 4](https://caolan.github.io/async/v3/eachSeries.js.html#line4) See: [async.each](#each)
###
(static) every(coll, iteratee, callbackopt) → {Promise}
```
import every from 'async/every';
```
Returns `true` if every element in `coll` satisfies an async test. If any iteratee call returns `false`, the main `callback` is immediately called.
Alias: all #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async truth test to apply to each item in the collection in parallel. The iteratee must complete with a boolean result value. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). |
#### Returns:
a promise, if no callback provided
Type Promise #### Example
```
async.every(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, result) {
// if result is true then every file exists
});
```
Source: [every.js](https://caolan.github.io/async/v3/every.js.html), [line 5](https://caolan.github.io/async/v3/every.js.html#line5) ###
(static) everyLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import everyLimit from 'async/everyLimit';
```
The same as [`every`](#every) but runs a maximum of `limit` async operations at a time.
Alias: allLimit #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async truth test to apply to each item in the collection in parallel. The iteratee must complete with a boolean result value. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). |
#### Returns:
a promise, if no callback provided
Type Promise Source: [everyLimit.js](https://caolan.github.io/async/v3/everyLimit.js.html), [line 5](https://caolan.github.io/async/v3/everyLimit.js.html#line5) See: [async.every](#every)
###
(static) everySeries(coll, iteratee, callbackopt) → {Promise}
```
import everySeries from 'async/everySeries';
```
The same as [`every`](#every) but runs only a single async operation at a time.
Alias: allSeries #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async truth test to apply to each item in the collection in series. The iteratee must complete with a boolean result value. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). |
#### Returns:
a promise, if no callback provided
Type Promise Source: [everySeries.js](https://caolan.github.io/async/v3/everySeries.js.html), [line 5](https://caolan.github.io/async/v3/everySeries.js.html#line5) See: [async.every](#every)
###
(static) filter(coll, iteratee, callbackopt) → {Promise}
```
import filter from 'async/filter';
```
Returns a new array of all the values in `coll` which pass an async truth test. This operation is performed in parallel, but the results array will be in the same order as the original.
Alias: select #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | function | A truth test to apply to each item in `coll`. The `iteratee` is passed a `callback(err, truthValue)`, which must be called with a boolean argument once it has completed. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Invoked with (err, results). |
#### Returns:
a promise, if no callback provided
Type Promise #### Example
```
async.filter(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, results) {
// results now equals an array of the existing files
});
```
Source: [filter.js](https://caolan.github.io/async/v3/filter.js.html), [line 5](https://caolan.github.io/async/v3/filter.js.html#line5) ###
(static) filterLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import filterLimit from 'async/filterLimit';
```
The same as [`filter`](#filter) but runs a maximum of `limit` async operations at a time.
Alias: selectLimit #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | function | A truth test to apply to each item in `coll`. The `iteratee` is passed a `callback(err, truthValue)`, which must be called with a boolean argument once it has completed. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Invoked with (err, results). |
#### Returns:
a promise, if no callback provided
Type Promise Source: [filterLimit.js](https://caolan.github.io/async/v3/filterLimit.js.html), [line 5](https://caolan.github.io/async/v3/filterLimit.js.html#line5) See: [async.filter](#filter)
###
(static) filterSeries(coll, iteratee, callbackopt) → {Promise}
```
import filterSeries from 'async/filterSeries';
```
The same as [`filter`](#filter) but runs only a single async operation at a time.
Alias: selectSeries #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | function | A truth test to apply to each item in `coll`. The `iteratee` is passed a `callback(err, truthValue)`, which must be called with a boolean argument once it has completed. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Invoked with (err, results) |
#### Returns:
a promise, if no callback provided
Type Promise Source: [filterSeries.js](https://caolan.github.io/async/v3/filterSeries.js.html), [line 5](https://caolan.github.io/async/v3/filterSeries.js.html#line5) See: [async.filter](#filter)
###
(static) groupBy(coll, iteratee, callbackopt) → {Promise}
```
import groupBy from 'async/groupBy';
```
Returns a new object, where each value corresponds to an array of items, from `coll`, that returned the corresponding key. That is, the keys of the object correspond to the values passed to the `iteratee` callback.
Note: Since this function applies the `iteratee` to each item in parallel, there is no guarantee that the `iteratee` functions will complete in order. However, the values for each key in the `result` will be in the same order as the original `coll`. For Objects, the values will roughly be in the order of the original Objects' keys (but this can vary across JavaScript engines).
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The iteratee should complete with a `key` to group the value under. Invoked with (value, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Result is an `Object` whoses properties are arrays of values which returned the corresponding key. |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
db.findById(userId, function(err, user) {
if (err) return callback(err);
return callback(null, user.age);
});
}, function(err, result) {
// result is object containing the userIds grouped by age
// e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
});
```
Source: [groupBy.js](https://caolan.github.io/async/v3/groupBy.js.html), [line 3](https://caolan.github.io/async/v3/groupBy.js.html#line3) ###
(static) groupByLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import groupByLimit from 'async/groupByLimit';
```
The same as [`groupBy`](#groupBy) but runs a maximum of `limit` async operations at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The iteratee should complete with a `key` to group the value under. Invoked with (value, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Result is an `Object` whoses properties are arrays of values which returned the corresponding key. |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [groupByLimit.js](https://caolan.github.io/async/v3/groupByLimit.js.html), [line 5](https://caolan.github.io/async/v3/groupByLimit.js.html#line5) See: [async.groupBy](#groupBy)
###
(static) groupBySeries(coll, iteratee, callbackopt) → {Promise}
```
import groupBySeries from 'async/groupBySeries';
```
The same as [`groupBy`](#groupBy) but runs only a single async operation at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The iteratee should complete with a `key` to group the value under. Invoked with (value, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Result is an `Object` whoses properties are arrays of values which returned the corresponding key. |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [groupBySeries.js](https://caolan.github.io/async/v3/groupBySeries.js.html), [line 3](https://caolan.github.io/async/v3/groupBySeries.js.html#line3) See: [async.groupBy](#groupBy)
###
(static) map(coll, iteratee, callbackopt) → {Promise}
```
import map from 'async/map';
```
Produces a new collection of values by mapping each value in `coll` through the `iteratee` function. The `iteratee` is called with an item from `coll` and a callback for when it has finished processing. Each of these callback takes 2 arguments: an `error`, and the transformed item from `coll`. If `iteratee` passes an error to its callback, the main `callback` (for the `map` function) is immediately called with the error.
Note, that since this function applies the `iteratee` to each item in parallel, there is no guarantee that the `iteratee` functions will complete in order. However, the results array will be in the same order as the original `coll`.
If `map` is passed an Object, the results will be an Array. The results will roughly be in the order of the original Objects' keys (but this can vary across JavaScript engines).
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The iteratee should complete with the transformed item. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Results is an Array of the transformed items from the `coll`. Invoked with (err, results). |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
// results is now an array of stats for each file
});
```
Source: [map.js](https://caolan.github.io/async/v3/map.js.html), [line 5](https://caolan.github.io/async/v3/map.js.html#line5) ###
(static) mapLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import mapLimit from 'async/mapLimit';
```
The same as [`map`](#map) but runs a maximum of `limit` async operations at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The iteratee should complete with the transformed item. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Results is an array of the transformed items from the `coll`. Invoked with (err, results). |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [mapLimit.js](https://caolan.github.io/async/v3/mapLimit.js.html), [line 5](https://caolan.github.io/async/v3/mapLimit.js.html#line5) See: [async.map](#map)
###
(static) mapSeries(coll, iteratee, callbackopt) → {Promise}
```
import mapSeries from 'async/mapSeries';
```
The same as [`map`](#map) but runs only a single async operation at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The iteratee should complete with the transformed item. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. Results is an array of the transformed items from the `coll`. Invoked with (err, results). |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [mapSeries.js](https://caolan.github.io/async/v3/mapSeries.js.html), [line 5](https://caolan.github.io/async/v3/mapSeries.js.html#line5) See: [async.map](#map)
###
(static) mapValues(obj, iteratee, callbackopt) → {Promise}
```
import mapValues from 'async/mapValues';
```
A relative of [`map`](#map), designed for use with objects.
Produces a new Object by mapping each value of `obj` through the `iteratee` function. The `iteratee` is called each `value` and `key` from `obj` and a callback for when it has finished processing. Each of these callbacks takes two arguments: an `error`, and the transformed item from `obj`. If `iteratee` passes an error to its callback, the main `callback` (for the `mapValues` function) is immediately called with the error.
Note, the order of the keys in the result is not guaranteed. The keys will be roughly in the order they complete, (but this is very engine-specific)
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `obj` | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function to apply to each value and key in `coll`. The iteratee should complete with the transformed value as its result. Invoked with (value, key, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. `result` is a new object consisting of each key from `obj`, with each transformed value on the right-hand side. Invoked with (err, result). |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
async.mapValues({
f1: 'file1',
f2: 'file2',
f3: 'file3'
}, function (file, key, callback) {
fs.stat(file, callback);
}, function(err, result) {
// result is now a map of stats for each file, e.g.
// {
// f1: [stats for file1],
// f2: [stats for file2],
// f3: [stats for file3]
// }
});
```
Source: [mapValues.js](https://caolan.github.io/async/v3/mapValues.js.html), [line 3](https://caolan.github.io/async/v3/mapValues.js.html#line3) ###
(static) mapValuesLimit(obj, limit, iteratee, callbackopt) → {Promise}
```
import mapValuesLimit from 'async/mapValuesLimit';
```
The same as [`mapValues`](#mapValues) but runs a maximum of `limit` async operations at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `obj` | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function to apply to each value and key in `coll`. The iteratee should complete with the transformed value as its result. Invoked with (value, key, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. `result` is a new object consisting of each key from `obj`, with each transformed value on the right-hand side. Invoked with (err, result). |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [mapValuesLimit.js](https://caolan.github.io/async/v3/mapValuesLimit.js.html), [line 6](https://caolan.github.io/async/v3/mapValuesLimit.js.html#line6) See: [async.mapValues](#mapValues)
###
(static) mapValuesSeries(obj, iteratee, callbackopt) → {Promise}
```
import mapValuesSeries from 'async/mapValuesSeries';
```
The same as [`mapValues`](#mapValues) but runs only a single async operation at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `obj` | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function to apply to each value and key in `coll`. The iteratee should complete with the transformed value as its result. Invoked with (value, key, callback). |
| `callback` | function <optional> | A callback which is called when all `iteratee` functions have finished, or an error occurs. `result` is a new object consisting of each key from `obj`, with each transformed value on the right-hand side. Invoked with (err, result). |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [mapValuesSeries.js](https://caolan.github.io/async/v3/mapValuesSeries.js.html), [line 3](https://caolan.github.io/async/v3/mapValuesSeries.js.html#line3) See: [async.mapValues](#mapValues)
###
(static) reduce(coll, memo, iteratee, callbackopt) → {Promise}
```
import reduce from 'async/reduce';
```
Reduces `coll` into a single value using an async `iteratee` to return each successive step. `memo` is the initial state of the reduction. This function only operates in series.
For performance reasons, it may make sense to split a call to this function into a parallel map, and then use the normal `Array.prototype.reduce` on the results. This function is for situations where each step in the reduction needs to be async; if you can get the data before reducing it, then it's probably a good idea to do so.
Alias: foldl #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `memo` | \* | The initial state of the reduction. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function applied to each item in the array to produce the next step in the reduction. The `iteratee` should complete with the next state of the reduction. If the iteratee complete with an error, the reduction is stopped and the main `callback` is immediately called with the error. Invoked with (memo, item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Result is the reduced value. Invoked with (err, result). |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
async.reduce([1,2,3], 0, function(memo, item, callback) {
// pointless async:
process.nextTick(function() {
callback(null, memo + item)
});
}, function(err, result) {
// result is now equal to the last value of memo, which is 6
});
```
Source: [reduce.js](https://caolan.github.io/async/v3/reduce.js.html), [line 6](https://caolan.github.io/async/v3/reduce.js.html#line6) ###
(static) reduceRight(array, memo, iteratee, callbackopt) → {Promise}
```
import reduceRight from 'async/reduceRight';
```
Same as [`reduce`](#reduce), only operates on `array` in reverse order.
Alias: foldr #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `array` | Array | A collection to iterate over. |
| `memo` | \* | The initial state of the reduction. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function applied to each item in the array to produce the next step in the reduction. The `iteratee` should complete with the next state of the reduction. If the iteratee complete with an error, the reduction is stopped and the main `callback` is immediately called with the error. Invoked with (memo, item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Result is the reduced value. Invoked with (err, result). |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [reduceRight.js](https://caolan.github.io/async/v3/reduceRight.js.html), [line 3](https://caolan.github.io/async/v3/reduceRight.js.html#line3) See: [async.reduce](#reduce)
###
(static) reject(coll, iteratee, callbackopt) → {Promise}
```
import reject from 'async/reject';
```
The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | function | An async truth test to apply to each item in `coll`. The should complete with a boolean value as its `result`. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Invoked with (err, results). |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
async.reject(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, results) {
// results now equals an array of missing files
createFiles(results);
});
```
Source: [reject.js](https://caolan.github.io/async/v3/reject.js.html), [line 5](https://caolan.github.io/async/v3/reject.js.html#line5) See: [async.filter](#filter)
###
(static) rejectLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import rejectLimit from 'async/rejectLimit';
```
The same as [`reject`](#reject) but runs a maximum of `limit` async operations at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | function | An async truth test to apply to each item in `coll`. The should complete with a boolean value as its `result`. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Invoked with (err, results). |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [rejectLimit.js](https://caolan.github.io/async/v3/rejectLimit.js.html), [line 4](https://caolan.github.io/async/v3/rejectLimit.js.html#line4) See: [async.reject](#reject)
###
(static) rejectSeries(coll, iteratee, callbackopt) → {Promise}
```
import rejectSeries from 'async/rejectSeries';
```
The same as [`reject`](#reject) but runs only a single async operation at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | function | An async truth test to apply to each item in `coll`. The should complete with a boolean value as its `result`. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Invoked with (err, results). |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [rejectSeries.js](https://caolan.github.io/async/v3/rejectSeries.js.html), [line 5](https://caolan.github.io/async/v3/rejectSeries.js.html#line5) See: [async.reject](#reject)
###
(static) some(coll, iteratee, callbackopt) → {Promise}
```
import some from 'async/some';
```
Returns `true` if at least one element in the `coll` satisfies an async test. If any iteratee call returns `true`, the main `callback` is immediately called.
Alias: any #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async truth test to apply to each item in the collections in parallel. The iteratee should complete with a boolean `result` value. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called as soon as any iteratee returns `true`, or after all the iteratee functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). |
#### Returns:
a promise, if no callback provided
Type Promise #### Example
```
async.some(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, result) {
// if result is true then at least one of the files exists
});
```
Source: [some.js](https://caolan.github.io/async/v3/some.js.html), [line 5](https://caolan.github.io/async/v3/some.js.html#line5) ###
(static) someLimit(coll, limit, iteratee, callbackopt) → {Promise}
```
import someLimit from 'async/someLimit';
```
The same as [`some`](#some) but runs a maximum of `limit` async operations at a time.
Alias: anyLimit #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async truth test to apply to each item in the collections in parallel. The iteratee should complete with a boolean `result` value. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called as soon as any iteratee returns `true`, or after all the iteratee functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). |
#### Returns:
a promise, if no callback provided
Type Promise Source: [someLimit.js](https://caolan.github.io/async/v3/someLimit.js.html), [line 5](https://caolan.github.io/async/v3/someLimit.js.html#line5) See: [async.some](#some)
###
(static) someSeries(coll, iteratee, callbackopt) → {Promise}
```
import someSeries from 'async/someSeries';
```
The same as [`some`](#some) but runs only a single async operation at a time.
Alias: anySeries #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async truth test to apply to each item in the collections in series. The iteratee should complete with a boolean `result` value. Invoked with (item, callback). |
| `callback` | function <optional> | A callback which is called as soon as any iteratee returns `true`, or after all the iteratee functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). |
#### Returns:
a promise, if no callback provided
Type Promise Source: [someSeries.js](https://caolan.github.io/async/v3/someSeries.js.html), [line 5](https://caolan.github.io/async/v3/someSeries.js.html#line5) See: [async.some](#some)
###
(static) sortBy(coll, iteratee, callback) → {Promise}
```
import sortBy from 'async/sortBy';
```
Sorts a list by the results of running each `coll` value through an async `iteratee`.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function to apply to each item in `coll`. The iteratee should complete with a value to use as the sort criteria as its `result`. Invoked with (item, callback). |
| `callback` | function | A callback which is called after all the `iteratee` functions have finished, or an error occurs. Results is the items from the original `coll` sorted by the values returned by the `iteratee` calls. Invoked with (err, results). |
#### Returns:
a promise, if no callback passed
Type Promise #### Example
```
async.sortBy(['file1','file2','file3'], function(file, callback) {
fs.stat(file, function(err, stats) {
callback(err, stats.mtime);
});
}, function(err, results) {
// results is now the original array of files sorted by
// modified date
});
// By modifying the callback parameter the
// sorting order can be influenced:
// ascending order
async.sortBy([1,9,3,5], function(x, callback) {
callback(null, x);
}, function(err,result) {
// result callback
});
// descending order
async.sortBy([1,9,3,5], function(x, callback) {
callback(null, x*-1); //<- x*-1 instead of x, turns the order around
}, function(err,result) {
// result callback
});
```
Source: [sortBy.js](https://caolan.github.io/async/v3/sortBy.js.html), [line 5](https://caolan.github.io/async/v3/sortBy.js.html#line5) ###
(static) transform(coll, accumulatoropt, iteratee, callbackopt) → {Promise}
```
import transform from 'async/transform';
```
A relative of `reduce`. Takes an Object or Array, and iterates over each element in parallel, each step potentially mutating an `accumulator` value. The type of the accumulator defaults to the type of collection passed in.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `coll` | Array | Iterable | AsyncIterable | Object | A collection to iterate over. |
| `accumulator` | \* <optional> | The initial state of the transform. If omitted, it will default to an empty Object or Array, depending on the type of `coll` |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function applied to each item in the collection that potentially modifies the accumulator. Invoked with (accumulator, item, key, callback). |
| `callback` | function <optional> | A callback which is called after all the `iteratee` functions have finished. Result is the transformed accumulator. Invoked with (err, result). |
#### Returns:
a promise, if no callback provided
Type Promise #### Examples
```
async.transform([1,2,3], function(acc, item, index, callback) {
// pointless async:
process.nextTick(function() {
acc[index] = item * 2
callback(null)
});
}, function(err, result) {
// result is now equal to [2, 4, 6]
});
```
```
async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
setImmediate(function () {
obj[key] = val * 2;
callback();
})
}, function (err, result) {
// result is equal to {a: 2, b: 4, c: 6}
})
```
Source: [transform.js](https://caolan.github.io/async/v3/transform.js.html), [line 6](https://caolan.github.io/async/v3/transform.js.html#line6) Control Flow
============
A collection of `async` functions for controlling the flow through a script.
Source: [index.js](https://caolan.github.io/async/v3/index.js.html), [line 56](https://caolan.github.io/async/v3/index.js.html#line56) Methods
-------
###
(static) applyEach(fns, …argsopt, callbackopt) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import applyEach from 'async/applyEach';
```
Applies the provided arguments to each function in the array, calling `callback` after all functions have completed. If you only provide the first argument, `fns`, then it will return a function which lets you pass in the arguments as if it were a single function call. If more arguments are provided, `callback` is required while `args` is still optional. The results for each of the applied async functions are passed to the final callback as an array.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fns` | Array | Iterable | AsyncIterable | Object | A collection of [AsyncFunction](https://caolan.github.io/async/v3/global.html)s to all call with the same arguments |
| `args` | \* <optional> | any number of separate arguments to pass to the function. |
| `callback` | function <optional> | the final argument should be the callback, called when all functions have completed processing. |
#### Returns:
* Returns a function that takes no args other than an optional callback, that is the result of applying the `args` to each of the functions.
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) #### Example
```
const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')
appliedFn((err, results) => {
// results[0] is the results for `enableSearch`
// results[1] is the results for `updateSchema`
});
// partial application example:
async.each(
buckets,
async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),
callback
);
```
Source: [applyEach.js](https://caolan.github.io/async/v3/applyEach.js.html), [line 4](https://caolan.github.io/async/v3/applyEach.js.html#line4) ###
(static) applyEachSeries(fns, …argsopt, callbackopt) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import applyEachSeries from 'async/applyEachSeries';
```
The same as [`applyEach`](#applyEach) but runs only a single async operation at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fns` | Array | Iterable | AsyncIterable | Object | A collection of [AsyncFunction](https://caolan.github.io/async/v3/global.html)s to all call with the same arguments |
| `args` | \* <optional> | any number of separate arguments to pass to the function. |
| `callback` | function <optional> | the final argument should be the callback, called when all functions have completed processing. |
#### Returns:
* A function, that when called, is the result of appling the `args` to the list of functions. It takes no args, other than a callback.
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) Source: [applyEachSeries.js](https://caolan.github.io/async/v3/applyEachSeries.js.html), [line 4](https://caolan.github.io/async/v3/applyEachSeries.js.html#line4) See: [async.applyEach](#applyEach)
###
(static) auto(tasks, concurrencyopt, callbackopt) → {Promise}
```
import auto from 'async/auto';
```
Determines the best order for running the [AsyncFunction](https://caolan.github.io/async/v3/global.html)s in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied.
If any of the [AsyncFunction](https://caolan.github.io/async/v3/global.html)s pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error.
[AsyncFunction](https://caolan.github.io/async/v3/global.html)s also receive an object containing the results of functions which have completed so far as the first argument, if they have dependencies. If a task function has no dependencies, it will only be passed a callback.
#### Parameters:
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `tasks` | Object | | An object. Each of its properties is either a function or an array of requirements, with the [AsyncFunction](https://caolan.github.io/async/v3/global.html) itself the last item in the array. The object's key of a property serves as the name of the task defined by that property, i.e. can be used when specifying requirements for other tasks. The function receives one or two arguments:* a `results` object, containing the results of the previously executed functions, only passed if the task has any dependencies,
* a `callback(err, result)` function, which must be called when finished, passing an `error` (which can be `null`) and the result of the function's execution.
|
| `concurrency` | number <optional> | Infinity | An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible. |
| `callback` | function <optional> | | An optional callback which is called when all the tasks have been completed. It receives the `err` argument if any `tasks` pass an error to their callback. Results are always returned; however, if an error occurs, no further `tasks` will be performed, and the results object will only contain partial results. Invoked with (err, results). |
#### Returns:
a promise, if a callback is not passed
Type Promise #### Example
```
async.auto({
// this function will just be passed a callback
readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
showData: ['readData', function(results, cb) {
// results.readData is the file's contents
// ...
}]
}, callback);
async.auto({
get_data: function(callback) {
console.log('in get_data');
// async code to get some data
callback(null, 'data', 'converted to array');
},
make_folder: function(callback) {
console.log('in make_folder');
// async code to create a directory to store a file in
// this is run at the same time as getting the data
callback(null, 'folder');
},
write_file: ['get_data', 'make_folder', function(results, callback) {
console.log('in write_file', JSON.stringify(results));
// once there is some data and the directory exists,
// write the data to a file in the directory
callback(null, 'filename');
}],
email_link: ['write_file', function(results, callback) {
console.log('in email_link', JSON.stringify(results));
// once the file is written let's email a link to it...
// results.write_file contains the filename returned by write_file.
callback(null, {'file':results.write_file, 'email':'[email protected]'});
}]
}, function(err, results) {
console.log('err = ', err);
console.log('results = ', results);
});
```
Source: [auto.js](https://caolan.github.io/async/v3/auto.js.html), [line 6](https://caolan.github.io/async/v3/auto.js.html#line6) ###
(static) autoInject(tasks, callbackopt) → {Promise}
```
import autoInject from 'async/autoInject';
```
A dependency-injected version of the [async.auto](#auto) function. Dependent tasks are specified as parameters to the function, after the usual callback parameter, with the parameter names matching the names of the tasks it depends on. This can provide even more readable task graphs which can be easier to maintain.
If a final callback is specified, the task results are similarly injected, specified as named parameters after the initial error parameter.
The autoInject function is purely syntactic sugar and its semantics are otherwise equivalent to [async.auto](#auto).
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Object | An object, each of whose properties is an [AsyncFunction](https://caolan.github.io/async/v3/global.html) of the form 'func([dependencies...], callback). The object's key of a property serves as the name of the task defined by that property, i.e. can be used when specifying requirements for other tasks.* The `callback` parameter is a `callback(err, result)` which must be called when finished, passing an `error` (which can be `null`) and the result of the function's execution. The remaining parameters name other tasks on which the task is dependent, and the results from those tasks are the arguments of those parameters.
|
| `callback` | function <optional> | An optional callback which is called when all the tasks have been completed. It receives the `err` argument if any `tasks` pass an error to their callback, and a `results` object with any completed task results, similar to `auto`. |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
// The example from `auto` can be rewritten as follows:
async.autoInject({
get_data: function(callback) {
// async code to get some data
callback(null, 'data', 'converted to array');
},
make_folder: function(callback) {
// async code to create a directory to store a file in
// this is run at the same time as getting the data
callback(null, 'folder');
},
write_file: function(get_data, make_folder, callback) {
// once there is some data and the directory exists,
// write the data to a file in the directory
callback(null, 'filename');
},
email_link: function(write_file, callback) {
// once the file is written let's email a link to it...
// write_file contains the filename returned by write_file.
callback(null, {'file':write_file, 'email':'[email protected]'});
}
}, function(err, results) {
console.log('err = ', err);
console.log('email_link = ', results.email_link);
});
// If you are using a JS minifier that mangles parameter names, `autoInject`
// will not work with plain functions, since the parameter names will be
// collapsed to a single letter identifier. To work around this, you can
// explicitly specify the names of the parameters your task function needs
// in an array, similar to Angular.js dependency injection.
// This still has an advantage over plain `auto`, since the results a task
// depends on are still spread into arguments.
async.autoInject({
//...
write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
callback(null, 'filename');
}],
email_link: ['write_file', function(write_file, callback) {
callback(null, {'file':write_file, 'email':'[email protected]'});
}]
//...
}, function(err, results) {
console.log('err = ', err);
console.log('email_link = ', results.email_link);
});
```
Source: [autoInject.js](https://caolan.github.io/async/v3/autoInject.js.html), [line 25](https://caolan.github.io/async/v3/autoInject.js.html#line25) See: [async.auto](#auto)
###
(static) cargo(worker, payloadopt) → {[QueueObject](#QueueObject)}
```
import cargo from 'async/cargo';
```
Creates a `cargo` object with the specified payload. Tasks added to the cargo will be processed altogether (up to the `payload` limit). If the `worker` is in progress, the task is queued until it becomes available. Once the `worker` has completed some tasks, each callback of those tasks is called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work.
While [`queue`](#queue) passes only one task to one of a group of workers at a time, cargo passes an array of tasks to a single worker, repeating when the worker is finished.
#### Parameters:
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `worker` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | | An asynchronous function for processing an array of queued tasks. Invoked with `(tasks, callback)`. |
| `payload` | number <optional> | Infinity | An optional `integer` for determining how many tasks should be processed per round; if omitted, the default is unlimited. |
#### Returns:
A cargo object to manage the tasks. Callbacks can attached as certain properties to listen for specific events during the lifecycle of the cargo and inner queue.
Type [QueueObject](#QueueObject) #### Example
```
// create a cargo object with payload 2
var cargo = async.cargo(function(tasks, callback) {
for (var i=0; i<tasks.length; i++) {
console.log('hello ' + tasks[i].name);
}
callback();
}, 2);
// add some items
cargo.push({name: 'foo'}, function(err) {
console.log('finished processing foo');
});
cargo.push({name: 'bar'}, function(err) {
console.log('finished processing bar');
});
await cargo.push({name: 'baz'});
console.log('finished processing baz');
```
Source: [cargo.js](https://caolan.github.io/async/v3/cargo.js.html), [line 3](https://caolan.github.io/async/v3/cargo.js.html#line3) See: [async.queue](#queue)
###
(static) cargoQueue(worker, concurrencyopt, payloadopt) → {[QueueObject](#QueueObject)}
```
import cargoQueue from 'async/cargoQueue';
```
Creates a `cargoQueue` object with the specified payload. Tasks added to the cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers. If the all `workers` are in progress, the task is queued until one becomes available. Once a `worker` has completed some tasks, each callback of those tasks is called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work.
While [`queue`](#queue) passes only one task to one of a group of workers at a time, and [`cargo`](#cargo) passes an array of tasks to a single worker, the cargoQueue passes an array of tasks to multiple parallel workers.
#### Parameters:
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `worker` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | | An asynchronous function for processing an array of queued tasks. Invoked with `(tasks, callback)`. |
| `concurrency` | number <optional> | 1 | An `integer` for determining how many `worker` functions should be run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. |
| `payload` | number <optional> | Infinity | An optional `integer` for determining how many tasks should be processed per round; if omitted, the default is unlimited. |
#### Returns:
A cargoQueue object to manage the tasks. Callbacks can attached as certain properties to listen for specific events during the lifecycle of the cargoQueue and inner queue.
Type [QueueObject](#QueueObject) #### Example
```
// create a cargoQueue object with payload 2 and concurrency 2
var cargoQueue = async.cargoQueue(function(tasks, callback) {
for (var i=0; i<tasks.length; i++) {
console.log('hello ' + tasks[i].name);
}
callback();
}, 2, 2);
// add some items
cargoQueue.push({name: 'foo'}, function(err) {
console.log('finished processing foo');
});
cargoQueue.push({name: 'bar'}, function(err) {
console.log('finished processing bar');
});
cargoQueue.push({name: 'baz'}, function(err) {
console.log('finished processing baz');
});
cargoQueue.push({name: 'boo'}, function(err) {
console.log('finished processing boo');
});
```
Source: [cargoQueue.js](https://caolan.github.io/async/v3/cargoQueue.js.html), [line 3](https://caolan.github.io/async/v3/cargoQueue.js.html#line3) See: [async.queue](#queue)
async.cargo
###
(static) compose(…functions) → {function}
```
import compose from 'async/compose';
```
Creates a function which is a composition of the passed asynchronous functions. Each function consumes the return value of the function that follows. Composing functions `f()`, `g()`, and `h()` would produce the result of `f(g(h()))`, only this version uses callbacks to obtain the return values.
If the last argument to the composed function is not a function, a promise is returned when you call it.
Each function is executed with the `this` binding of the composed function.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `functions` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | the asynchronous functions to compose |
#### Returns:
an asynchronous function that is the composed asynchronous `functions`
Type function #### Example
```
function add1(n, callback) {
setTimeout(function () {
callback(null, n + 1);
}, 10);
}
function mul3(n, callback) {
setTimeout(function () {
callback(null, n * 3);
}, 10);
}
var add1mul3 = async.compose(mul3, add1);
add1mul3(4, function (err, result) {
// result now equals 15
});
```
Source: [compose.js](https://caolan.github.io/async/v3/compose.js.html), [line 3](https://caolan.github.io/async/v3/compose.js.html#line3) ###
(static) doUntil(iteratee, test, callbackopt) → {Promise}
```
import doUntil from 'async/doUntil';
```
Like ['doWhilst'](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function which is called each time `test` fails. Invoked with (callback). |
| `test` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | asynchronous truth test to perform after each execution of `iteratee`. Invoked with (...args, callback), where `...args` are the non-error args from the previous callback of `iteratee` |
| `callback` | function <optional> | A callback which is called after the test function has passed and repeated execution of `iteratee` has stopped. `callback` will be passed an error and any arguments passed to the final `iteratee`'s callback. Invoked with (err, [results]); |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [doUntil.js](https://caolan.github.io/async/v3/doUntil.js.html), [line 4](https://caolan.github.io/async/v3/doUntil.js.html#line4) See: [async.doWhilst](#doWhilst)
###
(static) doWhilst(iteratee, test, callbackopt) → {Promise}
```
import doWhilst from 'async/doWhilst';
```
The post-check version of [`whilst`](#whilst). To reflect the difference in the order of operations, the arguments `test` and `iteratee` are switched.
`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | A function which is called each time `test` passes. Invoked with (callback). |
| `test` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | asynchronous truth test to perform after each execution of `iteratee`. Invoked with (...args, callback), where `...args` are the non-error args from the previous callback of `iteratee`. |
| `callback` | function <optional> | A callback which is called after the test function has failed and repeated execution of `iteratee` has stopped. `callback` will be passed an error and any arguments passed to the final `iteratee`'s callback. Invoked with (err, [results]); |
#### Returns:
a promise, if no callback is passed
Type Promise Source: [doWhilst.js](https://caolan.github.io/async/v3/doWhilst.js.html), [line 5](https://caolan.github.io/async/v3/doWhilst.js.html#line5) See: [async.whilst](#whilst)
###
(static) forever(fn, errbackopt) → {Promise}
```
import forever from 'async/forever';
```
Calls the asynchronous function `fn` with a callback parameter that allows it to call itself again, in series, indefinitely. If an error is passed to the callback then `errback` is called with the error, and execution stops, otherwise it will never be called.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fn` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | an async function to call repeatedly. Invoked with (next). |
| `errback` | function <optional> | when `fn` passes an error to it's callback, this function will be called, and execution stops. Invoked with (err). |
#### Returns:
a promise that rejects if an error occurs and an errback is not passed
Type Promise #### Example
```
async.forever(
function(next) {
// next is suitable for passing to things that need a callback(err [, whatever]);
// it will result in this function being called again.
},
function(err) {
// if next is called with a value in its first parameter, it will appear
// in here as 'err', and execution will stop.
}
);
```
Source: [forever.js](https://caolan.github.io/async/v3/forever.js.html), [line 6](https://caolan.github.io/async/v3/forever.js.html#line6) ###
(static) parallel(tasks, callbackopt) → {Promise}
```
import parallel from 'async/parallel';
```
Run the `tasks` collection of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main `callback` is immediately called with the value of the error. Once the `tasks` have completed, the results are passed to the final `callback` as an array.
**Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded.
**Hint:** Use [`reflect`](#reflect) to continue the execution of other tasks when a task fails.
It is also possible to use an object instead of an array. Each property will be run as a function and the results will be passed to the final `callback` as an object instead of an array. This can be a more readable way of handling results from async.parallel.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Array | Iterable | AsyncIterable | Object | A collection of [async functions](https://caolan.github.io/async/v3/global.html) to run. Each async function can complete with any number of optional `result` values. |
| `callback` | function <optional> | An optional callback to run once all the functions have completed successfully. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. Invoked with (err, results). |
#### Returns:
a promise, if a callback is not passed
Type Promise #### Example
```
async.parallel([
function(callback) {
setTimeout(function() {
callback(null, 'one');
}, 200);
},
function(callback) {
setTimeout(function() {
callback(null, 'two');
}, 100);
}
],
// optional callback
function(err, results) {
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
});
// an example using an object instead of an array
async.parallel({
one: function(callback) {
setTimeout(function() {
callback(null, 1);
}, 200);
},
two: function(callback) {
setTimeout(function() {
callback(null, 2);
}, 100);
}
}, function(err, results) {
// results is now equals to: {one: 1, two: 2}
});
```
Source: [parallel.js](https://caolan.github.io/async/v3/parallel.js.html), [line 4](https://caolan.github.io/async/v3/parallel.js.html#line4) ###
(static) parallelLimit(tasks, limit, callbackopt) → {Promise}
```
import parallelLimit from 'async/parallelLimit';
```
The same as [`parallel`](#parallel) but runs a maximum of `limit` async operations at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Array | Iterable | AsyncIterable | Object | A collection of [async functions](https://caolan.github.io/async/v3/global.html) to run. Each async function can complete with any number of optional `result` values. |
| `limit` | number | The maximum number of async operations at a time. |
| `callback` | function <optional> | An optional callback to run once all the functions have completed successfully. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. Invoked with (err, results). |
#### Returns:
a promise, if a callback is not passed
Type Promise Source: [parallelLimit.js](https://caolan.github.io/async/v3/parallelLimit.js.html), [line 4](https://caolan.github.io/async/v3/parallelLimit.js.html#line4) See: [async.parallel](#parallel)
###
(static) priorityQueue(worker, concurrency) → {[QueueObject](#QueueObject)}
```
import priorityQueue from 'async/priorityQueue';
```
The same as [async.queue](#queue) only tasks are assigned a priority and completed in ascending priority order.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `worker` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function for processing a queued task. If you want to handle errors from an individual task, pass a callback to `q.push()`. Invoked with (task, callback). |
| `concurrency` | number | An `integer` for determining how many `worker` functions should be run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. |
#### Returns:
A priorityQueue object to manage the tasks. There are two differences between `queue` and `priorityQueue` objects:
* `push(task, priority, [callback])` - `priority` should be a number. If an array of `tasks` is given, all tasks will be assigned the same priority.
* The `unshift` method was removed.
Type [QueueObject](#QueueObject) Source: [priorityQueue.js](https://caolan.github.io/async/v3/priorityQueue.js.html), [line 5](https://caolan.github.io/async/v3/priorityQueue.js.html#line5) See: [async.queue](#queue)
###
(static) queue(worker, concurrencyopt) → {[QueueObject](#QueueObject)}
```
import queue from 'async/queue';
```
Creates a `queue` object with the specified `concurrency`. Tasks added to the `queue` are processed in parallel (up to the `concurrency` limit). If all `worker`s are in progress, the task is queued until one becomes available. Once a `worker` completes a `task`, that `task`'s callback is called.
#### Parameters:
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `worker` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | | An async function for processing a queued task. If you want to handle errors from an individual task, pass a callback to `q.push()`. Invoked with (task, callback). |
| `concurrency` | number <optional> | 1 | An `integer` for determining how many `worker` functions should be run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. |
#### Returns:
A queue object to manage the tasks. Callbacks can be attached as certain properties to listen for specific events during the lifecycle of the queue.
Type [QueueObject](#QueueObject) #### Example
```
// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
console.log('hello ' + task.name);
callback();
}, 2);
// assign a callback
q.drain(function() {
console.log('all items have been processed');
});
// or await the end
await q.drain()
// assign an error callback
q.error(function(err, task) {
console.error('task experienced an error');
});
// add some items to the queue
q.push({name: 'foo'}, function(err) {
console.log('finished processing foo');
});
// callback is optional
q.push({name: 'bar'});
// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
console.log('finished processing item');
});
// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
```
Source: [queue.js](https://caolan.github.io/async/v3/queue.js.html), [line 89](https://caolan.github.io/async/v3/queue.js.html#line89) ###
(static) race(tasks, callback)
```
import race from 'async/race';
```
Runs the `tasks` array of functions in parallel, without waiting until the previous function has completed. Once any of the `tasks` complete or pass an error to its callback, the main `callback` is immediately called. It's equivalent to `Promise.race()`.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Array | An array containing [async functions](https://caolan.github.io/async/v3/global.html) to run. Each function can complete with an optional `result` value. |
| `callback` | function | A callback to run once any of the functions have completed. This function gets an error or result from the first function that completed. Invoked with (err, result). |
#### Returns:
undefined
#### Example
```
async.race([
function(callback) {
setTimeout(function() {
callback(null, 'one');
}, 200);
},
function(callback) {
setTimeout(function() {
callback(null, 'two');
}, 100);
}
],
// main callback
function(err, result) {
// the result will be equal to 'two' as it finishes earlier
});
```
Source: [race.js](https://caolan.github.io/async/v3/race.js.html), [line 5](https://caolan.github.io/async/v3/race.js.html#line5) ###
(static) retry(optsopt, task, callbackopt) → {Promise}
```
import retry from 'async/retry';
```
Attempts to get a successful response from `task` no more than `times` times before returning an error. If the task is successful, the `callback` will be passed the result of the successful task. If all attempts fail, the callback will be passed the error and result (if any) of the final attempt.
#### Parameters:
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `opts` | Object | number <optional> | {times: 5, interval: 0}| 5 | Can be either an object with `times` and `interval` or a number.* `times` - The number of attempts to make before giving up. The default is `5`.
* `interval` - The time to wait between retries, in milliseconds. The default is `0`. The interval may also be specified as a function of the retry count (see example).
* `errorFilter` - An optional synchronous function that is invoked on erroneous result. If it returns `true` the retry attempts will continue; if the function returns `false` the retry flow is aborted with the current attempt's error and result being returned to the final callback. Invoked with (err).
* If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`.
|
| `task` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | | An async function to retry. Invoked with (callback). |
| `callback` | function <optional> | | An optional callback which is called when the task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. Invoked with (err, results). |
#### Returns:
a promise if no callback provided
Type Promise #### Example
```
// The `retry` function can be used as a stand-alone control flow by passing
// a callback, as shown below:
// try calling apiMethod 3 times
async.retry(3, apiMethod, function(err, result) {
// do something with the result
});
// try calling apiMethod 3 times, waiting 200 ms between each retry
async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
// do something with the result
});
// try calling apiMethod 10 times with exponential backoff
// (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
async.retry({
times: 10,
interval: function(retryCount) {
return 50 * Math.pow(2, retryCount);
}
}, apiMethod, function(err, result) {
// do something with the result
});
// try calling apiMethod the default 5 times no delay between each retry
async.retry(apiMethod, function(err, result) {
// do something with the result
});
// try calling apiMethod only when error condition satisfies, all other
// errors will abort the retry control flow and return to final callback
async.retry({
errorFilter: function(err) {
return err.message === 'Temporary error'; // only retry on a specific error
}
}, apiMethod, function(err, result) {
// do something with the result
});
// to retry individual methods that are not as reliable within other
// control flow functions, use the `retryable` wrapper:
async.auto({
users: api.getUsers.bind(api),
payments: async.retryable(3, api.getPayments.bind(api))
}, function(err, results) {
// do something with the results
});
```
Source: [retry.js](https://caolan.github.io/async/v3/retry.js.html), [line 10](https://caolan.github.io/async/v3/retry.js.html#line10) See: [async.retryable](#retryable)
###
(static) retryable(optsopt, task) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import retryable from 'async/retryable';
```
A close relative of [`retry`](#retry). This method wraps a task and makes it retryable, rather than immediately calling it with retries.
#### Parameters:
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `opts` | Object | number <optional> | {times: 5, interval: 0}| 5 | optional options, exactly the same as from `retry`, except for a `opts.arity` that is the arity of the `task` function, defaulting to `task.length` |
| `task` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | | the asynchronous function to wrap. This function will be passed any arguments passed to the returned wrapper. Invoked with (...args, callback). |
#### Returns:
The wrapped function, which when invoked, will retry on an error, based on the parameters specified in `opts`. This function will accept the same parameters as `task`.
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) #### Example
```
async.auto({
dep1: async.retryable(3, getFromFlakyService),
process: ["dep1", async.retryable(3, function (results, cb) {
maybeProcessData(results.dep1, cb);
})]
}, callback);
```
Source: [retryable.js](https://caolan.github.io/async/v3/retryable.js.html), [line 6](https://caolan.github.io/async/v3/retryable.js.html#line6) See: [async.retry](#retry)
###
(static) seq(…functions) → {function}
```
import seq from 'async/seq';
```
Version of the compose function that is more natural to read. Each function consumes the return value of the previous function. It is the equivalent of [compose](#compose) with the arguments reversed.
Each function is executed with the `this` binding of the composed function.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `functions` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | the asynchronous functions to compose |
#### Returns:
a function that composes the `functions` in order
Type function #### Example
```
// Requires lodash (or underscore), express3 and dresende's orm2.
// Part of an app, that fetches cats of the logged user.
// This example uses `seq` function to avoid overnesting and error
// handling clutter.
app.get('/cats', function(request, response) {
var User = request.models.User;
async.seq(
_.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
function(user, fn) {
user.getCats(fn); // 'getCats' has signature (callback(err, data))
}
)(req.session.user_id, function (err, cats) {
if (err) {
console.error(err);
response.json({ status: 'error', message: err.message });
} else {
response.json({ status: 'ok', message: 'Cats found', data: cats });
}
});
});
```
Source: [seq.js](https://caolan.github.io/async/v3/seq.js.html), [line 5](https://caolan.github.io/async/v3/seq.js.html#line5) See: [async.compose](#compose)
###
(static) series(tasks, callbackopt) → {Promise}
```
import series from 'async/series';
```
Run the functions in the `tasks` collection in series, each one running once the previous function has completed. If any functions in the series pass an error to its callback, no more functions are run, and `callback` is immediately called with the value of the error. Otherwise, `callback` receives an array of results when `tasks` have completed.
It is also possible to use an object instead of an array. Each property will be run as a function, and the results will be passed to the final `callback` as an object instead of an array. This can be a more readable way of handling results from async.series.
**Note** that while many implementations preserve the order of object properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) explicitly states that
> The mechanics and order of enumerating the properties is not specified.
>
>
So if you rely on the order in which your series of functions are executed, and want this to work on all platforms, consider using an array.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Array | Iterable | AsyncIterable | Object | A collection containing [async functions](https://caolan.github.io/async/v3/global.html) to run in series. Each function can complete with any number of optional `result` values. |
| `callback` | function <optional> | An optional callback to run once all the functions have completed. This function gets a results array (or object) containing all the result arguments passed to the `task` callbacks. Invoked with (err, result). |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
async.series([
function(callback) {
// do some stuff ...
callback(null, 'one');
},
function(callback) {
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results) {
// results is now equal to ['one', 'two']
});
async.series({
one: function(callback) {
setTimeout(function() {
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function() {
callback(null, 2);
}, 100);
}
}, function(err, results) {
// results is now equal to: {one: 1, two: 2}
});
```
Source: [series.js](https://caolan.github.io/async/v3/series.js.html), [line 4](https://caolan.github.io/async/v3/series.js.html#line4) ###
(static) times(n, iteratee, callback) → {Promise}
```
import times from 'async/times';
```
Calls the `iteratee` function `n` times, and accumulates results in the same manner you would use with [map](#map).
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `n` | number | The number of times to run the function. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The async function to call `n` times. Invoked with the iteration index and a callback: (n, next). |
| `callback` | function | see [map](#map). |
#### Returns:
a promise, if no callback is provided
Type Promise #### Example
```
// Pretend this is some complicated async factory
var createUser = function(id, callback) {
callback(null, {
id: 'user' + id
});
};
// generate 5 users
async.times(5, function(n, next) {
createUser(n, function(err, user) {
next(err, user);
});
}, function(err, users) {
// we should now have 5 users
});
```
Source: [times.js](https://caolan.github.io/async/v3/times.js.html), [line 3](https://caolan.github.io/async/v3/times.js.html#line3) See: [async.map](#map)
###
(static) timesLimit(count, limit, iteratee, callback) → {Promise}
```
import timesLimit from 'async/timesLimit';
```
The same as [times](#times) but runs a maximum of `limit` async operations at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `count` | number | The number of times to run the function. |
| `limit` | number | The maximum number of async operations at a time. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The async function to call `n` times. Invoked with the iteration index and a callback: (n, next). |
| `callback` | function | see [async.map](#map). |
#### Returns:
a promise, if no callback is provided
Type Promise Source: [timesLimit.js](https://caolan.github.io/async/v3/timesLimit.js.html), [line 5](https://caolan.github.io/async/v3/timesLimit.js.html#line5) See: [async.times](#times)
###
(static) timesSeries(n, iteratee, callback) → {Promise}
```
import timesSeries from 'async/timesSeries';
```
The same as [times](#times) but runs only a single async operation at a time.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `n` | number | The number of times to run the function. |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The async function to call `n` times. Invoked with the iteration index and a callback: (n, next). |
| `callback` | function | see [map](#map). |
#### Returns:
a promise, if no callback is provided
Type Promise Source: [timesSeries.js](https://caolan.github.io/async/v3/timesSeries.js.html), [line 3](https://caolan.github.io/async/v3/timesSeries.js.html#line3) See: [async.times](#times)
###
(static) tryEach(tasks, callbackopt) → {Promise}
```
import tryEach from 'async/tryEach';
```
It runs each task in series but stops whenever any of the functions were successful. If one of the tasks were successful, the `callback` will be passed the result of the successful task. If all tasks fail, the callback will be passed the error and result (if any) of the final attempt.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Array | Iterable | AsyncIterable | Object | A collection containing functions to run, each function is passed a `callback(err, result)` it must call on completion with an error `err` (which can be `null`) and an optional `result` value. |
| `callback` | function <optional> | An optional callback which is called when one of the tasks has succeeded, or all have failed. It receives the `err` and `result` arguments of the last attempt at completing the `task`. Invoked with (err, results). |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
async.tryEach([
function getDataFromFirstWebsite(callback) {
// Try getting the data from the first website
callback(err, data);
},
function getDataFromSecondWebsite(callback) {
// First website failed,
// Try getting the data from the backup website
callback(err, data);
}
],
// optional callback
function(err, results) {
Now do something with the data.
});
```
Source: [tryEach.js](https://caolan.github.io/async/v3/tryEach.js.html), [line 5](https://caolan.github.io/async/v3/tryEach.js.html#line5) ###
(static) until(test, iteratee, callbackopt) → {Promise}
```
import until from 'async/until';
```
Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when stopped, or an error occurs. `callback` will be passed an error and any arguments passed to the final `iteratee`'s callback.
The inverse of [whilst](#whilst).
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `test` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | asynchronous truth test to perform before each execution of `iteratee`. Invoked with (callback). |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function which is called each time `test` fails. Invoked with (callback). |
| `callback` | function <optional> | A callback which is called after the test function has passed and repeated execution of `iteratee` has stopped. `callback` will be passed an error and any arguments passed to the final `iteratee`'s callback. Invoked with (err, [results]); |
#### Returns:
a promise, if a callback is not passed
Type Promise #### Example
```
const results = []
let finished = false
async.until(function test(page, cb) {
cb(null, finished)
}, function iter(next) {
fetchPage(url, (err, body) => {
if (err) return next(err)
results = results.concat(body.objects)
finished = !!body.next
next(err)
})
}, function done (err) {
// all pages have been fetched
})
```
Source: [until.js](https://caolan.github.io/async/v3/until.js.html), [line 4](https://caolan.github.io/async/v3/until.js.html#line4) See: [async.whilst](#whilst)
###
(static) waterfall(tasks, callbackopt)
```
import waterfall from 'async/waterfall';
```
Runs the `tasks` array of functions in series, each passing their results to the next in the array. However, if any of the `tasks` pass an error to their own callback, the next function is not executed, and the main `callback` is immediately called with the error.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Array | An array of [async functions](https://caolan.github.io/async/v3/global.html) to run. Each function should complete with any number of `result` values. The `result` values will be passed as arguments, in order, to the next task. |
| `callback` | function <optional> | An optional callback to run once all the functions have completed. This will be passed the results of the last task's callback. Invoked with (err, [results]). |
#### Returns:
undefined
#### Example
```
async.waterfall([
function(callback) {
callback(null, 'one', 'two');
},
function(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
// Or, with named functions:
async.waterfall([
myFirstFunction,
mySecondFunction,
myLastFunction,
], function (err, result) {
// result now equals 'done'
});
function myFirstFunction(callback) {
callback(null, 'one', 'two');
}
function mySecondFunction(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
}
function myLastFunction(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
```
Source: [waterfall.js](https://caolan.github.io/async/v3/waterfall.js.html), [line 7](https://caolan.github.io/async/v3/waterfall.js.html#line7) ###
(static) whilst(test, iteratee, callbackopt) → {Promise}
```
import whilst from 'async/whilst';
```
Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when stopped, or an error occurs.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `test` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | asynchronous truth test to perform before each execution of `iteratee`. Invoked with (). |
| `iteratee` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | An async function which is called each time `test` passes. Invoked with (callback). |
| `callback` | function <optional> | A callback which is called after the test function has failed and repeated execution of `iteratee` has stopped. `callback` will be passed an error and any arguments passed to the final `iteratee`'s callback. Invoked with (err, [results]); |
#### Returns:
a promise, if no callback is passed
Type Promise #### Example
```
var count = 0;
async.whilst(
function test(cb) { cb(null, count < 5); },
function iter(callback) {
count++;
setTimeout(function() {
callback(null, count);
}, 1000);
},
function (err, n) {
// 5 seconds have passed, n = 5
}
);
```
Source: [whilst.js](https://caolan.github.io/async/v3/whilst.js.html), [line 5](https://caolan.github.io/async/v3/whilst.js.html#line5) Type Definitions
----------------
### QueueObject
```
import queue from 'async/queue';
```
A queue of tasks for the worker function to complete.
#### Type:
* Iterable
#### Properties:
| Name | Type | Description |
| --- | --- | --- |
| `length` | function | a function returning the number of items waiting to be processed. Invoke with `queue.length()`. |
| `started` | boolean | a boolean indicating whether or not any items have been pushed and processed by the queue. |
| `running` | function | a function returning the number of items currently being processed. Invoke with `queue.running()`. |
| `workersList` | function | a function returning the array of items currently being processed. Invoke with `queue.workersList()`. |
| `idle` | function | a function returning false if there are items waiting or being processed, or true if not. Invoke with `queue.idle()`. |
| `concurrency` | number | an integer for determining how many `worker` functions should be run in parallel. This property can be changed after a `queue` is created to alter the concurrency on-the-fly. |
| `payload` | number | an integer that specifies how many items are passed to the worker function at a time. only applies if this is a [cargo](#cargo) object |
| `push` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | add a new task to the `queue`. Calls `callback` once the `worker` has finished processing the task. Instead of a single task, a `tasks` array can be submitted. The respective callback is used for every task in the list. Invoke with `queue.push(task, [callback])`, |
| `unshift` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | add a new task to the front of the `queue`. Invoke with `queue.unshift(task, [callback])`. |
| `pushAsync` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | the same as `q.push`, except this returns a promise that rejects if an error occurs. |
| `unshirtAsync` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | the same as `q.unshift`, except this returns a promise that rejects if an error occurs. |
| `remove` | function | remove items from the queue that match a test function. The test function will be passed an object with a `data` property, and a `priority` property, if this is a [priorityQueue](#priorityQueue) object. Invoked with `queue.remove(testFn)`, where `testFn` is of the form `function ({data, priority}) {}` and returns a Boolean. |
| `saturated` | function | a function that sets a callback that is called when the number of running workers hits the `concurrency` limit, and further tasks will be queued. If the callback is omitted, `q.saturated()` returns a promise for the next occurrence. |
| `unsaturated` | function | a function that sets a callback that is called when the number of running workers is less than the `concurrency` & `buffer` limits, and further tasks will not be queued. If the callback is omitted, `q.unsaturated()` returns a promise for the next occurrence. |
| `buffer` | number | A minimum threshold buffer in order to say that the `queue` is `unsaturated`. |
| `empty` | function | a function that sets a callback that is called when the last item from the `queue` is given to a `worker`. If the callback is omitted, `q.empty()` returns a promise for the next occurrence. |
| `drain` | function | a function that sets a callback that is called when the last item from the `queue` has returned from the `worker`. If the callback is omitted, `q.drain()` returns a promise for the next occurrence. |
| `error` | function | a function that sets a callback that is called when a task errors. Has the signature `function(error, task)`. If the callback is omitted, `error()` returns a promise that rejects on the next error. |
| `paused` | boolean | a boolean for determining whether the queue is in a paused state. |
| `pause` | function | a function that pauses the processing of tasks until `resume()` is called. Invoke with `queue.pause()`. |
| `resume` | function | a function that resumes the processing of queued tasks when the queue is paused. Invoke with `queue.resume()`. |
| `kill` | function | a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. No more tasks should be pushed to the queue after calling this function. Invoke with `queue.kill()`. |
Source: [queue.js](https://caolan.github.io/async/v3/queue.js.html), [line 4](https://caolan.github.io/async/v3/queue.js.html#line4) #### Example
```
const q = async.queue(worker, 2)
q.push(item1)
q.push(item2)
q.push(item3)
// queues are iterable, spread into an array to inspect
const items = [...q] // [item1, item2, item3]
// or use for of
for (let item of q) {
console.log(item)
}
q.drain(() => {
console.log('all done')
})
// or
await q.drain()
```
Utils
=====
A collection of `async` utility functions.
Source: [index.js](https://caolan.github.io/async/v3/index.js.html), [line 61](https://caolan.github.io/async/v3/index.js.html#line61) Methods
-------
###
(static) apply(fn) → {function}
```
import apply from 'async/apply';
```
Creates a continuation function with some arguments already applied.
Useful as a shorthand when combined with other control flow functions. Any arguments passed to the returned function are added to the arguments originally passed to apply.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fn` | function | The function you want to eventually apply all arguments to. Invokes with (arguments...). |
| `arguments...` | \* | Any number of arguments to automatically apply when the continuation is called. |
#### Returns:
the partially-applied function
Type function #### Example
```
// using apply
async.parallel([
async.apply(fs.writeFile, 'testfile1', 'test1'),
async.apply(fs.writeFile, 'testfile2', 'test2')
]);
// the same process without using apply
async.parallel([
function(callback) {
fs.writeFile('testfile1', 'test1', callback);
},
function(callback) {
fs.writeFile('testfile2', 'test2', callback);
}
]);
// It's possible to pass any number of additional arguments when calling the
// continuation:
node> var fn = async.apply(sys.puts, 'one');
node> fn('two', 'three');
one
two
three
```
Source: [apply.js](https://caolan.github.io/async/v3/apply.js.html), [line 1](https://caolan.github.io/async/v3/apply.js.html#line1) ###
(static) asyncify(func) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import asyncify from 'async/asyncify';
```
Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback.
If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value.
This also means you can asyncify ES2017 `async` functions.
Alias: wrapSync #### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `func` | function | The synchronous function, or Promise-returning function to convert to an [AsyncFunction](https://caolan.github.io/async/v3/global.html). |
#### Returns:
An asynchronous wrapper of the `func`. To be invoked with `(args..., callback)`.
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) #### Example
```
// passing a regular synchronous function
async.waterfall([
async.apply(fs.readFile, filename, "utf8"),
async.asyncify(JSON.parse),
function (data, next) {
// data is the result of parsing the text.
// If there was a parsing error, it would have been caught.
}
], callback);
// passing a function returning a promise
async.waterfall([
async.apply(fs.readFile, filename, "utf8"),
async.asyncify(function (contents) {
return db.model.create(contents);
}),
function (model, next) {
// `model` is the instantiated model object.
// If there was an error, this function would be skipped.
}
], callback);
// es2017 example, though `asyncify` is not needed if your JS environment
// supports async functions out of the box
var q = async.queue(async.asyncify(async function(file) {
var intermediateStep = await processFile(file);
return await somePromise(intermediateStep)
}));
q.push(files);
```
Source: [asyncify.js](https://caolan.github.io/async/v3/asyncify.js.html), [line 5](https://caolan.github.io/async/v3/asyncify.js.html#line5) ###
(static) constant() → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import constant from 'async/constant';
```
Returns a function that when called, calls-back with the values provided. Useful as the first function in a [`waterfall`](#waterfall), or for plugging values in to [`auto`](#auto).
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `arguments...` | \* | Any number of arguments to automatically invoke callback with. |
#### Returns:
Returns a function that when invoked, automatically invokes the callback with the previous given arguments.
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) #### Example
```
async.waterfall([
async.constant(42),
function (value, next) {
// value === 42
},
//...
], callback);
async.waterfall([
async.constant(filename, "utf8"),
fs.readFile,
function (fileData, next) {
//...
}
//...
], callback);
async.auto({
hostname: async.constant("https://server.net/"),
port: findFreePort,
launchServer: ["hostname", "port", function (options, cb) {
startServer(options, cb);
}],
//...
}, callback);
```
Source: [constant.js](https://caolan.github.io/async/v3/constant.js.html), [line 1](https://caolan.github.io/async/v3/constant.js.html#line1) ###
(static) dir(function)
```
import dir from 'async/dir';
```
Logs the result of an [`async` function](https://caolan.github.io/async/v3/global.html) to the `console` using `console.dir` to display the properties of the resulting object. Only works in Node.js or in browsers that support `console.dir` and `console.error` (such as FF and Chrome). If multiple arguments are returned from the async function, `console.dir` is called on each argument in order.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `function` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The function you want to eventually apply all arguments to. |
| `arguments...` | \* | Any number of arguments to apply to the function. |
#### Example
```
// in a module
var hello = function(name, callback) {
setTimeout(function() {
callback(null, {hello: name});
}, 1000);
};
// in the node repl
node> async.dir(hello, 'world');
{hello: 'world'}
```
Source: [dir.js](https://caolan.github.io/async/v3/dir.js.html), [line 3](https://caolan.github.io/async/v3/dir.js.html#line3) ###
(static) ensureAsync(fn) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import ensureAsync from 'async/ensureAsync';
```
Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained. ES2017 `async` functions are returned as-is -- they are immune to Zalgo's corrupting influences, as they always resolve on a later tick.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fn` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | an async function, one that expects a node-style callback as its last argument. |
#### Returns:
Returns a wrapped function with the exact same call signature as the function passed in.
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) #### Example
```
function sometimesAsync(arg, callback) {
if (cache[arg]) {
return callback(null, cache[arg]); // this would be synchronous!!
} else {
doSomeIO(arg, callback); // this IO would be asynchronous
}
}
// this has a risk of stack overflows if many results are cached in a row
async.mapSeries(args, sometimesAsync, done);
// this will defer sometimesAsync's callback if necessary,
// preventing stack overflows
async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
```
Source: [ensureAsync.js](https://caolan.github.io/async/v3/ensureAsync.js.html), [line 4](https://caolan.github.io/async/v3/ensureAsync.js.html#line4) ###
(static) log(function)
```
import log from 'async/log';
```
Logs the result of an `async` function to the `console`. Only works in Node.js or in browsers that support `console.log` and `console.error` (such as FF and Chrome). If multiple arguments are returned from the async function, `console.log` is called on each argument in order.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `function` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The function you want to eventually apply all arguments to. |
| `arguments...` | \* | Any number of arguments to apply to the function. |
#### Example
```
// in a module
var hello = function(name, callback) {
setTimeout(function() {
callback(null, 'hello ' + name);
}, 1000);
};
// in the node repl
node> async.log(hello, 'world');
'hello world'
```
Source: [log.js](https://caolan.github.io/async/v3/log.js.html), [line 3](https://caolan.github.io/async/v3/log.js.html#line3) ###
(static) memoize(fn, hasher) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import memoize from 'async/memoize';
```
Caches the results of an async function. When creating a hash to store function results against, the callback is omitted from the hash and an optional hash function can be used.
**Note: if the async function errs, the result will not be cached and subsequent calls will call the wrapped function.**
If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function.
The cache of results is exposed as the `memo` property of the function returned by `memoize`.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fn` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The async function to proxy and cache results from. |
| `hasher` | function | An optional function for generating a custom hash for storing results. It has all the arguments applied to it apart from the callback, and must be synchronous. |
#### Returns:
a memoized version of `fn`
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) #### Example
```
var slow_fn = function(name, callback) {
// do something
callback(null, result);
};
var fn = async.memoize(slow_fn);
// fn can now be used as if it were slow_fn
fn('some name', function() {
// callback
});
```
Source: [memoize.js](https://caolan.github.io/async/v3/memoize.js.html), [line 5](https://caolan.github.io/async/v3/memoize.js.html#line5) ###
(static) nextTick(callback)
```
import nextTick from 'async/nextTick';
```
Calls `callback` on a later loop around the event loop. In Node.js this just calls `process.nextTick`. In the browser it will use `setImmediate` if available, otherwise `setTimeout(callback, 0)`, which means other higher priority events may precede the execution of `callback`.
This is used internally for browser-compatibility purposes.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `callback` | function | The function to call on a later loop around the event loop. Invoked with (args...). |
| `args...` | \* | any number of additional arguments to pass to the callback on the next tick. |
#### Example
```
var call_order = [];
async.nextTick(function() {
call_order.push('two');
// call_order now equals ['one','two']
});
call_order.push('one');
async.setImmediate(function (a, b, c) {
// a, b, and c equal 1, 2, and 3
}, 1, 2, 3);
```
Source: [nextTick.js](https://caolan.github.io/async/v3/nextTick.js.html), [line 5](https://caolan.github.io/async/v3/nextTick.js.html#line5) See: [async.setImmediate](#setImmediate)
###
(static) reflect(fn) → {function}
```
import reflect from 'async/reflect';
```
Wraps the async function in another function that always completes with a result object, even when it errors.
The result object has either the property `error` or `value`.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fn` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The async function you want to wrap |
#### Returns:
* A function that always passes null to it's callback as the error. The second argument to the callback will be an `object` with either an `error` or a `value` property.
Type function #### Example
```
async.parallel([
async.reflect(function(callback) {
// do some stuff ...
callback(null, 'one');
}),
async.reflect(function(callback) {
// do some more stuff but error ...
callback('bad stuff happened');
}),
async.reflect(function(callback) {
// do some more stuff ...
callback(null, 'two');
})
],
// optional callback
function(err, results) {
// values
// results[0].value = 'one'
// results[1].error = 'bad stuff happened'
// results[2].value = 'two'
});
```
Source: [reflect.js](https://caolan.github.io/async/v3/reflect.js.html), [line 4](https://caolan.github.io/async/v3/reflect.js.html#line4) ###
(static) reflectAll(tasks) → {Array}
```
import reflectAll from 'async/reflectAll';
```
A helper function that wraps an array or an object of functions with `reflect`.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `tasks` | Array | Object | Iterable | The collection of [async functions](https://caolan.github.io/async/v3/global.html) to wrap in `async.reflect`. |
#### Returns:
Returns an array of async functions, each wrapped in `async.reflect`
Type Array #### Example
```
let tasks = [
function(callback) {
setTimeout(function() {
callback(null, 'one');
}, 200);
},
function(callback) {
// do some more stuff but error ...
callback(new Error('bad stuff happened'));
},
function(callback) {
setTimeout(function() {
callback(null, 'two');
}, 100);
}
];
async.parallel(async.reflectAll(tasks),
// optional callback
function(err, results) {
// values
// results[0].value = 'one'
// results[1].error = Error('bad stuff happened')
// results[2].value = 'two'
});
// an example using an object instead of an array
let tasks = {
one: function(callback) {
setTimeout(function() {
callback(null, 'one');
}, 200);
},
two: function(callback) {
callback('two');
},
three: function(callback) {
setTimeout(function() {
callback(null, 'three');
}, 100);
}
};
async.parallel(async.reflectAll(tasks),
// optional callback
function(err, results) {
// values
// results.one.value = 'one'
// results.two.error = 'two'
// results.three.value = 'three'
});
```
Source: [reflectAll.js](https://caolan.github.io/async/v3/reflectAll.js.html), [line 3](https://caolan.github.io/async/v3/reflectAll.js.html#line3) See: [async.reflect](#reflect)
###
(static) setImmediate(callback)
```
import setImmediate from 'async/setImmediate';
```
Calls `callback` on a later loop around the event loop. In Node.js this just calls `setImmediate`. In the browser it will use `setImmediate` if available, otherwise `setTimeout(callback, 0)`, which means other higher priority events may precede the execution of `callback`.
This is used internally for browser-compatibility purposes.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `callback` | function | The function to call on a later loop around the event loop. Invoked with (args...). |
| `args...` | \* | any number of additional arguments to pass to the callback on the next tick. |
#### Example
```
var call_order = [];
async.nextTick(function() {
call_order.push('two');
// call_order now equals ['one','two']
});
call_order.push('one');
async.setImmediate(function (a, b, c) {
// a, b, and c equal 1, 2, and 3
}, 1, 2, 3);
```
Source: [setImmediate.js](https://caolan.github.io/async/v3/setImmediate.js.html), [line 3](https://caolan.github.io/async/v3/setImmediate.js.html#line3) See: [async.nextTick](#nextTick)
###
(static) timeout(asyncFn, milliseconds, infoopt) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import timeout from 'async/timeout';
```
Sets a time limit on an asynchronous function. If the function does not call its callback within the specified milliseconds, it will be called with a timeout error. The code property for the error object will be `'ETIMEDOUT'`.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `asyncFn` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | The async function to limit in time. |
| `milliseconds` | number | The specified time limit. |
| `info` | \* <optional> | Any variable you want attached (`string`, `object`, etc) to timeout Error for more information.. |
#### Returns:
Returns a wrapped function that can be used with any of the control flow functions. Invoke this function with the same parameters as you would `asyncFunc`.
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) #### Example
```
function myFunction(foo, callback) {
doAsyncTask(foo, function(err, data) {
// handle errors
if (err) return callback(err);
// do some stuff ...
// return processed data
return callback(null, data);
});
}
var wrapped = async.timeout(myFunction, 1000);
// call `wrapped` as you would `myFunction`
wrapped({ bar: 'bar' }, function(err, data) {
// if `myFunction` takes < 1000 ms to execute, `err`
// and `data` will have their expected values
// else `err` will be an Error with the code 'ETIMEDOUT'
});
```
Source: [timeout.js](https://caolan.github.io/async/v3/timeout.js.html), [line 4](https://caolan.github.io/async/v3/timeout.js.html#line4) ###
(static) unmemoize(fn) → {[AsyncFunction](https://caolan.github.io/async/v3/global.html)}
```
import unmemoize from 'async/unmemoize';
```
Undoes a [memoize](#memoize)d function, reverting it to the original, unmemoized form. Handy for testing.
#### Parameters:
| Name | Type | Description |
| --- | --- | --- |
| `fn` | [AsyncFunction](https://caolan.github.io/async/v3/global.html) | the memoized function |
#### Returns:
a function that calls the original unmemoized function
Type [AsyncFunction](https://caolan.github.io/async/v3/global.html) Source: [unmemoize.js](https://caolan.github.io/async/v3/unmemoize.js.html), [line 1](https://caolan.github.io/async/v3/unmemoize.js.html#line1) See: [async.memoize](#memoize)
| programming_docs |
phoenix Phoenix (Phoenix v1.6.11) Phoenix (Phoenix v1.6.11)
==========================
This is the documentation for the Phoenix project.
By default, Phoenix applications depend on the following packages across these categories.
General
--------
* [Ecto](https://hexdocs.pm/ecto) - a language integrated query and database wrapper
* [ExUnit](https://hexdocs.pm/ex_unit) - Elixir's built-in test framework
* [Gettext](https://hexdocs.pm/gettext) - Internationalization and localization through [`gettext`](https://www.gnu.org/software/gettext/)
* [Phoenix](https://hexdocs.pm/phoenix) - the Phoenix web framework (these docs)
* [Phoenix PubSub](https://hexdocs.pm/phoenix_pubsub) - a distributed pub/sub system with presence support
* [Phoenix HTML](https://hexdocs.pm/phoenix_html) - conveniences for working with HTML in Phoenix
* [Phoenix View](https://hexdocs.pm/phoenix_view) - a set of functions for building [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) and working with template languages such as Elixir's own [`EEx`](https://hexdocs.pm/eex/EEx.html)
* [Phoenix LiveView](https://hexdocs.pm/phoenix_live_view) - rich, real-time user experiences with server-rendered HTML
* [Phoenix LiveDashboard](https://hexdocs.pm/phoenix_live_dashboard) - real-time performance monitoring and debugging tools for Phoenix developers
* [Plug](https://hexdocs.pm/plug) - a specification and conveniences for composable modules in between web applications
* [Swoosh](https://hexdocs.pm/swoosh) - a library for composing, delivering and testing emails, also used by [`mix phx.gen.auth`](phoenix/mix.tasks.phx.gen.auth)
* [Telemetry Metrics](https://hexdocs.pm/telemetry_metrics) - common interface for defining metrics based on Telemetry events
To get started, see our [overview guides](phoenix/overview).
Summary
========
Functions
----------
[json\_library()](#json_library/0) Returns the configured JSON encoding library for Phoenix.
[plug\_init\_mode()](#plug_init_mode/0) Returns the `:plug_init_mode` that controls when plugs are initialized.
Functions
==========
### json\_library()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix.ex#L87)
Returns the configured JSON encoding library for Phoenix.
To customize the JSON library, including the following in your `config/config.exs`:
```
config :phoenix, :json_library, Jason
```
### plug\_init\_mode()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix.ex#L101)
Returns the `:plug_init_mode` that controls when plugs are initialized.
We recommend to set it to `:runtime` in development for compilation time improvements. It must be `:compile` in production (the default).
This option is passed as the `:init_mode` to [`Plug.Builder.compile/3`](https://hexdocs.pm/plug/1.13.6/Plug.Builder.html#compile/3).
phoenix Deploying on Heroku Deploying on Heroku
====================
What we'll need
----------------
The only thing we'll need for this guide is a working Phoenix application. For those of us who need a simple application to deploy, please follow the [Up and Running guide](up_and_running).
Goals
------
Our main goal for this guide is to get a Phoenix application running on Heroku.
Limitations
------------
Heroku is a great platform and Elixir performs well on it. However, you may run into limitations if you plan to leverage advanced features provided by Elixir and Phoenix, such as:
* Connections are limited.
+ Heroku [limits the number of simultaneous connections](https://devcenter.heroku.com/articles/http-routing#request-concurrency) as well as the [duration of each connection](https://devcenter.heroku.com/articles/limits#http-timeouts). It is common to use Elixir for real-time apps which need lots of concurrent, persistent connections, and Phoenix is capable of [handling over 2 million connections on a single server](https://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections).
* Distributed clustering is not possible.
+ Heroku [firewalls dynos off from one another](https://devcenter.heroku.com/articles/dynos#networking). This means things like [distributed Phoenix channels](https://dockyard.com/blog/2016/01/28/running-elixir-and-phoenix-projects-on-a-cluster-of-nodes) and [distributed tasks](https://elixir-lang.org/getting-started/mix-otp/distributed-tasks.html) will need to rely on something like Redis instead of Elixir's built-in distribution.
* In-memory state such as those in [Agents](https://elixir-lang.org/getting-started/mix-otp/agent.html), [GenServers](https://elixir-lang.org/getting-started/mix-otp/genserver.html), and [ETS](https://elixir-lang.org/getting-started/mix-otp/ets.html) will be lost every 24 hours.
+ Heroku [restarts dynos](https://devcenter.heroku.com/articles/dynos#restarting) every 24 hours regardless of whether the node is healthy.
* [The built-in observer](https://elixir-lang.org/getting-started/debugging.html#observer) can't be used with Heroku.
+ Heroku does allow for connection into your dyno, but you won't be able to use the observer to watch the state of your dyno.
If you are just getting started, or you don't expect to use the features above, Heroku should be enough for your needs. For instance, if you are migrating an existing application running on Heroku to Phoenix, keeping a similar set of features, Elixir will perform just as well or even better than your current stack.
If you want a platform-as-a-service without these limitations, try [Gigalixir](gigalixir). If you would rather deploy to a cloud platform, such as EC2, Google Cloud, etc, consider using [`mix release`](https://hexdocs.pm/mix/Mix.Tasks.Release.html).
Steps
------
Let's separate this process into a few steps, so we can keep track of where we are.
* Initialize Git repository
* Sign up for Heroku
* Install the Heroku Toolbelt
* Create and set up Heroku application
* Make our project ready for Heroku
* Deploy time!
* Useful Heroku commands
Initializing Git repository
----------------------------
[Git](https://git-scm.com/) is a popular decentralized revision control system and is also used to deploy apps to Heroku.
Before we can push to Heroku, we'll need to initialize a local Git repository and commit our files to it. We can do so by running the following commands in our project directory:
```
$ git init
$ git add .
$ git commit -m "Initial commit"
```
Heroku offers some great information on how it is using Git [here](https://devcenter.heroku.com/articles/git#tracking-your-app-in-git).
Signing up for Heroku
----------------------
Signing up to Heroku is very simple, just head over to <https://signup.heroku.com/> and fill in the form.
The Free plan will give us one web [dyno](https://devcenter.heroku.com/articles/dynos#dynos) and one worker dyno, as well as a PostgreSQL and Redis instance for free.
These are meant to be used for testing and development, and come with some limitations. In order to run a production application, please consider upgrading to a paid plan.
Installing the Heroku Toolbelt
-------------------------------
Once we have signed up, we can download the correct version of the Heroku Toolbelt for our system [here](https://toolbelt.heroku.com/).
The Heroku CLI, part of the Toolbelt, is useful to create Heroku applications, list currently running dynos for an existing application, tail logs or run one-off commands (mix tasks for instance).
Create and Set Up Heroku Application
-------------------------------------
There are two different ways to deploy a Phoenix app on Heroku. We could use Heroku buildpacks or their container stack. The difference between these two approaches is in how we tell Heroku to treat our build. In buildpack case, we need to update our apps configuration on Heroku to use Phoenix/Elixir specific buildpacks. On container approach, we have more control on how we want to set up our app, and we can define our container image using `Dockerfile` and `heroku.yml`. This section will explore the buildpack approach. In order to use Dockerfile, it is often recommended to convert our app to use releases, which we will describe later on.
### Create Application
A [buildpack](https://devcenter.heroku.com/articles/buildpacks) is a convenient way of packaging framework and/or runtime support. Phoenix requires 2 buildpacks to run on Heroku, the first adds basic Elixir support and the second adds Phoenix specific commands.
With the Toolbelt installed, let's create the Heroku application. We will do so using the latest available version of the [Elixir buildpack](https://github.com/HashNuke/heroku-buildpack-elixir):
```
$ heroku create --buildpack hashnuke/elixir
Creating app... done, ⬢ mysterious-meadow-6277
Setting buildpack to hashnuke/elixir... done
https://mysterious-meadow-6277.herokuapp.com/ | https://git.heroku.com/mysterious-meadow-6277.git
```
> Note: the first time we use a Heroku command, it may prompt us to log in. If this happens, just enter the email and password you specified during signup.
>
>
> Note: the name of the Heroku application is the random string after "Creating" in the output above (mysterious-meadow-6277). This will be unique, so expect to see a different name from "mysterious-meadow-6277".
>
>
> Note: the URL in the output is the URL to our application. If we open it in our browser now, we will get the default Heroku welcome page.
>
>
> Note: if we hadn't initialized our Git repository before we ran the `heroku create` command, we wouldn't have our Heroku remote repository properly set up at this point. We can set that up manually by running: `heroku git:remote -a [our-app-name].`
>
>
The buildpack uses a predefined Elixir and Erlang version, but to avoid surprises when deploying, it is best to explicitly list the Elixir and Erlang version we want in production to be the same we are using during development or in your continuous integration servers. This is done by creating a config file named `elixir_buildpack.config` in the root directory of your project with your target version of Elixir and Erlang:
```
# Elixir version
elixir_version=1.12.2
# Erlang version
# https://github.com/HashNuke/heroku-buildpack-elixir-otp-builds/blob/master/otp-versions
erlang_version=24.0.3
# Invoke assets.deploy defined in your mix.exs to deploy assets with esbuild
# Note we nuke the esbuild executable from the image
hook_post_compile="eval mix assets.deploy && rm -f _build/esbuild*"
```
Finally, let's tell the build pack how to start our webserver. Create a file named `Procfile` at the root of your project:
```
web: mix phx.server
```
### Optional: Node, npm, and the Phoenix Static buildpack
By default, Phoenix uses `esbuild` and manages all assets for you. However, if you are using `node` and `npm`, you will need to install the [Phoenix Static buildpack](https://github.com/gjaldon/heroku-buildpack-phoenix-static) to handle them:
```
$ heroku buildpacks:add https://github.com/gjaldon/heroku-buildpack-phoenix-static.git
Buildpack added. Next release on mysterious-meadow-6277 will use:
1. https://github.com/HashNuke/heroku-buildpack-elixir.git
2. https://github.com/gjaldon/heroku-buildpack-phoenix-static.git
```
When using this buildpack, you want to delegate all asset bundling to `npm`. So you must remove the `hook_post_compile` configuration from your `elixir_buildpack.config` and move it to the deploy script of your `assets/package.json`. Something like this:
```
{
...
"scripts": {
"deploy": "cd .. && mix assets.deploy && rm -f _build/esbuild*"
}
...
}
```
The Phoenix Static buildpack uses a predefined Node.js version, but to avoid surprises when deploying, it is best to explicitly list the Node.js version we want in production to be the same we are using during development or in your continuous integration servers. This is done by creating a config file named `phoenix_static_buildpack.config` in the root directory of your project with your target version of Node.js:
```
# Node.js version
node_version=10.20.1
```
Please refer to the [configuration section](https://github.com/gjaldon/heroku-buildpack-phoenix-static#configuration) for full details. You can make your own custom build script, but for now we will use the [default one provided](https://github.com/gjaldon/heroku-buildpack-phoenix-static/blob/master/compile).
Finally, note that since we are using multiple buildpacks, you might run into an issue where the sequence is out of order (the Elixir buildpack needs to run before the Phoenix Static buildpack). [Heroku's docs](https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app) explain this better, but you will need to make sure the Phoenix Static buildpack comes last.
Making our Project ready for Heroku
------------------------------------
Every new Phoenix project ships with a config file `config/runtime.exs` (formerly `config/prod.secret.exs`) which loads configuration and secrets from [environment variables](https://devcenter.heroku.com/articles/config-vars). This aligns well with Heroku best practices, so the only work left for us to do is to configure URLs and SSL.
First let's tell Phoenix to use our Heroku URL and enforce we only use the SSL version of the website. Also, bind to the port requested by Heroku in the [`$PORT` environment variable](https://devcenter.heroku.com/articles/runtime-principles#web-servers). Find the url line in your `config/prod.exs`:
```
url: [host: "example.com", port: 80],
```
... and replace it with this (don't forget to replace `mysterious-meadow-6277` with your application name):
```
url: [scheme: "https", host: "mysterious-meadow-6277.herokuapp.com", port: 443],
force_ssl: [rewrite_on: [:x_forwarded_proto]],
```
Then open up your `config/runtime.xs` (formerly `config/prod.secret.exs`) and uncomment the `# ssl: true,` line in your repository configuration. It will look like this:
```
config :hello, Hello.Repo,
ssl: true,
url: database_url,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
```
Finally, if you plan on using websockets, then we will need to decrease the timeout for the websocket transport in `lib/hello_web/endpoint.ex`. If you do not plan on using websockets, then leaving it set to false is fine. You can find further explanation of the options available at the [documentation](phoenix.endpoint#socket/3-websocket-configuration).
```
defmodule HelloWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :hello
socket "/socket", HelloWeb.UserSocket,
websocket: [timeout: 45_000]
...
end
```
This ensures that any idle connections are closed by Phoenix before they reach Heroku's 55-second timeout window.
Creating Environment Variables in Heroku
-----------------------------------------
The `DATABASE_URL` config var is automatically created by Heroku when we add the [Heroku Postgres add-on](https://elements.heroku.com/addons/heroku-postgresql). We can create the database via the Heroku toolbelt:
```
$ heroku addons:create heroku-postgresql:hobby-dev
```
Now we set the `POOL_SIZE` config var:
```
$ heroku config:set POOL_SIZE=18
```
This value should be just under the number of available connections, leaving a couple open for migrations and mix tasks. The hobby-dev database allows 20 connections, so we set this number to 18. If additional dynos will share the database, reduce the `POOL_SIZE` to give each dyno an equal share.
When running a mix task later (after we have pushed the project to Heroku) you will also want to limit its pool size like so:
```
$ heroku run "POOL_SIZE=2 mix hello.task"
```
So that Ecto does not attempt to open more than the available connections.
We still have to create the `SECRET_KEY_BASE` config based on a random string. First, use [`mix phx.gen.secret`](mix.tasks.phx.gen.secret) to get a new secret:
```
$ mix phx.gen.secret
xvafzY4y01jYuzLm3ecJqo008dVnU3CN4f+MamNd1Zue4pXvfvUjbiXT8akaIF53
```
Your random string will be different; don't use this example value.
Now set it in Heroku:
```
$ heroku config:set SECRET_KEY_BASE="xvafzY4y01jYuzLm3ecJqo008dVnU3CN4f+MamNd1Zue4pXvfvUjbiXT8akaIF53"
Setting config vars and restarting mysterious-meadow-6277... done, v3
SECRET_KEY_BASE: xvafzY4y01jYuzLm3ecJqo008dVnU3CN4f+MamNd1Zue4pXvfvUjbiXT8akaIF53
```
Deploy Time!
-------------
Our project is now ready to be deployed on Heroku.
Let's commit all our changes:
```
$ git add elixir_buildpack.config
$ git commit -a -m "Use production config from Heroku ENV variables and decrease socket timeout"
```
And deploy:
```
$ git push heroku master
Counting objects: 55, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (49/49), done.
Writing objects: 100% (55/55), 48.48 KiB | 0 bytes/s, done.
Total 55 (delta 1), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Multipack app detected
remote: -----> Fetching custom git buildpack... done
remote: -----> elixir app detected
remote: -----> Checking Erlang and Elixir versions
remote: WARNING: elixir_buildpack.config wasn't found in the app
remote: Using default config from Elixir buildpack
remote: Will use the following versions:
remote: * Stack cedar-14
remote: * Erlang 17.5
remote: * Elixir 1.0.4
remote: Will export the following config vars:
remote: * Config vars DATABASE_URL
remote: * MIX_ENV=prod
remote: -----> Stack changed, will rebuild
remote: -----> Fetching Erlang 17.5
remote: -----> Installing Erlang 17.5 (changed)
remote:
remote: -----> Fetching Elixir v1.0.4
remote: -----> Installing Elixir v1.0.4 (changed)
remote: -----> Installing Hex
remote: 2015-07-07 00:04:00 URL:https://s3.amazonaws.com/s3.hex.pm/installs/1.0.0/hex.ez [262010/262010] ->
"/app/.mix/archives/hex.ez" [1]
remote: * creating /app/.mix/archives/hex.ez
remote: -----> Installing rebar
remote: * creating /app/.mix/rebar
remote: -----> Fetching app dependencies with mix
remote: Running dependency resolution
remote: Dependency resolution completed successfully
remote: [...]
remote: -----> Compiling
remote: [...]
remote: Generated phoenix_heroku app
remote: [...]
remote: Consolidated protocols written to _build/prod/consolidated
remote: -----> Creating .profile.d with env vars
remote: -----> Fetching custom git buildpack... done
remote: -----> Phoenix app detected
remote:
remote: -----> Loading configuration and environment
remote: Loading config...
remote: [...]
remote: Will export the following config vars:
remote: * Config vars DATABASE_URL
remote: * MIX_ENV=prod
remote:
remote: -----> Compressing... done, 82.1MB
remote: -----> Launching... done, v5
remote: https://mysterious-meadow-6277.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/mysterious-meadow-6277.git
* [new branch] master -> master
```
Typing `heroku open` in the terminal should launch a browser with the Phoenix welcome page opened. In the event that you are using Ecto to access a database, you will also need to run migrations after the first deploy:
```
$ heroku run "POOL_SIZE=2 mix ecto.migrate"
```
And that's it!
Deploying to Heroku using the container stack
----------------------------------------------
### Create Heroku application
Set the stack of your app to `container`, this allows us to use `Dockerfile` to define our app setup.
```
$ heroku create
Creating app... done, ⬢ mysterious-meadow-6277
$ heroku stack:set container
```
Add a new `heroku.yml` file to your root folder. In this file you can define addons used by your app, how to build the image and what configs are passed to the image. You can learn more about Heroku's `heroku.yml` options [here](https://devcenter.heroku.com/articles/build-docker-images-heroku-yml). Here is a sample:
```
setup:
addons:
- plan: heroku-postgresql
as: DATABASE
build:
docker:
web: Dockerfile
config:
MIX_ENV: prod
SECRET_KEY_BASE: $SECRET_KEY_BASE
DATABASE_URL: $DATABASE_URL
```
### Set up releases and Dockerfile
Now we need to define a `Dockerfile` at the root folder of your project that contains your application. We recommend to use releases when doing so, as the release will allow us to build a container with only the parts of Erlang and Elixir we actually use. Follow the [releases docs](releases). At the end of the guide, there is a sample Dockerfile file you can use.
Once you have the image definition set up, you can push your app to heroku and you can see it starts building the image and deploy it.
Useful Heroku Commands
-----------------------
We can look at the logs of our application by running the following command in our project directory:
```
$ heroku logs # use --tail if you want to tail them
```
We can also start an IEx session attached to our terminal for experimenting in our app's environment:
```
$ heroku run "POOL_SIZE=2 iex -S mix"
```
In fact, we can run anything using the `heroku run` command, like the Ecto migration task from above:
```
$ heroku run "POOL_SIZE=2 mix ecto.migrate"
```
Connecting to your dyno
------------------------
Heroku gives you the ability to connect to your dyno with an IEx shell which allows running Elixir code such as database queries.
* Modify the `web` process in your Procfile to run a named node:
```
web: elixir --sname server -S mix phx.server
```
* Redeploy to Heroku
* Connect to the dyno with `heroku ps:exec` (if you have several applications on the same repository you will need to specify the app name or the remote name with `--app APP_NAME` or `--remote REMOTE_NAME`)
* Launch an iex session with `iex --sname console --remsh server`
You have an iex session into your dyno!
Troubleshooting
----------------
### Compilation Error
Occasionally, an application will compile locally, but not on Heroku. The compilation error on Heroku will look something like this:
```
remote: == Compilation error on file lib/postgrex/connection.ex ==
remote: could not compile dependency :postgrex, "mix compile" failed. You can recompile this dependency with "mix deps.compile postgrex", update it with "mix deps.update postgrex" or clean it with "mix deps.clean postgrex"
remote: ** (CompileError) lib/postgrex/connection.ex:207: Postgrex.Connection.__struct__/0 is undefined, cannot expand struct Postgrex.Connection
remote: (elixir) src/elixir_map.erl:58: :elixir_map.translate_struct/4
remote: (stdlib) lists.erl:1353: :lists.mapfoldl/3
remote: (stdlib) lists.erl:1354: :lists.mapfoldl/3
remote:
remote:
remote: ! Push rejected, failed to compile elixir app
remote:
remote: Verifying deploy...
remote:
remote: ! Push rejected to mysterious-meadow-6277.
remote:
To https://git.heroku.com/mysterious-meadow-6277.git
```
This has to do with stale dependencies which are not getting recompiled properly. It's possible to force Heroku to recompile all dependencies on each deploy, which should fix this problem. The way to do it is to add a new file called `elixir_buildpack.config` at the root of the application. The file should contain this line:
```
always_rebuild=true
```
Commit this file to the repository and try to push again to Heroku.
### Connection Timeout Error
If you are constantly getting connection timeouts while running `heroku run` this could mean that your internet provider has blocked port number 5000:
```
heroku run "POOL_SIZE=2 mix myapp.task"
Running POOL_SIZE=2 mix myapp.task on mysterious-meadow-6277... !
ETIMEDOUT: connect ETIMEDOUT 50.19.103.36:5000
```
You can overcome this by adding `detached` option to run command:
```
heroku run:detached "POOL_SIZE=2 mix ecto.migrate"
Running POOL_SIZE=2 mix ecto.migrate on mysterious-meadow-6277... done, run.8089 (Free)
```
[← Previous Page Deploying on Fly.io](fly) [Next Page → Custom Error Pages](custom_error_pages)
| programming_docs |
phoenix mix phx.gen.cert mix phx.gen.cert
=================
Generates a self-signed certificate for HTTPS testing.
```
$ mix phx.gen.cert
$ mix phx.gen.cert my-app my-app.local my-app.internal.example.com
```
Creates a private key and a self-signed certificate in PEM format. These files can be referenced in the `certfile` and `keyfile` parameters of an HTTPS Endpoint.
WARNING: only use the generated certificate for testing in a closed network environment, such as running a development server on `localhost`. For production, staging, or testing servers on the public internet, obtain a proper certificate, for example from [Let's Encrypt](https://letsencrypt.org).
NOTE: when using Google Chrome, open chrome://flags/#allow-insecure-localhost to enable the use of self-signed certificates on `localhost`.
Arguments
----------
The list of hostnames, if none are specified, defaults to:
* localhost
Other (optional) arguments:
* `--output` (`-o`): the path and base filename for the certificate and key (default: priv/cert/selfsigned)
* `--name` (`-n`): the Common Name value in certificate's subject (default: "Self-signed test certificate")
Requires OTP 21.3 or later.
phoenix Phoenix.NotAcceptableError exception Phoenix.NotAcceptableError exception
=====================================
Raised when one of the `accept*` headers is not accepted by the server.
This exception is commonly raised by [`Phoenix.Controller.accepts/2`](phoenix.controller#accepts/2) which negotiates the media types the server is able to serve with the contents the client is able to render.
If you are seeing this error, you should check if you are listing the desired formats in your `:accepts` plug or if you are setting the proper accept header in the client. The exception contains the acceptable mime types in the `accepts` field.
phoenix mix phx.gen.html mix phx.gen.html
=================
Generates controller, views, and context for an HTML resource.
```
mix phx.gen.html Accounts User users name:string age:integer
```
The first argument is the context module followed by the schema module and its plural name (used as the schema table name).
The context is an Elixir module that serves as an API boundary for the given resource. A context often holds many related resources. Therefore, if the context already exists, it will be augmented with functions for the given resource.
> Note: A resource may also be split over distinct contexts (such as `Accounts.User` and `Payments.User`).
>
>
The schema is responsible for mapping the database fields into an Elixir struct. It is followed by an optional list of attributes, with their respective names and types. See [`mix phx.gen.schema`](mix.tasks.phx.gen.schema) for more information on attributes.
Overall, this generator will add the following files to `lib/`:
* a context module in `lib/app/accounts.ex` for the accounts API
* a schema in `lib/app/accounts/user.ex`, with an `users` table
* a view in `lib/app_web/views/user_view.ex`
* a controller in `lib/app_web/controllers/user_controller.ex`
* default CRUD templates in `lib/app_web/templates/user`
The context app
----------------
A migration file for the repository and test files for the context and controller features will also be generated.
The location of the web files (controllers, views, templates, etc) in an umbrella application will vary based on the `:context_app` config located in your applications `:generators` configuration. When set, the Phoenix generators will generate web files directly in your lib and test folders since the application is assumed to be isolated to web specific functionality. If `:context_app` is not set, the generators will place web related lib and test files in a `web/` directory since the application is assumed to be handling both web and domain specific functionality. Example configuration:
```
config :my_app_web, :generators, context_app: :my_app
```
Alternatively, the `--context-app` option may be supplied to the generator:
```
mix phx.gen.html Sales User users --context-app warehouse
```
Web namespace
--------------
By default, the controller and view will be namespaced by the schema name. You can customize the web module namespace by passing the `--web` flag with a module name, for example:
```
mix phx.gen.html Sales User users --web Sales
```
Which would generate a `lib/app_web/controllers/sales/user_controller.ex` and `lib/app_web/views/sales/user_view.ex`.
Customizing the context, schema, tables and migrations
-------------------------------------------------------
In some cases, you may wish to bootstrap HTML templates, controllers, and controller tests, but leave internal implementation of the context or schema to yourself. You can use the `--no-context` and `--no-schema` flags for file generation control.
You can also change the table name or configure the migrations to use binary ids for primary keys, see [`mix phx.gen.schema`](mix.tasks.phx.gen.schema) for more information.
phoenix mix phx.gen.auth mix phx.gen.auth
=================
The [`mix phx.gen.auth`](mix.tasks.phx.gen.auth) command generates a flexible, pre-built authentication system into your Phoenix app. This simple generator allows you to quickly move past the task of adding authentication to your codebase and stay focused on the real-world problem your application is trying to solve.
Getting started
----------------
Let's start by running the following command from the root of our app (or `apps/my_app_web` in an umbrella app):
```
$ mix phx.gen.auth Accounts User users
```
This creates an `Accounts` context with an `Accounts.User` schema module. The final argument is the plural version of the schema module, which is used for generating database table names and route helpers. The [`mix phx.gen.auth`](mix.tasks.phx.gen.auth) generator is similar to [`mix phx.gen.html`](mix.tasks.phx.gen.html) except it does not accept a list of additional fields to add to the schema, and it generates many more context functions.
Since this generator installed additional dependencies in `mix.exs`, let's fetch those:
```
$ mix deps.get
```
Now we need to verify the database connection details for the development and test environments in `config/` so the migrator and tests can run properly. Then run the following to create the database:
```
$ mix ecto.setup
```
Let's run the tests to make sure our new authentication system works as expected.
```
$ mix test
```
And finally, let's start our Phoenix server and try it out.
```
$ mix phx.server
```
Developer responsibilities
---------------------------
Since Phoenix generates this code into your application instead of building these modules into Phoenix itself, you now have complete freedom to modify the authentication system, so it works best with your use case. The one caveat with using a generated authentication system is it will not be updated after it's been generated. Therefore, as improvements are made to the output of [`mix phx.gen.auth`](mix.tasks.phx.gen.auth), it becomes your responsibility to determine if these changes need to be ported into your application. Security-related and other important improvements will be explicitly and clearly marked in the `CHANGELOG.md` file and upgrade notes.
Generated code
---------------
The following are notes about the generated authentication system.
### Password hashing
The password hashing mechanism defaults to `bcrypt` for Unix systems and `pbkdf2` for Windows systems. Both systems use the [Comeonin interface](https://hexdocs.pm/comeonin/).
The password hashing mechanism can be overridden with the `--hashing-lib` option. The following values are supported:
* `bcrypt` - [bcrypt\_elixir](https://hex.pm/packages/bcrypt_elixir)
* `pbkdf2` - [pbkdf2\_elixir](https://hex.pm/packages/pbkdf2_elixir)
* `argon2` - [argon2\_elixir](https://hex.pm/packages/argon2_elixir)
We recommend developers to consider using `argon2`, which is the most robust of all 3. The downside is that `argon2` is quite CPU and memory intensive, and you will need more powerful instances to run your applications on.
For more information about choosing these libraries, see the [Comeonin project](https://github.com/riverrun/comeonin).
### Forbidding access
The generated code ships with an authentication module with a handful of plugs that fetch the current user, require authentication and so on. For instance, in an app named Demo which had `mix phx.gen.auth Accounts User users` run on it, you will find a module named `DemoWeb.UserAuth` with plugs such as:
* `fetch_current_user` - fetches the current user information if available
* `require_authenticated_user` - must be invoked after `fetch_current_user` and requires that a current user exists and is authenticated
* `redirect_if_user_is_authenticated` - used for the few pages that must not be available to authenticated users
### Confirmation
The generated functionality ships with an account confirmation mechanism, where users have to confirm their account, typically by email. However, the generated code does not forbid users from using the application if their accounts have not yet been confirmed. You can add this functionality by customizing the `require_authenticated_user` in the `Auth` module to check for the `confirmed_at` field (and any other property you desire).
### Notifiers
The generated code is not integrated with any system to send SMSes or emails for confirming accounts, resetting passwords, etc. Instead, it simply logs a message to the terminal. It is your responsibility to integrate with the proper system after generation.
### Tracking sessions
All sessions and tokens are tracked in a separate table. This allows you to track how many sessions are active for each account. You could even expose this information to users if desired.
Note that whenever the password changes (either via reset password or directly), all tokens are deleted, and the user has to log in again on all devices.
### User Enumeration attacks
A user enumeration attack allows someone to check if an email is registered in the application. The generated authentication code does not attempt to protect from such checks. For instance, when you register an account, if the email is already registered, the code will notify the user the email is already registered.
If your application is sensitive to enumeration attacks, you need to implement your own workflows, which tends to be very different from most applications, as you need to carefully balance security and user experience.
Furthermore, if you are concerned about enumeration attacks, beware of timing attacks too. For example, registering a new account typically involves additional work (such as writing to the database, sending emails, etc) compared to when an account already exists. Someone could measure the time taken to execute those additional tasks to enumerate emails. This applies to all endpoints (registration, confirmation, password recovery, etc.) that may send email, in-app notifications, etc.
### Case sensitiveness
The email lookup is made to be case-insensitive. Case-insensitive lookups are the default in MySQL and MSSQL. In SQLite3 we use [`COLLATE NOCASE`](https://www.sqlite.org/datatype3.html#collating_sequences) in the column definition to support it. In PostgreSQL, we use the [`citext` extension](https://www.postgresql.org/docs/current/citext.html).
Note `citext` is part of PostgreSQL itself and is bundled with it in most operating systems and package managers. [`mix phx.gen.auth`](mix.tasks.phx.gen.auth) takes care of creating the extension and no extra work is necessary in the majority of cases. If by any chance your package manager splits `citext` into a separate package, you will get an error while migrating, and you can most likely solve it by installing the `postgres-contrib` package.
### Concurrent tests
The generated tests run concurrently if you are using a database that supports concurrent tests, which is the case of PostgreSQL.
More about [`mix phx.gen.auth`](mix.tasks.phx.gen.auth)
--------------------------------------------------------
Check out [`mix phx.gen.auth`](mix.tasks.phx.gen.auth) for more details, such as using a different password hashing library, customizing the web module namespace, generating binary id type, configuring the default options, and using custom table names.
Additional resources
---------------------
The following links have more information regarding the motivation and design of the code this generates.
* José Valim's blog post - [An upcoming authentication solution for Phoenix](https://dashbit.co/blog/a-new-authentication-solution-for-phoenix)
* The [original `phx_gen_auth` repo](https://github.com/aaronrenner/phx_gen_auth) (for Phoenix 1.5 applications) - This is a great resource to see discussions around decisions that have been made in earlier versions of the project.
* [Original pull request on bare Phoenix app](https://github.com/dashbitco/mix_phx_gen_auth_demo/pull/1)
* [Original design spec](https://github.com/dashbitco/mix_phx_gen_auth_demo/blob/auth/README.md)
[← Previous Page Asset Management](asset_management) [Next Page → Channels](channels)
phoenix Phoenix.Controller Phoenix.Controller
===================
Controllers are used to group common functionality in the same (pluggable) module.
For example, the route:
```
get "/users/:id", MyAppWeb.UserController, :show
```
will invoke the `show/2` action in the `MyAppWeb.UserController`:
```
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def show(conn, %{"id" => id}) do
user = Repo.get(User, id)
render(conn, "show.html", user: user)
end
end
```
An action is a regular function that receives the connection and the request parameters as arguments. The connection is a [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) struct, as specified by the Plug library.
Options
--------
When used, the controller supports the following options:
* `:namespace` - sets the namespace to properly inflect the layout view. By default it uses the base alias in your controller name
* `:put_default_views` - controls whether the default view and layout should be set or not
Connection
-----------
A controller by default provides many convenience functions for manipulating the connection, rendering templates, and more.
Those functions are imported from two modules:
* [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) - a collection of low-level functions to work with the connection
* [`Phoenix.Controller`](phoenix.controller#content) - functions provided by Phoenix to support rendering, and other Phoenix specific behaviour
If you want to have functions that manipulate the connection without fully implementing the controller, you can import both modules directly instead of `use Phoenix.Controller`.
Plug pipeline
--------------
As with routers, controllers also have their own plug pipeline. However, different from routers, controllers have a single pipeline:
```
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
plug :authenticate, usernames: ["jose", "eric", "sonny"]
def show(conn, params) do
# authenticated users only
end
defp authenticate(conn, options) do
if get_session(conn, :username) in options[:usernames] do
conn
else
conn |> redirect(to: "/") |> halt()
end
end
end
```
The `:authenticate` plug will be invoked before the action. If the plug calls [`Plug.Conn.halt/1`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#halt/1) (which is by default imported into controllers), it will halt the pipeline and won't invoke the action.
### Guards
`plug/2` in controllers supports guards, allowing a developer to configure a plug to only run in some particular action:
```
plug :authenticate, [usernames: ["jose", "eric", "sonny"]] when action in [:show, :edit]
plug :authenticate, [usernames: ["admin"]] when not action in [:index]
```
The first plug will run only when action is show or edit. The second plug will always run, except for the index action.
Those guards work like regular Elixir guards and the only variables accessible in the guard are `conn`, the `action` as an atom and the `controller` as an alias.
Controllers are plugs
----------------------
Like routers, controllers are plugs, but they are wired to dispatch to a particular function which is called an action.
For example, the route:
```
get "/users/:id", UserController, :show
```
will invoke `UserController` as a plug:
```
UserController.call(conn, :show)
```
which will trigger the plug pipeline and which will eventually invoke the inner action plug that dispatches to the `show/2` function in `UserController`.
As controllers are plugs, they implement both [`init/1`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:init/1) and [`call/2`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:call/2), and it also provides a function named `action/2` which is responsible for dispatching the appropriate action after the plug stack (and is also overridable).
### Overriding `action/2` for custom arguments
Phoenix injects an `action/2` plug in your controller which calls the function matched from the router. By default, it passes the conn and params. In some cases, overriding the `action/2` plug in your controller is a useful way to inject arguments into your actions that you would otherwise need to repeatedly fetch off the connection. For example, imagine if you stored a `conn.assigns.current_user` in the connection and wanted quick access to the user for every action in your controller:
```
def action(conn, _) do
args = [conn, conn.params, conn.assigns.current_user]
apply(__MODULE__, action_name(conn), args)
end
def index(conn, _params, user) do
videos = Repo.all(user_videos(user))
# ...
end
def delete(conn, %{"id" => id}, user) do
video = Repo.get!(user_videos(user), id)
# ...
end
```
Rendering and layouts
----------------------
One of the main features provided by controllers is the ability to perform content negotiation and render templates based on information sent by the client. Read [`render/3`](#render/3) to learn more.
It is also important not to confuse [`Phoenix.Controller.render/3`](#render/3) with [`Phoenix.View.render/3`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html#render/3). The former expects a connection and relies on content negotiation while the latter is connection-agnostic and typically invoked from your views.
Summary
========
Functions
----------
[accepts(conn, accepted)](#accepts/2) Performs content negotiation based on the available formats.
[action\_fallback(plug)](#action_fallback/1) Registers the plug to call as a fallback to the controller action.
[action\_name(conn)](#action_name/1) Returns the action name as an atom, raises if unavailable.
[allow\_jsonp(conn, opts \\ [])](#allow_jsonp/2) A plug that may convert a JSON response into a JSONP one.
[clear\_flash(conn)](#clear_flash/1) Clears all flash messages.
[controller\_module(conn)](#controller_module/1) Returns the controller module as an atom, raises if unavailable.
[current\_path(conn)](#current_path/1) Returns the current request path with its default query parameters
[current\_path(conn, params)](#current_path/2) Returns the current path with the given query parameters.
[current\_url(conn)](#current_url/1) Returns the current request url with its default query parameters
[current\_url(conn, params)](#current_url/2) Returns the current request URL with query params.
[delete\_csrf\_token()](#delete_csrf_token/0) Deletes the CSRF token from the process dictionary.
[endpoint\_module(conn)](#endpoint_module/1) Returns the endpoint module as an atom, raises if unavailable.
[fetch\_flash(conn, opts \\ [])](#fetch_flash/2) Fetches the flash storage.
[get\_csrf\_token()](#get_csrf_token/0) Gets or generates a CSRF token.
[get\_flash(conn)](#get_flash/1) Returns a map of previously set flash messages or an empty map.
[get\_flash(conn, key)](#get_flash/2) Returns a message from flash by `key` (or `nil` if no message is available for `key`).
[get\_format(conn)](#get_format/1) Returns the request format, such as "json", "html".
[html(conn, data)](#html/2) Sends html response.
[json(conn, data)](#json/2) Sends JSON response.
[layout(conn)](#layout/1) Retrieves the current layout.
[layout\_formats(conn)](#layout_formats/1) Retrieves current layout formats.
[merge\_flash(conn, enumerable)](#merge_flash/2) Merges a map into the flash.
[protect\_from\_forgery(conn, opts \\ [])](#protect_from_forgery/2) Enables CSRF protection.
[put\_flash(conn, key, message)](#put_flash/3) Persists a value in flash.
[put\_format(conn, format)](#put_format/2) Puts the format in the connection.
[put\_layout(conn, layout)](#put_layout/2) Stores the layout for rendering.
[put\_layout\_formats(conn, formats)](#put_layout_formats/2) Sets which formats have a layout when rendering.
[put\_new\_layout(conn, layout)](#put_new_layout/2) Stores the layout for rendering if one was not stored yet.
[put\_new\_view(conn, module)](#put_new_view/2) Stores the view for rendering if one was not stored yet.
[put\_root\_layout(conn, layout)](#put_root_layout/2) Stores the root layout for rendering.
[put\_router\_url(conn, uri)](#put_router_url/2) Puts the url string or `%URI{}` to be used for route generation.
[put\_secure\_browser\_headers(conn, headers \\ %{})](#put_secure_browser_headers/2) Put headers that improve browser security.
[put\_static\_url(conn, uri)](#put_static_url/2) Puts the URL or `%URI{}` to be used for the static url generation.
[put\_view(conn, module)](#put_view/2) Stores the view for rendering.
[redirect(conn, opts)](#redirect/2) Sends redirect response to the given url.
[render(conn, template\_or\_assigns \\ [])](#render/2) Render the given template or the default template specified by the current action with the given assigns.
[render(conn, template, assigns)](#render/3) Renders the given `template` and `assigns` based on the `conn` information.
[root\_layout(conn)](#root_layout/1) Retrieves the current root layout.
[router\_module(conn)](#router_module/1) Returns the router module as an atom, raises if unavailable.
[scrub\_params(conn, required\_key)](#scrub_params/2) Scrubs the parameters from the request.
[send\_download(conn, kind, opts \\ [])](#send_download/3) Sends the given file or binary as a download.
[status\_message\_from\_template(template)](#status_message_from_template/1) Generates a status message from the template name.
[text(conn, data)](#text/2) Sends text response.
[view\_module(conn)](#view_module/1) Retrieves the current view.
[view\_template(conn)](#view_template/1) Returns the template name rendered in the view as a string (or nil if no template was rendered).
Functions
==========
### accepts(conn, accepted)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1212)
```
@spec accepts(Plug.Conn.t(), [binary()]) :: Plug.Conn.t() | no_return()
```
Performs content negotiation based on the available formats.
It receives a connection, a list of formats that the server is capable of rendering and then proceeds to perform content negotiation based on the request information. If the client accepts any of the given formats, the request proceeds.
If the request contains a "\_format" parameter, it is considered to be the format desired by the client. If no "\_format" parameter is available, this function will parse the "accept" header and find a matching format accordingly.
This function is useful when you may want to serve different content-types (such as JSON and HTML) from the same routes. However, if you always have distinct routes, you can also disable content negotiation and simply hardcode your format of choice in your route pipelines:
```
plug :put_format, "html"
```
It is important to notice that browsers have historically sent bad accept headers. For this reason, this function will default to "html" format whenever:
* the accepted list of arguments contains the "html" format
* the accept header specified more than one media type preceded or followed by the wildcard media type "`*/*`"
This function raises [`Phoenix.NotAcceptableError`](phoenix.notacceptableerror), which is rendered with status 406, whenever the server cannot serve a response in any of the formats expected by the client.
#### Examples
[`accepts/2`](#accepts/2) can be invoked as a function:
```
iex> accepts(conn, ["html", "json"])
```
or used as a plug:
```
plug :accepts, ["html", "json"]
plug :accepts, ~w(html json)
```
#### Custom media types
It is possible to add custom media types to your Phoenix application. The first step is to teach Plug about those new media types in your `config/config.exs` file:
```
config :mime, :types, %{
"application/vnd.api+json" => ["json-api"]
}
```
The key is the media type, the value is a list of formats the media type can be identified with. For example, by using "json-api", you will be able to use templates with extension "index.json-api" or to force a particular format in a given URL by sending "?\_format=json-api".
After this change, you must recompile plug:
```
$ mix deps.clean mime --build
$ mix deps.get
```
And now you can use it in accepts too:
```
plug :accepts, ["html", "json-api"]
```
### action\_fallback(plug)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L231)
Registers the plug to call as a fallback to the controller action.
A fallback plug is useful to translate common domain data structures into a valid `%Plug.Conn{}` response. If the controller action fails to return a `%Plug.Conn{}`, the provided plug will be called and receive the controller's `%Plug.Conn{}` as it was before the action was invoked along with the value returned from the controller action.
#### Examples
```
defmodule MyController do
use Phoenix.Controller
action_fallback MyFallbackController
def show(conn, %{"id" => id}, current_user) do
with {:ok, post} <- Blog.fetch_post(id),
:ok <- Authorizer.authorize(current_user, :view, post) do
render(conn, "show.json", post: post)
end
end
end
```
In the above example, `with` is used to match only a successful post fetch, followed by valid authorization for the current user. In the event either of those fail to match, `with` will not invoke the render block and instead return the unmatched value. In this case, imagine `Blog.fetch_post/2` returned `{:error, :not_found}` or `Authorizer.authorize/3` returned `{:error, :unauthorized}`. For cases where these data structures serve as return values across multiple boundaries in our domain, a single fallback module can be used to translate the value into a valid response. For example, you could write the following fallback controller to handle the above values:
```
defmodule MyFallbackController do
use Phoenix.Controller
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(MyErrorView)
|> render(:"404")
end
def call(conn, {:error, :unauthorized}) do
conn
|> put_status(403)
|> put_view(MyErrorView)
|> render(:"403")
end
end
```
### action\_name(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L239)
```
@spec action_name(Plug.Conn.t()) :: atom()
```
Returns the action name as an atom, raises if unavailable.
### allow\_jsonp(conn, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L309)
```
@spec allow_jsonp(Plug.Conn.t(), Keyword.t()) :: Plug.Conn.t()
```
A plug that may convert a JSON response into a JSONP one.
In case a JSON response is returned, it will be converted to a JSONP as long as the callback field is present in the query string. The callback field itself defaults to "callback", but may be configured with the callback option.
In case there is no callback or the response is not encoded in JSON format, it is a no-op.
Only alphanumeric characters and underscore are allowed in the callback name. Otherwise an exception is raised.
#### Examples
```
# Will convert JSON to JSONP if callback=someFunction is given
plug :allow_jsonp
# Will convert JSON to JSONP if cb=someFunction is given
plug :allow_jsonp, callback: "cb"
```
### clear\_flash(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1443)
Clears all flash messages.
### controller\_module(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L245)
```
@spec controller_module(Plug.Conn.t()) :: atom()
```
Returns the controller module as an atom, raises if unavailable.
### current\_path(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1466)
Returns the current request path with its default query parameters:
```
iex> current_path(conn)
"/users/123?existing=param"
```
See [`current_path/2`](#current_path/2) to override the default parameters.
The path is normalized based on the `conn.script_name` and `conn.path_info`. For example, "/foo//bar/" will become "/foo/bar". If you want the original path, use `conn.request_path` instead.
### current\_path(conn, params)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1498)
Returns the current path with the given query parameters.
You may also retrieve only the request path by passing an empty map of params.
#### Examples
```
iex> current_path(conn)
"/users/123?existing=param"
iex> current_path(conn, %{new: "param"})
"/users/123?new=param"
iex> current_path(conn, %{filter: %{status: ["draft", "published"]}})
"/users/123?filter[status][]=draft&filter[status][]=published"
iex> current_path(conn, %{})
"/users/123"
```
The path is normalized based on the `conn.script_name` and `conn.path_info`. For example, "/foo//bar/" will become "/foo/bar". If you want the original path, use `conn.request_path` instead.
### current\_url(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1517)
Returns the current request url with its default query parameters:
```
iex> current_url(conn)
"https://www.example.com/users/123?existing=param"
```
See [`current_url/2`](#current_url/2) to override the default parameters.
### current\_url(conn, params)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1564)
Returns the current request URL with query params.
The path will be retrieved from the currently requested path via [`current_path/1`](#current_path/1). The scheme, host and others will be received from the URL configuration in your Phoenix endpoint. The reason we don't use the host and scheme information in the request is because most applications are behind proxies and the host and scheme may not actually reflect the host and scheme accessed by the client. If you want to access the url precisely as requested by the client, see [`Plug.Conn.request_url/1`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#request_url/1).
#### Examples
```
iex> current_url(conn)
"https://www.example.com/users/123?existing=param"
iex> current_url(conn, %{new: "param"})
"https://www.example.com/users/123?new=param"
iex> current_url(conn, %{})
"https://www.example.com/users/123"
```
#### Custom URL Generation
In some cases, you'll need to generate a request's URL, but using a different scheme, different host, etc. This can be accomplished in two ways.
If you want to do so in a case-by-case basis, you can define a custom function that gets the endpoint URI configuration and changes it accordingly. For example, to get the current URL always in HTTPS format:
```
def current_secure_url(conn, params \\ %{}) do
cur_uri = MyAppWeb.Endpoint.struct_url()
cur_path = Phoenix.Controller.current_path(conn, params)
MyAppWeb.Router.Helpers.url(%URI{cur_uri | scheme: "https"}) <> cur_path
end
```
However, if you want all generated URLs to always have a certain schema, host, etc, you may use [`put_router_url/2`](#put_router_url/2).
### delete\_csrf\_token()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1138)
Deletes the CSRF token from the process dictionary.
*Note*: The token is deleted only after a response has been sent.
### endpoint\_module(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L257)
```
@spec endpoint_module(Plug.Conn.t()) :: atom()
```
Returns the endpoint module as an atom, raises if unavailable.
### fetch\_flash(conn, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1331)
Fetches the flash storage.
### get\_csrf\_token()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1131)
Gets or generates a CSRF token.
If a token exists, it is returned, otherwise it is generated and stored in the process dictionary.
### get\_flash(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1400)
Returns a map of previously set flash messages or an empty map.
#### Examples
```
iex> get_flash(conn)
%{}
iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn)
%{"info" => "Welcome Back!"}
```
### get\_flash(conn, key)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1415)
Returns a message from flash by `key` (or `nil` if no message is available for `key`).
#### Examples
```
iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
```
### get\_format(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L904)
Returns the request format, such as "json", "html".
This format is used when rendering a template as an atom. For example, `render(conn, :foo)` will render `"foo.FORMAT"` where the format is the one set here. The default format is typically set from the negotiation done in [`accepts/2`](#accepts/2).
### html(conn, data)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L377)
```
@spec html(Plug.Conn.t(), iodata()) :: Plug.Conn.t()
```
Sends html response.
#### Examples
```
iex> html(conn, "<html><head>...")
```
### json(conn, data)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L280)
```
@spec json(Plug.Conn.t(), term()) :: Plug.Conn.t()
```
Sends JSON response.
It uses the configured `:json_library` under the `:phoenix` application for `:json` to pick up the encoder module.
#### Examples
```
iex> json(conn, %{id: 123})
```
### layout(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L608)
```
@spec layout(Plug.Conn.t()) :: {atom(), String.t() | atom()} | false
```
Retrieves the current layout.
### layout\_formats(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L600)
```
@spec layout_formats(Plug.Conn.t()) :: [String.t()]
```
Retrieves current layout formats.
### merge\_flash(conn, enumerable)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1366)
Merges a map into the flash.
Returns the updated connection.
#### Examples
```
iex> conn = merge_flash(conn, info: "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
```
### protect\_from\_forgery(conn, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1075)
Enables CSRF protection.
Currently used as a wrapper function for [`Plug.CSRFProtection`](https://hexdocs.pm/plug/1.13.6/Plug.CSRFProtection.html) and mainly serves as a function plug in `YourApp.Router`.
Check [`get_csrf_token/0`](#get_csrf_token/0) and [`delete_csrf_token/0`](#delete_csrf_token/0) for retrieving and deleting CSRF tokens.
### put\_flash(conn, key, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1383)
Persists a value in flash.
Returns the updated connection.
#### Examples
```
iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
```
### put\_format(conn, format)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L894)
Puts the format in the connection.
This format is used when rendering a template as an atom. For example, `render(conn, :foo)` will render `"foo.FORMAT"` where the format is the one set here. The default format is typically set from the negotiation done in [`accepts/2`](#accepts/2).
See [`get_format/1`](#get_format/1) for retrieval.
### put\_layout(conn, layout)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L493)
```
@spec put_layout(
Plug.Conn.t(),
{atom(), binary() | atom()} | atom() | binary() | false
) ::
Plug.Conn.t()
```
Stores the layout for rendering.
The layout must be a tuple, specifying the layout view and the layout name, or false. In case a previous layout is set, `put_layout` also accepts the layout name to be given as a string or as an atom. If a string, it must contain the format. Passing an atom means the layout format will be found at rendering time, similar to the template in [`render/3`](#render/3). It can also be set to `false`. In this case, no layout would be used.
#### Examples
```
iex> layout(conn)
false
iex> conn = put_layout conn, {AppView, "application.html"}
iex> layout(conn)
{AppView, "application.html"}
iex> conn = put_layout conn, "print.html"
iex> layout(conn)
{AppView, "print.html"}
iex> conn = put_layout conn, :print
iex> layout(conn)
{AppView, :print}
```
Raises [`Plug.Conn.AlreadySentError`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.AlreadySentError.html) if `conn` is already sent.
### put\_layout\_formats(conn, formats)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L589)
```
@spec put_layout_formats(Plug.Conn.t(), [String.t()]) :: Plug.Conn.t()
```
Sets which formats have a layout when rendering.
#### Examples
```
iex> layout_formats(conn)
["html"]
iex> put_layout_formats(conn, ["html", "mobile"])
iex> layout_formats(conn)
["html", "mobile"]
```
Raises [`Plug.Conn.AlreadySentError`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.AlreadySentError.html) if `conn` is already sent.
### put\_new\_layout(conn, layout)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L524)
```
@spec put_new_layout(Plug.Conn.t(), {atom(), binary() | atom()} | false) ::
Plug.Conn.t()
```
Stores the layout for rendering if one was not stored yet.
Raises [`Plug.Conn.AlreadySentError`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.AlreadySentError.html) if `conn` is already sent.
### put\_new\_view(conn, module)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L449)
```
@spec put_new_view(Plug.Conn.t(), atom()) :: Plug.Conn.t()
```
Stores the view for rendering if one was not stored yet.
Raises [`Plug.Conn.AlreadySentError`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.AlreadySentError.html) if `conn` is already sent.
### put\_root\_layout(conn, layout)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L566)
```
@spec put_root_layout(
Plug.Conn.t(),
{atom(), binary() | atom()} | atom() | binary() | false
) ::
Plug.Conn.t()
```
Stores the root layout for rendering.
Like [`put_layout/2`](#put_layout/2), the layout must be a tuple, specifying the layout view and the layout name, or false.
In case a previous layout is set, `put_root_layout` also accepts the layout name to be given as a string or as an atom. If a string, it must contain the format. Passing an atom means the layout format will be found at rendering time, similar to the template in [`render/3`](#render/3). It can also be set to `false`. In this case, no layout would be used.
#### Examples
```
iex> root_layout(conn)
false
iex> conn = put_root_layout conn, {AppView, "root.html"}
iex> root_layout(conn)
{AppView, "root.html"}
iex> conn = put_root_layout conn, "bare.html"
iex> root_layout(conn)
{AppView, "bare.html"}
iex> conn = put_root_layout conn, :bare
iex> root_layout(conn)
{AppView, :bare}
```
Raises [`Plug.Conn.AlreadySentError`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.AlreadySentError.html) if `conn` is already sent.
### put\_router\_url(conn, uri)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L863)
Puts the url string or `%URI{}` to be used for route generation.
This function overrides the default URL generation pulled from the `%Plug.Conn{}`'s endpoint configuration.
#### Examples
Imagine your application is configured to run on "example.com" but after the user signs in, you want all links to use "some\_user.example.com". You can do so by setting the proper router url configuration:
```
def put_router_url_by_user(conn) do
put_router_url(conn, get_user_from_conn(conn).account_name <> ".example.com")
end
```
Now when you call `Routes.some_route_url(conn, ...)`, it will use the router url set above. Keep in mind that, if you want to generate routes to the *current* domain, it is preferred to use `Routes.some_route_path` helpers, as those are always relative.
### put\_secure\_browser\_headers(conn, headers \\ %{})[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1105)
Put headers that improve browser security.
It sets the following headers:
* `x-frame-options` - set to SAMEORIGIN to avoid clickjacking through iframes unless in the same origin
* `x-content-type-options` - set to nosniff. This requires script and style tags to be sent with proper content type
* `x-xss-protection` - set to "1; mode=block" to improve XSS protection on both Chrome and IE
* `x-download-options` - set to noopen to instruct the browser not to open a download directly in the browser, to avoid HTML files rendering inline and accessing the security context of the application (like critical domain cookies)
* `x-permitted-cross-domain-policies` - set to none to restrict Adobe Flash Player’s access to data
* `cross-origin-window-policy` - set to deny to avoid window control attacks
A custom headers map may also be given to be merged with defaults. It is recommended for custom header keys to be in lowercase, to avoid sending duplicate keys in a request. Additionally, responses with mixed-case headers served over HTTP/2 are not considered valid by common clients, resulting in dropped responses.
### put\_static\_url(conn, uri)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L877)
Puts the URL or `%URI{}` to be used for the static url generation.
Using this function on a `%Plug.Conn{}` struct tells `static_url/2` to use the given information for URL generation instead of the the `%Plug.Conn{}`'s endpoint configuration (much like [`put_router_url/2`](#put_router_url/2) but for static URLs).
### put\_view(conn, module)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L437)
```
@spec put_view(Plug.Conn.t(), atom()) :: Plug.Conn.t()
```
Stores the view for rendering.
Raises [`Plug.Conn.AlreadySentError`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.AlreadySentError.html) if `conn` is already sent.
### redirect(conn, opts)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L398)
Sends redirect response to the given url.
For security, `:to` only accepts paths. Use the `:external` option to redirect to any URL.
The response will be sent with the status code defined within the connection, via [`Plug.Conn.put_status/2`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#put_status/2). If no status code is set, a 302 response is sent.
#### Examples
```
iex> redirect(conn, to: "/login")
iex> redirect(conn, external: "https://elixir-lang.org")
```
### render(conn, template\_or\_assigns \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L623)
```
@spec render(Plug.Conn.t(), Keyword.t() | map() | binary() | atom()) :: Plug.Conn.t()
```
Render the given template or the default template specified by the current action with the given assigns.
See [`render/3`](#render/3) for more information.
### render(conn, template, assigns)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L728)
```
@spec render(
Plug.Conn.t(),
binary() | atom(),
Keyword.t() | map() | binary() | atom()
) :: Plug.Conn.t()
```
Renders the given `template` and `assigns` based on the `conn` information.
Once the template is rendered, the template format is set as the response content type (for example, an HTML template will set "text/html" as response content type) and the data is sent to the client with default status of 200.
#### Arguments
* `conn` - the [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) struct
* `template` - which may be an atom or a string. If an atom, like `:index`, it will render a template with the same format as the one returned by [`get_format/1`](#get_format/1). For example, for an HTML request, it will render the "index.html" template. If the template is a string, it must contain the extension too, like "index.json"
* `assigns` - a dictionary with the assigns to be used in the view. Those assigns are merged and have higher precedence than the connection assigns (`conn.assigns`)
#### Examples
```
defmodule MyAppWeb.UserController do
use Phoenix.Controller
def show(conn, _params) do
render(conn, "show.html", message: "Hello")
end
end
```
The example above renders a template "show.html" from the `MyAppWeb.UserView` and sets the response content type to "text/html".
In many cases, you may want the template format to be set dynamically based on the request. To do so, you can pass the template name as an atom (without the extension):
```
def show(conn, _params) do
render(conn, :show, message: "Hello")
end
```
In order for the example above to work, we need to do content negotiation with the accepts plug before rendering. You can do so by adding the following to your pipeline (in the router):
```
plug :accepts, ["html"]
```
#### Views
By default, Controllers render templates in a view with a similar name to the controller. For example, `MyAppWeb.UserController` will render templates inside the `MyAppWeb.UserView`. This information can be changed any time by using the [`put_view/2`](#put_view/2) function:
```
def show(conn, _params) do
conn
|> put_view(MyAppWeb.SpecialView)
|> render(:show, message: "Hello")
end
```
[`put_view/2`](#put_view/2) can also be used as a plug:
```
defmodule MyAppWeb.UserController do
use Phoenix.Controller
plug :put_view, MyAppWeb.SpecialView
def show(conn, _params) do
render(conn, :show, message: "Hello")
end
end
```
#### Layouts
Templates are often rendered inside layouts. By default, Phoenix will render layouts for html requests. For example:
```
defmodule MyAppWeb.UserController do
use Phoenix.Controller
def show(conn, _params) do
render(conn, "show.html", message: "Hello")
end
end
```
will render the "show.html" template inside an "app.html" template specified in `MyAppWeb.LayoutView`. [`put_layout/2`](#put_layout/2) can be used to change the layout, similar to how [`put_view/2`](#put_view/2) can be used to change the view.
[`layout_formats/1`](#layout_formats/1) and [`put_layout_formats/2`](#put_layout_formats/2) can be used to configure which formats support/require layout rendering (defaults to "html" only).
### root\_layout(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L614)
```
@spec root_layout(Plug.Conn.t()) :: {atom(), String.t() | atom()} | false
```
Retrieves the current root layout.
### router\_module(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L251)
```
@spec router_module(Plug.Conn.t()) :: atom()
```
Returns the router module as an atom, raises if unavailable.
### scrub\_params(conn, required\_key)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1035)
```
@spec scrub_params(Plug.Conn.t(), String.t()) :: Plug.Conn.t()
```
Scrubs the parameters from the request.
This process is two-fold:
* Checks to see if the `required_key` is present
* Changes empty parameters of `required_key` (recursively) to nils
This function is useful for removing empty strings sent via HTML forms. If you are providing an API, there is likely no need to invoke [`scrub_params/2`](#scrub_params/2).
If the `required_key` is not present, it will raise [`Phoenix.MissingParamError`](phoenix.missingparamerror).
#### Examples
```
iex> scrub_params(conn, "user")
```
### send\_download(conn, kind, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L965)
Sends the given file or binary as a download.
The second argument must be `{:binary, contents}`, where `contents` will be sent as download, or`{:file, path}`, where `path` is the filesystem location of the file to be sent. Be careful to not interpolate the path from external parameters, as it could allow traversal of the filesystem.
The download is achieved by setting "content-disposition" to attachment. The "content-type" will also be set based on the extension of the given filename but can be customized via the `:content_type` and `:charset` options.
#### Options
* `:filename` - the filename to be presented to the user as download
* `:content_type` - the content type of the file or binary sent as download. It is automatically inferred from the filename extension
* `:disposition` - specifies disposition type (`:attachment` or `:inline`). If `:attachment` was used, user will be prompted to save the file. If `:inline` was used, the browser will attempt to open the file. Defaults to `:attachment`.
* `:charset` - the charset of the file, such as "utf-8". Defaults to none
* `:offset` - the bytes to offset when reading. Defaults to `0`
* `:length` - the total bytes to read. Defaults to `:all`
* `:encode` - encodes the filename using [`URI.encode_www_form/1`](https://hexdocs.pm/elixir/URI.html#encode_www_form/1). Defaults to `true`. When `false`, disables encoding. If you disable encoding, you need to guarantee there are no special characters in the filename, such as quotes, newlines, etc. Otherwise you can expose your application to security attacks
#### Examples
To send a file that is stored inside your application priv directory:
```
path = Application.app_dir(:my_app, "priv/prospectus.pdf")
send_download(conn, {:file, path})
```
When using `{:file, path}`, the filename is inferred from the given path but may also be set explicitly.
To allow the user to download contents that are in memory as a binary or string:
```
send_download(conn, {:binary, "world"}, filename: "hello.txt")
```
See [`Plug.Conn.send_file/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#send_file/3) and [`Plug.Conn.send_resp/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#send_resp/3) if you would like to access the low-level functions used to send files and responses via Plug.
### status\_message\_from\_template(template)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L1430)
Generates a status message from the template name.
#### Examples
```
iex> status_message_from_template("404.html")
"Not Found"
iex> status_message_from_template("whatever.html")
"Internal Server Error"
```
### text(conn, data)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L364)
```
@spec text(Plug.Conn.t(), String.Chars.t()) :: Plug.Conn.t()
```
Sends text response.
#### Examples
```
iex> text(conn, "hello")
iex> text(conn, :implements_to_string)
```
### view\_module(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L460)
```
@spec view_module(Plug.Conn.t()) :: atom()
```
Retrieves the current view.
### view\_template(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/controller.ex#L264)
```
@spec view_template(Plug.Conn.t()) :: binary() | nil
```
Returns the template name rendered in the view as a string (or nil if no template was rendered).
| programming_docs |
phoenix Phoenix.Socket behaviour Phoenix.Socket behaviour
=========================
A socket implementation that multiplexes messages over channels.
[`Phoenix.Socket`](phoenix.socket#content) is used as a module for establishing and maintaining the socket state via the [`Phoenix.Socket`](phoenix.socket#content) struct.
Once connected to a socket, incoming and outgoing events are routed to channels. The incoming client data is routed to channels via transports. It is the responsibility of the socket to tie transports and channels together.
Phoenix supports `websocket` and `longpoll` options when invoking [`Phoenix.Endpoint.socket/3`](phoenix.endpoint#socket/3) in your endpoint. `websocket` is set by default and `longpoll` can also be configured explicitly.
```
socket "/socket", MyAppWeb.Socket, websocket: true, longpoll: false
```
The command above means incoming socket connections can be made via a WebSocket connection. Events are routed by topic to channels:
```
channel "room:lobby", MyAppWeb.LobbyChannel
```
See [`Phoenix.Channel`](phoenix.channel) for more information on channels.
Socket Behaviour
-----------------
Socket handlers are mounted in Endpoints and must define two callbacks:
* `connect/3` - receives the socket params, connection info if any, and authenticates the connection. Must return a [`Phoenix.Socket`](phoenix.socket#content) struct, often with custom assigns
* `id/1` - receives the socket returned by `connect/3` and returns the id of this connection as a string. The `id` is used to identify socket connections, often to a particular user, allowing us to force disconnections. For sockets requiring no authentication, `nil` can be returned
Examples
---------
```
defmodule MyAppWeb.UserSocket do
use Phoenix.Socket
channel "room:*", MyAppWeb.RoomChannel
def connect(params, socket, _connect_info) do
{:ok, assign(socket, :user_id, params["user_id"])}
end
def id(socket), do: "users_socket:#{socket.assigns.user_id}"
end
# Disconnect all user's socket connections and their multiplexed channels
MyAppWeb.Endpoint.broadcast("users_socket:" <> user.id, "disconnect", %{})
```
Socket fields
--------------
* `:id` - The string id of the socket
* `:assigns` - The map of socket assigns, default: `%{}`
* `:channel` - The current channel module
* `:channel_pid` - The channel pid
* `:endpoint` - The endpoint module where this socket originated, for example: `MyAppWeb.Endpoint`
* `:handler` - The socket module where this socket originated, for example: `MyAppWeb.UserSocket`
* `:joined` - If the socket has effectively joined the channel
* `:join_ref` - The ref sent by the client when joining
* `:ref` - The latest ref sent by the client
* `:pubsub_server` - The registered name of the socket's pubsub server
* `:topic` - The string topic, for example `"room:123"`
* `:transport` - An identifier for the transport, used for logging
* `:transport_pid` - The pid of the socket's transport process
* `:serializer` - The serializer for socket messages
Using options
--------------
On `use Phoenix.Socket`, the following options are accepted:
* `:log` - the default level to log socket actions. Defaults to `:info`. May be set to `false` to disable it
* `:partitions` - each channel is spawned under a supervisor. This option controls how many supervisors will be spawned to handle channels. Defaults to the number of cores.
Garbage collection
-------------------
It's possible to force garbage collection in the transport process after processing large messages. For example, to trigger such from your channels, run:
```
send(socket.transport_pid, :garbage_collect)
```
Alternatively, you can configure your endpoint socket to trigger more fullsweep garbage collections more frequently, by setting the `:fullsweep_after` option for websockets. See [`Phoenix.Endpoint.socket/3`](phoenix.endpoint#socket/3) for more info.
Client-server communication
----------------------------
The encoding of server data and the decoding of client data is done according to a serializer, defined in [`Phoenix.Socket.Serializer`](phoenix.socket.serializer). By default, JSON encoding is used to broker messages to and from clients.
The serializer `decode!` function must return a [`Phoenix.Socket.Message`](phoenix.socket.message) which is forwarded to channels except:
* `"heartbeat"` events in the "phoenix" topic - should just emit an OK reply
* `"phx_join"` on any topic - should join the topic
* `"phx_leave"` on any topic - should leave the topic
Each message also has a `ref` field which is used to track responses.
The server may send messages or replies back. For messages, the ref uniquely identifies the message. For replies, the ref matches the original message. Both data-types also include a join\_ref that uniquely identifies the currently joined channel.
The [`Phoenix.Socket`](phoenix.socket#content) implementation may also send special messages and replies:
* `"phx_error"` - in case of errors, such as a channel process crashing, or when attempting to join an already joined channel
* `"phx_close"` - the channel was gracefully closed
Phoenix ships with a JavaScript implementation of both websocket and long polling that interacts with Phoenix.Socket and can be used as reference for those interested in implementing custom clients.
Custom sockets and transports
------------------------------
See the [`Phoenix.Socket.Transport`](phoenix.socket.transport) documentation for more information on writing your own socket that does not leverage channels or for writing your own transports that interacts with other sockets.
Custom channels
----------------
You can list any module as a channel as long as it implements a `child_spec/1` function. The `child_spec/1` function receives the caller as argument and it must return a child spec that initializes a process.
Once the process is initialized, it will receive the following message:
```
{Phoenix.Channel, auth_payload, from, socket}
```
A custom channel implementation MUST invoke `GenServer.reply(from, {:ok | :error, reply_payload})` during its initialization with a custom `reply_payload` that will be sent as a reply to the client. Failing to do so will block the socket forever.
A custom channel receives [`Phoenix.Socket.Message`](phoenix.socket.message) structs as regular messages from the transport. Replies to those messages and custom messages can be sent to the socket at any moment by building an appropriate [`Phoenix.Socket.Reply`](phoenix.socket.reply) and [`Phoenix.Socket.Message`](phoenix.socket.message) structs, encoding them with the serializer and dispatching the serialized result to the transport.
For example, to handle "phx\_leave" messages, which is recommended to be handled by all channel implementations, one may do:
```
def handle_info(
%Message{topic: topic, event: "phx_leave"} = message,
%{topic: topic, serializer: serializer, transport_pid: transport_pid} = socket
) do
send transport_pid, serializer.encode!(build_leave_reply(message))
{:stop, {:shutdown, :left}, socket}
end
```
We also recommend all channels to monitor the `transport_pid` on `init` and exit if the transport exits. We also advise to rewrite `:normal` exit reasons (usually due to the socket being closed) to the `{:shutdown, :closed}` to guarantee links are broken on the channel exit (as a `:normal` exit does not break links):
```
def handle_info({:DOWN, _, _, transport_pid, reason}, %{transport_pid: transport_pid} = socket) do
reason = if reason == :normal, do: {:shutdown, :closed}, else: reason
{:stop, reason, socket}
end
```
Any process exit is treated as an error by the socket layer unless a `{:socket_close, pid, reason}` message is sent to the socket before shutdown.
Custom channel implementations cannot be tested with [`Phoenix.ChannelTest`](phoenix.channeltest) and are currently considered experimental. The underlying API may be changed at any moment.
Summary
========
Types
------
[t()](#t:t/0) Callbacks
----------
[connect(params, t)](#c:connect/2) Receives the socket params and authenticates the connection.
[connect(params, t, connect\_info)](#c:connect/3) [id(t)](#c:id/1) Identifies the socket connection.
Functions
----------
[assign(socket, attrs)](#assign/2) [assign(socket, key, value)](#assign/3) Adds key-value pairs to socket assigns.
[channel(topic\_pattern, module, opts \\ [])](#channel/3) Defines a channel matching the given topic and transports.
Types
======
### t()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket.ex#L254)
```
@type t() :: %Phoenix.Socket{
assigns: map(),
channel: atom(),
channel_pid: pid(),
endpoint: atom(),
handler: atom(),
id: String.t() | nil,
join_ref: term(),
joined: boolean(),
private: map(),
pubsub_server: atom(),
ref: term(),
serializer: atom(),
topic: String.t(),
transport: atom(),
transport_pid: pid()
}
```
Callbacks
==========
### connect(params, t)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket.ex#L210)
```
@callback connect(params :: map(), t()) :: {:ok, t()} | {:error, term()} | :error
```
Receives the socket params and authenticates the connection.
#### Socket params and assigns
Socket params are passed from the client and can be used to verify and authenticate a user. After verification, you can put default assigns into the socket that will be set for all channels, ie
```
{:ok, assign(socket, :user_id, verified_user_id)}
```
To deny connection, return `:error`.
See [`Phoenix.Token`](phoenix.token) documentation for examples in performing token verification on connect.
### connect(params, t, connect\_info)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket.ex#L211)
```
@callback connect(params :: map(), t(), connect_info :: map()) ::
{:ok, t()} | {:error, term()} | :error
```
### id(t)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket.ex#L227)
```
@callback id(t()) :: String.t() | nil
```
Identifies the socket connection.
Socket IDs are topics that allow you to identify all sockets for a given user:
```
def id(socket), do: "users_socket:#{socket.assigns.user_id}"
```
Would allow you to broadcast a `"disconnect"` event and terminate all active sockets and channels for a given user:
```
MyAppWeb.Endpoint.broadcast("users_socket:" <> user.id, "disconnect", %{})
```
Returning `nil` makes this socket anonymous.
Functions
==========
### assign(socket, attrs)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket.ex#L325)
### assign(socket, key, value)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket.ex#L321)
Adds key-value pairs to socket assigns.
A single key-value pair may be passed, a keyword list or map of assigns may be provided to be merged into existing socket assigns.
#### Examples
```
iex> assign(socket, :name, "Elixir")
iex> assign(socket, name: "Elixir", logo: "💧")
```
### channel(topic\_pattern, module, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket.ex#L356)
Defines a channel matching the given topic and transports.
* `topic_pattern` - The string pattern, for example `"room:*"`, `"users:*"`, or `"system"`
* `module` - The channel module handler, for example `MyAppWeb.RoomChannel`
* `opts` - The optional list of options, see below
#### Options
* `:assigns` - the map of socket assigns to merge into the socket on join
#### Examples
```
channel "topic1:*", MyChannel
```
#### Topic Patterns
The `channel` macro accepts topic patterns in two flavors. A splat (the `*` character) argument can be provided as the last character to indicate a `"topic:subtopic"` match. If a plain string is provided, only that topic will match the channel handler. Most use-cases will use the `"topic:*"` pattern to allow more versatile topic scoping.
See [`Phoenix.Channel`](phoenix.channel) for more information
phoenix Phoenix.Presence behaviour Phoenix.Presence behaviour
===========================
Provides Presence tracking to processes and channels.
This behaviour provides presence features such as fetching presences for a given topic, as well as handling diffs of join and leave events as they occur in real-time. Using this module defines a supervisor and a module that implements the [`Phoenix.Tracker`](https://hexdocs.pm/phoenix_pubsub/2.1.1/Phoenix.Tracker.html) behaviour that uses [`Phoenix.PubSub`](https://hexdocs.pm/phoenix_pubsub/2.1.1/Phoenix.PubSub.html) to broadcast presence updates.
In case you want to use only a subset of the functionality provided by [`Phoenix.Presence`](phoenix.presence#content), such as tracking processes but without broadcasting updates, we recommend that you look at the [`Phoenix.Tracker`](https://hexdocs.pm/phoenix_pubsub/2.1.1/Phoenix.Tracker.html) functionality from the `phoenix_pubsub` project.
Example Usage
--------------
Start by defining a presence module within your application which uses [`Phoenix.Presence`](phoenix.presence#content) and provide the `:otp_app` which holds your configuration, as well as the `:pubsub_server`.
```
defmodule MyAppWeb.Presence do
use Phoenix.Presence,
otp_app: :my_app,
pubsub_server: MyApp.PubSub
end
```
The `:pubsub_server` must point to an existing pubsub server running in your application, which is included by default as `MyApp.PubSub` for new applications.
Next, add the new supervisor to your supervision tree in `lib/my_app/application.ex`. It must be after the PubSub child and before the endpoint:
```
children = [
...
{Phoenix.PubSub, name: MyApp.PubSub},
MyAppWeb.Presence,
MyAppWeb.Endpoint
]
```
Once added, presences can be tracked in your channel after joining:
```
defmodule MyAppWeb.MyChannel do
use MyAppWeb, :channel
alias MyAppWeb.Presence
def join("some:topic", _params, socket) do
send(self(), :after_join)
{:ok, assign(socket, :user_id, ...)}
end
def handle_info(:after_join, socket) do
{:ok, _} = Presence.track(socket, socket.assigns.user_id, %{
online_at: inspect(System.system_time(:second))
})
push(socket, "presence_state", Presence.list(socket))
{:noreply, socket}
end
end
```
In the example above, `Presence.track` is used to register this channel's process as a presence for the socket's user ID, with a map of metadata. Next, the current presence information for the socket's topic is pushed to the client as a `"presence_state"` event.
Finally, a diff of presence join and leave events will be sent to the client as they happen in real-time with the "presence\_diff" event. The diff structure will be a map of `:joins` and `:leaves` of the form:
```
%{
joins: %{"123" => %{metas: [%{status: "away", phx_ref: ...}]}},
leaves: %{"456" => %{metas: [%{status: "online", phx_ref: ...}]}}
},
```
See [`list/1`](#c:list/1) for more information on the presence data structure.
Fetching Presence Information
------------------------------
Presence metadata should be minimized and used to store small, ephemeral state, such as a user's "online" or "away" status. More detailed information, such as user details that need to be fetched from the database, can be achieved by overriding the [`fetch/2`](#c:fetch/2) function.
The [`fetch/2`](#c:fetch/2) callback is triggered when using [`list/1`](#c:list/1) and on every update, and it serves as a mechanism to fetch presence information a single time, before broadcasting the information to all channel subscribers. This prevents N query problems and gives you a single place to group isolated data fetching to extend presence metadata.
The function must return a map of data matching the outlined Presence data structure, including the `:metas` key, but can extend the map of information to include any additional information. For example:
```
def fetch(_topic, presences) do
users = presences |> Map.keys() |> Accounts.get_users_map()
for {key, %{metas: metas}} <- presences, into: %{} do
{key, %{metas: metas, user: users[String.to_integer(key)]}}
end
end
```
Where `Account.get_users_map/1` could be implemented like:
```
def get_users_map(ids) do
query =
from u in User,
where: u.id in ^ids,
select: {u.id, u}
query |> Repo.all() |> Enum.into(%{})
end
```
The `fetch/2` function above fetches all users from the database who have registered presences for the given topic. The presences information is then extended with a `:user` key of the user's information, while maintaining the required `:metas` field from the original presence data.
Testing with Presence
----------------------
Every time the `fetch` callback is invoked, it is done from a separate process. Given those processes run asynchronously, it is often necessary to guarantee they have been shutdown at the end of every test. This can be done by using ExUnit's `on_exit` hook plus `fetchers_pids` function:
```
on_exit(fn ->
for pid <- MyAppWeb.Presence.fetchers_pids() do
ref = Process.monitor(pid)
assert_receive {:DOWN, ^ref, _, _, _}, 1000
end
end)
```
Summary
========
Types
------
[presence()](#t:presence/0) [presences()](#t:presences/0) [topic()](#t:topic/0) Callbacks
----------
[fetch(topic, presences)](#c:fetch/2) Extend presence information with additional data.
[get\_by\_key(arg1, key)](#c:get_by_key/2) Returns the map of presence metadata for a socket/topic-key pair.
[list(arg1)](#c:list/1) Returns presences for a socket/topic.
[track(socket, key, meta)](#c:track/3) Track a channel's process as a presence.
[track(pid, topic, key, meta)](#c:track/4) Track an arbitrary process as a presence.
[untrack(socket, key)](#c:untrack/2) Stop tracking a channel's process.
[untrack(pid, topic, key)](#c:untrack/3) Stop tracking a process.
[update(socket, key, meta)](#c:update/3) Update a channel presence's metadata.
[update(pid, topic, key, meta)](#c:update/4) Update a process presence's metadata.
Types
======
### presence()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L141)
```
@type presence() :: %{key: String.t(), meta: map()}
```
### presences()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L140)
```
@type presences() :: %{required(String.t()) => %{metas: [map()]}}
```
### topic()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L142)
```
@type topic() :: String.t()
```
Callbacks
==========
### fetch(topic, presences)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L278)
```
@callback fetch(topic(), presences()) :: presences()
```
Extend presence information with additional data.
When [`list/1`](#c:list/1) is used to list all presences of the given `topic`, this callback is triggered once to modify the result before it is broadcasted to all channel subscribers. This avoids N query problems and provides a single place to extend presence metadata. You must return a map of data matching the original result, including the `:metas` key, but can extend the map to include any additional information.
The default implementation simply passes `presences` through unchanged.
#### Example
```
def fetch(_topic, presences) do
query =
from u in User,
where: u.id in ^Map.keys(presences),
select: {u.id, u}
users = query |> Repo.all() |> Enum.into(%{})
for {key, %{metas: metas}} <- presences, into: %{} do
{key, %{metas: metas, user: users[key]}}
end
end
```
### get\_by\_key(arg1, key)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L249)
```
@callback get_by_key(Phoenix.Socket.t() | topic(), key :: String.t()) :: presences()
```
Returns the map of presence metadata for a socket/topic-key pair.
#### Examples
Uses the same data format as [`list/1`](#c:list/1), but only returns metadata for the presences under a topic and key pair. For example, a user with key `"user1"`, connected to the same chat room `"room:1"` from two devices, could return:
```
iex> MyPresence.get_by_key("room:1", "user1")
[%{name: "User 1", metas: [%{device: "Desktop"}, %{device: "Mobile"}]}]
```
Like [`list/1`](#c:list/1), the presence metadata is passed to the `fetch` callback of your presence module to fetch any additional information.
### list(arg1)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L231)
```
@callback list(Phoenix.Socket.t() | topic()) :: presences()
```
Returns presences for a socket/topic.
#### Presence data structure
The presence information is returned as a map with presences grouped by key, cast as a string, and accumulated metadata, with the following form:
```
%{key => %{metas: [%{phx_ref: ..., ...}, ...]}}
```
For example, imagine a user with id `123` online from two different devices, as well as a user with id `456` online from just one device. The following presence information might be returned:
```
%{"123" => %{metas: [%{status: "away", phx_ref: ...},
%{status: "online", phx_ref: ...}]},
"456" => %{metas: [%{status: "online", phx_ref: ...}]}}
```
The keys of the map will usually point to a resource ID. The value will contain a map with a `:metas` key containing a list of metadata for each resource. Additionally, every metadata entry will contain a `:phx_ref` key which can be used to uniquely identify metadata for a given key. In the event that the metadata was previously updated, a `:phx_ref_prev` key will be present containing the previous `:phx_ref` value.
### track(socket, key, meta)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L163)
```
@callback track(socket :: Phoenix.Socket.t(), key :: String.t(), meta :: map()) ::
{:ok, ref :: binary()} | {:error, reason :: term()}
```
Track a channel's process as a presence.
Tracked presences are grouped by `key`, cast as a string. For example, to group each user's channels together, use user IDs as keys. Each presence can be associated with a map of metadata to store small, ephemeral state, such as a user's online status. To store detailed information, see [`fetch/2`](#c:fetch/2).
#### Example
```
alias MyApp.Presence
def handle_info(:after_join, socket) do
{:ok, _} = Presence.track(socket, socket.assigns.user_id, %{
online_at: inspect(System.system_time(:second))
})
{:noreply, socket}
end
```
### track(pid, topic, key, meta)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L172)
```
@callback track(pid(), topic(), key :: String.t(), meta :: map()) ::
{:ok, ref :: binary()} | {:error, reason :: term()}
```
Track an arbitrary process as a presence.
Same with `track/3`, except track any process by `topic` and `key`.
### untrack(socket, key)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L179)
```
@callback untrack(socket :: Phoenix.Socket.t(), key :: String.t()) :: :ok
```
Stop tracking a channel's process.
### untrack(pid, topic, key)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L184)
```
@callback untrack(pid(), topic(), key :: String.t()) :: :ok
```
Stop tracking a process.
### update(socket, key, meta)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L192)
```
@callback update(
socket :: Phoenix.Socket.t(),
key :: String.t(),
meta :: map() | (map() -> map())
) ::
{:ok, ref :: binary()} | {:error, reason :: term()}
```
Update a channel presence's metadata.
Replace a presence's metadata by passing a new map or a function that takes the current map and returns a new one.
### update(pid, topic, key, meta)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/presence.ex#L201)
```
@callback update(pid(), topic(), key :: String.t(), meta :: map() | (map() -> map())) ::
{:ok, ref :: binary()} | {:error, reason :: term()}
```
Update a process presence's metadata.
Same as `update/3`, but with an arbitrary process.
| programming_docs |
phoenix Testing Contexts Testing Contexts
=================
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [Introduction to Testing guide](testing).
>
>
> **Requirement**: This guide expects that you have gone through the [Contexts guide](contexts).
>
>
At the end of the Introduction to Testing guide, we generated an HTML resource for posts using the following command:
```
$ mix phx.gen.html Blog Post posts title body:text
```
This gave us a number of modules for free, including a Blog context and a Post schema, alongside their respective test files. As we have learned in the Context guide, the Blog context is simply a module with functions to a particular area of our business domain, while Post schema maps to a particular table in our database.
In this guide, we are going to explore the tests generated for our contexts and schemas. Before we do anything else, let's run [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html) to make sure our test suite runs cleanly.
```
$ mix test
................
Finished in 0.6 seconds
19 tests, 0 failures
Randomized with seed 638414
```
Great. We've got nineteen tests and they are all passing!
Testing posts
--------------
If you open up `test/hello/blog_test.exs`, you will see a file with the following:
```
defmodule Hello.BlogTest do
use Hello.DataCase
alias Hello.Blog
describe "posts" do
alias Hello.Blog.Post
@valid_attrs %{body: "some body", title: "some title"}
@update_attrs %{body: "some updated body", title: "some updated title"}
@invalid_attrs %{body: nil, title: nil}
def post_fixture(attrs \\ %{}) do
{:ok, post} =
attrs
|> Enum.into(@valid_attrs)
|> Blog.create_post()
post
end
test "list_posts/0 returns all posts" do
post = post_fixture()
assert Blog.list_posts() == [post]
end
...
```
As the top of the file we import `Hello.DataCase`, which as we will see soon, it is similar to `HelloWeb.ConnCase`. While `HelloWeb.ConnCase` sets up helpers for working with connections, which is useful when testing controllers and views, `Hello.DataCase` provides functionality for working with contexts and schemas.
Next, we define an alias, so we can refer to `Hello.Blog` simply as `Blog`.
Then we start a `describe "posts"` block. A `describe` block is a feature in ExUnit that allows us to group similar tests. The reason why we have grouped all post related tests together is because contexts in Phoenix are capable of grouping multiple schemas together. For example, if we ran this command:
```
$ mix phx.gen.html Blog Comment comments post_id:references:posts body:text
```
We will get a bunch of new functions in the `Hello.Blog` context, plus a whole new `describe "comments"` block in our test file.
The tests defined for our context are very straight-forward. They call the functions in our context and assert on their results. As you can see, some of those tests even create entries in the database:
```
test "create_post/1 with valid data creates a post" do
assert {:ok, %Post{} = post} = Blog.create_post(@valid_attrs)
assert post.body == "some body"
assert post.title == "some title"
end
```
At this point, you may wonder: how can Phoenix make sure the data created in one of the tests do not affect other tests? We are glad you asked. To answer this question, let's talk about the `DataCase`.
The DataCase
-------------
If you open up `test/support/data_case.ex`, you will find the following:
```
defmodule Hello.DataCase do
use ExUnit.CaseTemplate
using do
quote do
alias Hello.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Hello.DataCase
end
end
setup tags do
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Demo.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
:ok
end
def errors_on(changeset) do
...
end
end
```
`Hello.DataCase` is another [`ExUnit.CaseTemplate`](https://hexdocs.pm/ex_unit/ExUnit.CaseTemplate.html). In the `using` block, we can see all of the aliases and imports `DataCase` brings into our tests. The `setup` chunk for `DataCase` is very similar to the one from `ConnCase`. As we can see, most of the `setup` block revolves around setting up a SQL Sandbox.
The SQL Sandbox is precisely what allows our tests to write to the database without affecting any of the other tests. In a nutshell, at the beginning of every test, we start a transaction in the database. When the test is over, we automatically rollback the transaction, effectively erasing all of the data created in the test.
Furthermore, the SQL Sandbox allows multiple tests to run concurrently, even if they talk to the database. This feature is provided for PostgreSQL databases and it can be used to further speed up your contexts and controllers tests by adding a `async: true` flag when using them:
```
use Hello.DataCase, async: true
```
There are some considerations you need to have in mind when running asynchronous tests with the sandbox, so please refer to the [`Ecto.Adapters.SQL.Sandbox`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html) for more information.
Finally at the end of the of the `DataCase` module we can find a function named `errors_on` with some examples of how to use it. This function is used for testing any validation we may want to add to our schemas. Let's give it a try by adding our own validations and then testing them.
Testing schemas
----------------
When we generate our HTML Post resource, Phoenix generated a Blog context and a Post schema. It generated a test file for the context, but no test file for the schema. However, this doesn't mean we don't need to test the schema, it just means we did not have to test the schema so far.
You may be wondering then: when do we test the context directly and when do we test the schema directly? The answer to this question is the same answer to the question of when do we add code to a context and when do we add it to the schema?
The general guideline is to keep all side-effect free code in the schema. In other words, if you are simply working with data structures, schemas and changesets, put it in the schema. The context will typically have the code that creates and updates schemas and then write them to a database or an API.
We'll be adding additional validations to the schema module, so that's a great opportunity to write some schema specific tests. Open up `lib/hello/blog/post.ex` and add the following validation to `def changeset`:
```
def changeset(post, attrs) do
post
|> cast(attrs, [:title, :body])
|> validate_required([:title, :body])
|> validate_length(:title, min: 2)
end
```
The new validation says the title needs to have at least 2 characters. Let's write a test for this. Create a new file at `test/hello/blog/post_test.exs` with this:
```
defmodule Hello.Blog.PostTest do
use Hello.DataCase, async: true
alias Hello.Blog.Post
test "title must be at least two characters long" do
changeset = Post.changeset(%Post{}, %{title: "I"})
assert %{title: ["should be at least 2 character(s)"]} = errors_on(changeset)
end
end
```
And that's it. As our business domain grows, we have well-defined places to test our contexts and schemas.
[← Previous Page Introduction to Testing](testing) [Next Page → Testing Controllers](testing_controllers)
phoenix mix phx.gen.live mix phx.gen.live
=================
Generates LiveView, templates, and context for a resource.
```
mix phx.gen.live Accounts User users name:string age:integer
```
The first argument is the context module. The context is an Elixir module that serves as an API boundary for the given resource. A context often holds many related resources. Therefore, if the context already exists, it will be augmented with functions for the given resource.
The second argument is the schema module. The schema is responsible for mapping the database fields into an Elixir struct.
The remaining arguments are the schema module plural name (used as the schema table name), and an optional list of attributes as their respective names and types. See [`mix help phx.gen.schema`](mix.tasks.phx.gen.schema) for more information on attributes.
When this command is run for the first time, a `ModalComponent` and `LiveHelpers` module will be created, along with the resource level LiveViews and components, including `UserLive.Index`, `UserLive.Show`, and `UserLive.FormComponent` modules for the new resource.
> Note: A resource may also be split over distinct contexts (such as `Accounts.User` and `Payments.User`).
>
>
Overall, this generator will add the following files:
* a context module in `lib/app/accounts.ex` for the accounts API
* a schema in `lib/app/accounts/user.ex`, with a `users` table
* a LiveView in `lib/app_web/live/user_live/show.ex`
* a LiveView in `lib/app_web/live/user_live/index.ex`
* a LiveComponent in `lib/app_web/live/user_live/form_component.ex`
* a helpers module in `lib/app_web/live/live_helpers.ex` with a modal
After file generation is complete, there will be output regarding required updates to the lib/app\_web/router.ex file.
```
Add the live routes to your browser scope in lib/app_web/router.ex:
live "/users", UserLive.Index, :index
live "/users/new", UserLive.Index, :new
live "/users/:id/edit", UserLive.Index, :edit
live "/users/:id", UserLive.Show, :show
live "/users/:id/show/edit", UserLive.Show, :edit
```
The context app
----------------
A migration file for the repository and test files for the context and controller features will also be generated.
The location of the web files (LiveView's, views, templates, etc.) in an umbrella application will vary based on the `:context_app` config located in your applications `:generators` configuration. When set, the Phoenix generators will generate web files directly in your lib and test folders since the application is assumed to be isolated to web specific functionality. If `:context_app` is not set, the generators will place web related lib and test files in a `web/` directory since the application is assumed to be handling both web and domain specific functionality. Example configuration:
```
config :my_app_web, :generators, context_app: :my_app
```
Alternatively, the `--context-app` option may be supplied to the generator:
```
mix phx.gen.live Accounts User users --context-app warehouse
```
Web namespace
--------------
By default, the LiveView modules will be namespaced by the web module. You can customize the web module namespace by passing the `--web` flag with a module name, for example:
```
mix phx.gen.live Accounts User users --web Sales
```
Which would generate the LiveViews in `lib/app_web/live/sales/user_live/`, namespaced `AppWeb.Sales.UserLive` instead of `AppWeb.UserLive`.
Customizing the context, schema, tables and migrations
-------------------------------------------------------
In some cases, you may wish to bootstrap HTML templates, LiveViews, and tests, but leave internal implementation of the context or schema to yourself. You can use the `--no-context` and `--no-schema` flags for file generation control.
You can also change the table name or configure the migrations to use binary ids for primary keys, see [`mix help phx.gen.schema`](mix.tasks.phx.gen.schema) for more information.
phoenix mix phx.gen.presence mix phx.gen.presence
=====================
Generates a Presence tracker.
```
$ mix phx.gen.presence
$ mix phx.gen.presence MyPresence
```
The argument, which defaults to `Presence`, defines the module name of the Presence tracker.
Generates a new file, `lib/my_app_web/channels/my_presence.ex`, where `my_presence` is the snake-cased version of the provided module name.
phoenix Phoenix.Endpoint.Cowboy2Adapter Phoenix.Endpoint.Cowboy2Adapter
================================
The Cowboy2 adapter for Phoenix.
Endpoint configuration
-----------------------
This adapter uses the following endpoint configuration:
* `:http` - the configuration for the HTTP server. It accepts all options as defined by [`Plug.Cowboy`](https://hexdocs.pm/plug_cowboy/). Defaults to `false`
* `:https` - the configuration for the HTTPS server. It accepts all options as defined by [`Plug.Cowboy`](https://hexdocs.pm/plug_cowboy/). Defaults to `false`
* `:drainer` - a drainer process that triggers when your application is shutting down to wait for any on-going request to finish. It accepts all options as defined by [`Plug.Cowboy.Drainer`](https://hexdocs.pm/plug_cowboy/Plug.Cowboy.Drainer.html). Defaults to `[]`, which will start a drainer process for each configured endpoint, but can be disabled by setting it to `false`.
Custom dispatch options
------------------------
You can provide custom dispatch options in order to use Phoenix's builtin Cowboy server with custom handlers. For example, to handle raw WebSockets [as shown in Cowboy's docs](https://github.com/ninenines/cowboy/tree/master/examples)).
The options are passed to both `:http` and `:https` keys in the endpoint configuration. However, once you pass your custom dispatch options, you will need to manually wire the Phoenix endpoint by adding the following rule:
```
{:_, Phoenix.Endpoint.Cowboy2Handler, {MyAppWeb.Endpoint, []}}
```
For example:
```
config :myapp, MyAppWeb.Endpoint,
http: [dispatch: [
{:_, [
{"/foo", MyAppWeb.CustomHandler, []},
{:_, Phoenix.Endpoint.Cowboy2Handler, {MyAppWeb.Endpoint, []}}
]}]]
```
It is also important to specify your handlers first, otherwise Phoenix will intercept the requests before they get to your handler.
phoenix Routing Routing
========
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [Request life-cycle guide](request_lifecycle).
>
>
Routers are the main hubs of Phoenix applications. They match HTTP requests to controller actions, wire up real-time channel handlers, and define a series of pipeline transformations scoped to a set of routes.
The router file that Phoenix generates, `lib/hello_web/router.ex`, will look something like this one:
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
end
# Other scopes may use custom stacks.
# scope "/api", HelloWeb do
# pipe_through :api
# end
# ...
end
```
Both the router and controller module names will be prefixed with the name you gave your application suffixed with `Web`.
The first line of this module, `use HelloWeb, :router`, simply makes Phoenix router functions available in our particular router.
Scopes have their own section in this guide, so we won't spend time on the `scope "/", HelloWeb do` block here. The `pipe_through :browser` line will get a full treatment in the "Pipelines" section of this guide. For now, you only need to know that pipelines allow a set of plugs to be applied to different sets of routes.
Inside the scope block, however, we have our first actual route:
```
get "/", PageController, :index
```
`get` is a Phoenix macro that corresponds to the HTTP verb GET. Similar macros exist for other HTTP verbs, including POST, PUT, PATCH, DELETE, OPTIONS, CONNECT, TRACE, and HEAD.
Examining routes
-----------------
Phoenix provides an excellent tool for investigating routes in an application: [`mix phx.routes`](mix.tasks.phx.routes).
Let's see how this works. Go to the root of a newly-generated Phoenix application and run [`mix phx.routes`](mix.tasks.phx.routes). You should see something like the following, generated with all routes you currently have:
```
$ mix phx.routes
page_path GET / HelloWeb.PageController :index
...
```
The route above tells us that any HTTP GET request for the root of the application will be handled by the `index` action of the `HelloWeb.PageController`.
`page_path` is an example of what Phoenix calls a path helper, and we'll talk about those very soon.
Resources
----------
The router supports other macros besides those for HTTP verbs like [`get`](phoenix.router#get/3), [`post`](phoenix.router#post/3), and [`put`](phoenix.router#put/3). The most important among them is [`resources`](phoenix.router#resources/4). Let's add a resource to our `lib/hello_web/router.ex` file like this:
```
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
resources "/users", UserController
...
end
```
For now it doesn't matter that we don't actually have a `HelloWeb.UserController`.
Run [`mix phx.routes`](mix.tasks.phx.routes) once again at the root of your project. You should see something like the following:
```
...
user_path GET /users HelloWeb.UserController :index
user_path GET /users/:id/edit HelloWeb.UserController :edit
user_path GET /users/new HelloWeb.UserController :new
user_path GET /users/:id HelloWeb.UserController :show
user_path POST /users HelloWeb.UserController :create
user_path PATCH /users/:id HelloWeb.UserController :update
PUT /users/:id HelloWeb.UserController :update
user_path DELETE /users/:id HelloWeb.UserController :delete
...
```
This is the standard matrix of HTTP verbs, paths, and controller actions. For a while, this was known as RESTful routes, but most consider this a misnomer nowadays. Let's look at them individually, in a slightly different order.
* A GET request to `/users` will invoke the `index` action to show all the users.
* A GET request to `/users/:id/edit` will invoke the `edit` action with an ID to retrieve an individual user from the data store and present the information in a form for editing.
* A GET request to `/users/new` will invoke the `new` action to present a form for creating a new user.
* A GET request to `/users/:id` will invoke the `show` action with an id to show an individual user identified by that ID.
* A POST request to `/users` will invoke the `create` action to save a new user to the data store.
* A PATCH request to `/users/:id` will invoke the `update` action with an ID to save the updated user to the data store.
* A PUT request to `/users/:id` will also invoke the `update` action with an ID to save the updated user to the data store.
* A DELETE request to `/users/:id` will invoke the `delete` action with an ID to remove the individual user from the data store.
If we don't need all these routes, we can be selective using the `:only` and `:except` options to filter specific actions.
Let's say we have a read-only posts resource. We could define it like this:
```
resources "/posts", PostController, only: [:index, :show]
```
Running [`mix phx.routes`](mix.tasks.phx.routes) shows that we now only have the routes to the index and show actions defined.
```
post_path GET /posts HelloWeb.PostController :index
post_path GET /posts/:id HelloWeb.PostController :show
```
Similarly, if we have a comments resource, and we don't want to provide a route to delete one, we could define a route like this.
```
resources "/comments", CommentController, except: [:delete]
```
Running [`mix phx.routes`](mix.tasks.phx.routes) now shows that we have all the routes except the DELETE request to the delete action.
```
comment_path GET /comments HelloWeb.CommentController :index
comment_path GET /comments/:id/edit HelloWeb.CommentController :edit
comment_path GET /comments/new HelloWeb.CommentController :new
comment_path GET /comments/:id HelloWeb.CommentController :show
comment_path POST /comments HelloWeb.CommentController :create
comment_path PATCH /comments/:id HelloWeb.CommentController :update
PUT /comments/:id HelloWeb.CommentController :update
```
The [`Phoenix.Router.resources/4`](phoenix.router#resources/4) macro describes additional options for customizing resource routes.
Path helpers
-------------
Path helpers are dynamically defined functions. They allow us to retrieve the path corresponding to a given controller-action pair. The name of each path helper is derived from the name of the controller used in the route definition. For our controller `HelloWeb.PageController`, `page_path` is the function that will return the path, which in this case is the root of our application.
Let's see it in action. Run `iex -S mix` at the root of the project. When we call the `page_path` function on our router helpers with the endpoint or connection and action as arguments, it returns the path to us.
```
iex> HelloWeb.Router.Helpers.page_path(HelloWeb.Endpoint, :index)
"/"
```
This is significant because we can use the `page_path` function in a template to link to the root of our application. We can then use this helper in our templates:
```
<%= link "Welcome Page!", to: Routes.page_path(@conn, :index) %>
```
Note that path helpers are dynamically defined on the `Router.Helpers` module for an individual application. For us, that is `HelloWeb.Router.Helpers`.
The reason we can use `Routes.page_path` instead of the full `HelloWeb.Router.Helpers.page_path` name is because `HelloWeb.Router.Helpers` is aliased as `Routes` by default in the `view_helpers/0` block defined inside `lib/hello_web.ex`. This definition is made available to our templates through `use HelloWeb, :view`.
We can, of course, use `HelloWeb.Router.Helpers.page_path(@conn, :index)` instead, but the convention is to use the aliased version for conciseness. Note that the alias is only set automatically for use in views, controllers and templates - outside these, you need either the full name, or to alias it yourself inside the module definition with `alias HelloWeb.Router.Helpers, as: Routes`.
Using path helpers makes it easy to ensure our controllers, views, and templates link to pages our router can actually handle.
### More on path helpers
When we ran [`mix phx.routes`](mix.tasks.phx.routes) for our user resource, it listed the `user_path` as the path helper function for each output line. Here is what that translates to for each action:
```
iex> alias HelloWeb.Router.Helpers, as: Routes
iex> alias HelloWeb.Endpoint
iex> Routes.user_path(Endpoint, :index)
"/users"
iex> Routes.user_path(Endpoint, :show, 17)
"/users/17"
iex> Routes.user_path(Endpoint, :new)
"/users/new"
iex> Routes.user_path(Endpoint, :create)
"/users"
iex> Routes.user_path(Endpoint, :edit, 37)
"/users/37/edit"
iex> Routes.user_path(Endpoint, :update, 37)
"/users/37"
iex> Routes.user_path(Endpoint, :delete, 17)
"/users/17"
```
What about paths with query strings? By adding an optional fourth argument of key-value pairs, the path helpers will return those pairs in the query string.
```
iex> Routes.user_path(Endpoint, :show, 17, admin: true, active: false)
"/users/17?admin=true&active=false"
```
What if we need a full URL instead of a path? Just replace `_path` with `_url`:
```
iex> Routes.user_url(Endpoint, :index)
"http://localhost:4000/users"
```
The `*_url` functions will get the host, port, proxy port, and SSL information needed to construct the full URL from the configuration parameters set for each environment. We'll talk about configuration in more detail in its own guide. For now, you can take a look at `config/dev.exs` file in your own project to see those values.
Whenever possible, prefer to pass a `conn` (or `@conn` in your views) in place of an endpoint module.
Nested resources
-----------------
It is also possible to nest resources in a Phoenix router. Let's say we also have a `posts` resource that has a many-to-one relationship with `users`. That is to say, a user can create many posts, and an individual post belongs to only one user. We can represent that by adding a nested route in `lib/hello_web/router.ex` like this:
```
resources "/users", UserController do
resources "/posts", PostController
end
```
When we run [`mix phx.routes`](mix.tasks.phx.routes) now, in addition to the routes we saw for `users` above, we get the following set of routes:
```
...
user_post_path GET /users/:user_id/posts HelloWeb.PostController :index
user_post_path GET /users/:user_id/posts/:id/edit HelloWeb.PostController :edit
user_post_path GET /users/:user_id/posts/new HelloWeb.PostController :new
user_post_path GET /users/:user_id/posts/:id HelloWeb.PostController :show
user_post_path POST /users/:user_id/posts HelloWeb.PostController :create
user_post_path PATCH /users/:user_id/posts/:id HelloWeb.PostController :update
PUT /users/:user_id/posts/:id HelloWeb.PostController :update
user_post_path DELETE /users/:user_id/posts/:id HelloWeb.PostController :delete
...
```
We see that each of these routes scopes the posts to a user ID. For the first one, we will invoke `PostController`'s `index` action, but we will pass in a `user_id`. This implies that we would display all the posts for that individual user only. The same scoping applies for all these routes.
When calling path helper functions for nested routes, we will need to pass the IDs in the order they came in the route definition. For the following `show` route, `42` is the `user_id`, and `17` is the `post_id`. Let's remember to alias our `HelloWeb.Endpoint` before we begin.
```
iex> alias HelloWeb.Endpoint
iex> HelloWeb.Router.Helpers.user_post_path(Endpoint, :show, 42, 17)
"/users/42/posts/17"
```
Again, if we add a key-value pair to the end of the function call, it is added to the query string.
```
iex> HelloWeb.Router.Helpers.user_post_path(Endpoint, :index, 42, active: true)
"/users/42/posts?active=true"
```
If we hadn't aliased the `Helpers` module as we did before (remember it is only automatically aliased for views, templates and controllers), and since we are inside `iex`, we'll have to do it ourselves:
```
iex> alias HelloWeb.Router.Helpers, as: Routes
iex> alias HelloWeb.Endpoint
iex> Routes.user_post_path(Endpoint, :index, 42, active: true)
"/users/42/posts?active=true"
```
Scoped routes
--------------
Scopes are a way to group routes under a common path prefix and scoped set of plugs. We might want to do this for admin functionality, APIs, and especially for versioned APIs. Let's say we have user-generated reviews on a site, and that those reviews first need to be approved by an administrator. The semantics of these resources are quite different, and they might not share the same controller. Scopes enable us to segregate these routes.
The paths to the user-facing reviews would look like a standard resource.
```
/reviews
/reviews/1234
/reviews/1234/edit
...
```
The administration review paths can be prefixed with `/admin`.
```
/admin/reviews
/admin/reviews/1234
/admin/reviews/1234/edit
...
```
We accomplish this with a scoped route that sets a path option to `/admin` like this one. We can nest this scope inside another scope, but instead, let's set it by itself at the root, by adding to `lib/hello_web/router.ex` the following:
```
scope "/admin", HelloWeb.Admin do
pipe_through :browser
resources "/reviews", ReviewController
end
```
We define a new scope where all routes are prefixed with `/admin` and all controllers are under the `HelloWeb.Admin` namespace.
Running [`mix phx.routes`](mix.tasks.phx.routes) again, in addition to the previous set of routes we get the following:
```
...
review_path GET /admin/reviews HelloWeb.Admin.ReviewController :index
review_path GET /admin/reviews/:id/edit HelloWeb.Admin.ReviewController :edit
review_path GET /admin/reviews/new HelloWeb.Admin.ReviewController :new
review_path GET /admin/reviews/:id HelloWeb.Admin.ReviewController :show
review_path POST /admin/reviews HelloWeb.Admin.ReviewController :create
review_path PATCH /admin/reviews/:id HelloWeb.Admin.ReviewController :update
PUT /admin/reviews/:id HelloWeb.Admin.ReviewController :update
review_path DELETE /admin/reviews/:id HelloWeb.Admin.ReviewController :delete
...
```
This looks good, but there is a problem here. Remember that we wanted both user-facing review routes `/reviews` and the admin ones `/admin/reviews`. If we now include the user-facing reviews in our router under the root scope like this:
```
scope "/", HelloWeb do
pipe_through :browser
...
resources "/reviews", ReviewController
end
scope "/admin", HelloWeb.Admin do
pipe_through :browser
resources "/reviews", ReviewController
end
```
and we run [`mix phx.routes`](mix.tasks.phx.routes), we get this output:
```
...
review_path GET /reviews HelloWeb.ReviewController :index
review_path GET /reviews/:id/edit HelloWeb.ReviewController :edit
review_path GET /reviews/new HelloWeb.ReviewController :new
review_path GET /reviews/:id HelloWeb.ReviewController :show
review_path POST /reviews HelloWeb.ReviewController :create
review_path PATCH /reviews/:id HelloWeb.ReviewController :update
PUT /reviews/:id HelloWeb.ReviewController :update
review_path DELETE /reviews/:id HelloWeb.ReviewController :delete
...
review_path GET /admin/reviews HelloWeb.Admin.ReviewController :index
review_path GET /admin/reviews/:id/edit HelloWeb.Admin.ReviewController :edit
review_path GET /admin/reviews/new HelloWeb.Admin.ReviewController :new
review_path GET /admin/reviews/:id HelloWeb.Admin.ReviewController :show
review_path POST /admin/reviews HelloWeb.Admin.ReviewController :create
review_path PATCH /admin/reviews/:id HelloWeb.Admin.ReviewController :update
PUT /admin/reviews/:id HelloWeb.Admin.ReviewController :update
review_path DELETE /admin/reviews/:id HelloWeb.Admin.ReviewController :delete
```
The actual routes we get all look right, except for the path helper `review_path` at the beginning of each line. We are getting the same helper for both the user facing review routes and the admin ones, which is not correct.
We can fix this problem by adding an `as: :admin` option to our admin scope:
```
scope "/admin", HelloWeb.Admin, as: :admin do
pipe_through :browser
resources "/reviews", ReviewController
end
```
[`mix phx.routes`](mix.tasks.phx.routes) now shows us we have what we are looking for.
```
...
review_path GET /reviews HelloWeb.ReviewController :index
review_path GET /reviews/:id/edit HelloWeb.ReviewController :edit
review_path GET /reviews/new HelloWeb.ReviewController :new
review_path GET /reviews/:id HelloWeb.ReviewController :show
review_path POST /reviews HelloWeb.ReviewController :create
review_path PATCH /reviews/:id HelloWeb.ReviewController :update
PUT /reviews/:id HelloWeb.ReviewController :update
review_path DELETE /reviews/:id HelloWeb.ReviewController :delete
...
admin_review_path GET /admin/reviews HelloWeb.Admin.ReviewController :index
admin_review_path GET /admin/reviews/:id/edit HelloWeb.Admin.ReviewController :edit
admin_review_path GET /admin/reviews/new HelloWeb.Admin.ReviewController :new
admin_review_path GET /admin/reviews/:id HelloWeb.Admin.ReviewController :show
admin_review_path POST /admin/reviews HelloWeb.Admin.ReviewController :create
admin_review_path PATCH /admin/reviews/:id HelloWeb.Admin.ReviewController :update
PUT /admin/reviews/:id HelloWeb.Admin.ReviewController :update
admin_review_path DELETE /admin/reviews/:id HelloWeb.Admin.ReviewController :delete
```
The path helpers now return what we want them to as well. Run `iex -S mix` and give it a try yourself.
```
iex> HelloWeb.Router.Helpers.review_path(HelloWeb.Endpoint, :index)
"/reviews"
iex> HelloWeb.Router.Helpers.admin_review_path(HelloWeb.Endpoint, :show, 1234)
"/admin/reviews/1234"
```
What if we had a number of resources that were all handled by admins? We could put all of them inside the same scope like this:
```
scope "/admin", HelloWeb.Admin, as: :admin do
pipe_through :browser
resources "/images", ImageController
resources "/reviews", ReviewController
resources "/users", UserController
end
```
Here's what [`mix phx.routes`](mix.tasks.phx.routes) tells us:
```
...
admin_image_path GET /admin/images HelloWeb.Admin.ImageController :index
admin_image_path GET /admin/images/:id/edit HelloWeb.Admin.ImageController :edit
admin_image_path GET /admin/images/new HelloWeb.Admin.ImageController :new
admin_image_path GET /admin/images/:id HelloWeb.Admin.ImageController :show
admin_image_path POST /admin/images HelloWeb.Admin.ImageController :create
admin_image_path PATCH /admin/images/:id HelloWeb.Admin.ImageController :update
PUT /admin/images/:id HelloWeb.Admin.ImageController :update
admin_image_path DELETE /admin/images/:id HelloWeb.Admin.ImageController :delete
admin_review_path GET /admin/reviews HelloWeb.Admin.ReviewController :index
admin_review_path GET /admin/reviews/:id/edit HelloWeb.Admin.ReviewController :edit
admin_review_path GET /admin/reviews/new HelloWeb.Admin.ReviewController :new
admin_review_path GET /admin/reviews/:id HelloWeb.Admin.ReviewController :show
admin_review_path POST /admin/reviews HelloWeb.Admin.ReviewController :create
admin_review_path PATCH /admin/reviews/:id HelloWeb.Admin.ReviewController :update
PUT /admin/reviews/:id HelloWeb.Admin.ReviewController :update
admin_review_path DELETE /admin/reviews/:id HelloWeb.Admin.ReviewController :delete
admin_user_path GET /admin/users HelloWeb.Admin.UserController :index
admin_user_path GET /admin/users/:id/edit HelloWeb.Admin.UserController :edit
admin_user_path GET /admin/users/new HelloWeb.Admin.UserController :new
admin_user_path GET /admin/users/:id HelloWeb.Admin.UserController :show
admin_user_path POST /admin/users HelloWeb.Admin.UserController :create
admin_user_path PATCH /admin/users/:id HelloWeb.Admin.UserController :update
PUT /admin/users/:id HelloWeb.Admin.UserController :update
admin_user_path DELETE /admin/users/:id HelloWeb.Admin.UserController :delete
```
This is great, exactly what we want. Note how every route, path helper and controller is properly namespaced.
Scopes can also be arbitrarily nested, but you should do it carefully as nesting can sometimes make our code confusing and less clear. With that said, suppose that we had a versioned API with resources defined for images, reviews, and users. Then technically, we could set up routes for the versioned API like this:
```
scope "/api", HelloWeb.Api, as: :api do
pipe_through :api
scope "/v1", V1, as: :v1 do
resources "/images", ImageController
resources "/reviews", ReviewController
resources "/users", UserController
end
end
```
You can run [`mix phx.routes`](mix.tasks.phx.routes) to see how these definitions will look like.
Interestingly, we can use multiple scopes with the same path as long as we are careful not to duplicate routes. The following router is perfectly fine with two scopes defined for the same path:
```
defmodule HelloWeb.Router do
use Phoenix.Router
...
scope "/", HelloWeb do
pipe_through :browser
resources "/users", UserController
end
scope "/", AnotherAppWeb do
pipe_through :browser
resources "/posts", PostController
end
...
end
```
If we do duplicate a route — which means two routes having the same path and the same alias — we'll get this familiar warning:
```
warning: this clause cannot match because a previous clause at line 16 always matches
```
Pipelines
----------
We have come quite a long way in this guide without talking about one of the first lines we saw in the router: `pipe_through :browser`. It's time to fix that.
Pipelines are a series of plugs that can be attached to specific scopes. If you are not familiar with plugs, we have an [in-depth guide about them](plug).
Routes are defined inside scopes and scopes may pipe through multiple pipelines. Once a route matches, Phoenix invokes all plugs defined in all pipelines associated to that route. For example, accessing `/` will pipe through the `:browser` pipeline, consequently invoking all of its plugs.
Phoenix defines two pipelines by default, `:browser` and `:api`, which can be used for a number of common tasks. In turn we can customize them as well as create new pipelines to meet our needs.
### The `:browser` and `:api` pipelines
As their names suggest, the `:browser` pipeline prepares for routes which render requests for a browser, and the `:api` pipeline prepares for routes which produce data for an API.
The `:browser` pipeline has six plugs: The `plug :accepts, ["html"]` defines the accepted request format or formats. `:fetch_session`, which, naturally, fetches the session data and makes it available in the connection. `:fetch_live_flash`, which fetches any flash messages from LiveView and merges them with the controller flash messages. Then, the plug `:put_root_layout` will store the root layout for rendering purposes. Later `:protect_from_forgery` and `:put_secure_browser_headers`, protects form posts from cross-site forgery.
Currently, the `:api` pipeline only defines `plug :accepts, ["json"]`.
The router invokes a pipeline on a route defined within a scope. Routes outside of a scope have no pipelines. Although the use of nested scopes is discouraged (see above the versioned API example), if we call `pipe_through` within a nested scope, the router will invoke all `pipe_through`'s from parent scopes, followed by the nested one.
Those are a lot of words bunched up together. Let's take a look at some examples to untangle their meaning.
Here's another look at the router from a newly generated Phoenix application, this time with the `/api` scope uncommented back in and a route added.
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
end
# Other scopes may use custom stacks.
scope "/api", HelloWeb do
pipe_through :api
resources "/reviews", ReviewController
end
# ...
end
```
When the server accepts a request, the request will always first pass through the plugs in our endpoint, after which it will attempt to match on the path and HTTP verb.
Let's say that the request matches our first route: a GET to `/`. The router will first pipe that request through the `:browser` pipeline - which will fetch the session data, fetch the flash, and execute forgery protection - before it dispatches the request to `PageController`'s `index` action.
Conversely, suppose the request matches any of the routes defined by the [`resources/2`](phoenix.router#resources/2) macro. In that case, the router will pipe it through the `:api` pipeline — which currently only performs content negotiation — before it dispatches further to the correct action of the `HelloWeb.ReviewController`.
If no route matches, no pipeline is invoked and a 404 error is raised.
Let's stretch these ideas out a little bit more. What if we need to pipe requests through both `:browser` and one or more custom pipelines? We simply `pipe_through` a list of pipelines, and Phoenix will invoke them in order.
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
...
scope "/reviews" do
pipe_through [:browser, :review_checks, :other_great_stuff]
resources "/", HelloWeb.ReviewController
end
end
```
Here's another example with two scopes that have different pipelines:
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
...
scope "/", HelloWeb do
pipe_through :browser
resources "/posts", PostController
end
scope "/reviews", HelloWeb do
pipe_through [:browser, :review_checks]
resources "/", ReviewController
end
end
```
In general, the scoping rules for pipelines behave as you might expect. In this example, all routes will pipe through the `:browser` pipeline. However, only the `reviews` resources routes will pipe through the `:review_checks` pipeline. Since we declared both pipes `pipe_through [:browser, :review_checks]` in a list of pipelines, Phoenix will `pipe_through` each of them as it invokes them in order.
### Creating new pipelines
Phoenix allows us to create our own custom pipelines anywhere in the router. To do so, we call the [`pipeline/2`](phoenix.router#pipeline/2) macro with these arguments: an atom for the name of our new pipeline and a block with all the plugs we want in it.
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :review_checks do
plug :ensure_authenticated_user
plug :ensure_user_owns_review
end
scope "/reviews", HelloWeb do
pipe_through [:browser, :review_checks]
resources "/", ReviewController
end
end
```
Note that pipelines themselves are plugs, so we can plug a pipeline inside another pipeline. For example, we could rewrite the `review_checks` pipeline above to automatically invoke `browser`, simplifying the downstream pipeline call:
```
pipeline :review_checks do
plug :browser
plug :ensure_authenticated_user
plug :ensure_user_owns_review
end
scope "/reviews", HelloWeb do
pipe_through :review_checks
resources "/", ReviewController
end
```
Forward
--------
The [`Phoenix.Router.forward/4`](phoenix.router#forward/4) macro can be used to send all requests that start with a particular path to a particular plug. Let's say we have a part of our system that is responsible (it could even be a separate application or library) for running jobs in the background, it could have its own web interface for checking the status of the jobs. We can forward to this admin interface using:
```
defmodule HelloWeb.Router do
use HelloWeb, :router
...
scope "/", HelloWeb do
...
end
forward "/jobs", BackgroundJob.Plug
end
```
This means that all routes starting with `/jobs` will be sent to the `HelloWeb.BackgroundJob.Plug` module. Inside the plug, you can match on subroutes, such as `/pending` and `/active` that shows the status of certain jobs.
We can even mix the [`forward/4`](phoenix.router#forward/4) macro with pipelines. If we wanted to ensure that the user was authenticated and was an administrator in order to see the jobs page, we could use the following in our router.
```
defmodule HelloWeb.Router do
use HelloWeb, :router
...
scope "/" do
pipe_through [:authenticate_user, :ensure_admin]
forward "/jobs", BackgroundJob.Plug
end
end
```
This means the plugs in the `authenticate_user` and `ensure_admin` pipelines will be called before the `BackgroundJob.Plug` allowing them to send an appropriate response and halt the request accordingly.
The `opts` that are received in the `init/1` callback of the Module Plug can be passed as a third argument. For example, maybe the background job lets you set the name of your application to be displayed on the page. This could be passed with:
```
forward "/jobs", BackgroundJob.Plug, name: "Hello Phoenix"
```
There is a fourth `router_opts` argument that can be passed. These options are outlined in the [`Phoenix.Router.scope/2`](phoenix.router#scope/2) documentation.
`BackgroundJob.Plug` can be implemented as any Module Plug discussed in the [Plug guide](plug). Note though it is not advised to forward to another Phoenix endpoint. This is because plugs defined by your app and the forwarded endpoint would be invoked twice, which may lead to errors.
Summary
--------
Routing is a big topic, and we have covered a lot of ground here. The important points to take away from this guide are:
* Routes which begin with an HTTP verb name expand to a single clause of the match function.
* Routes declared with `resources` expand to 8 clauses of the match function.
* Resources may restrict the number of match function clauses by using the `only:` or `except:` options.
* Any of these routes may be nested.
* Any of these routes may be scoped to a given path.
* Using the `as:` option in a scope can reduce duplication.
* Using the helper option for scoped routes eliminates unreachable paths.
[← Previous Page Plug](plug) [Next Page → Controllers](controllers)
| programming_docs |
phoenix Community Community
==========
The Elixir and Phoenix communities are friendly and welcoming. All questions and comments are valuable, so please come join the discussion!
There are a number of places to connect with community members at all experience levels.
* We're on Libera IRC in the [#elixir](https://web.libera.chat/?channels=#elixir) channel.
* [Request an invitation](https://elixir-slackin.herokuapp.com/) and join the #phoenix channel on [Slack](https://elixir-lang.slack.com).
* Feel free to join and check out the #phoenix channel on [Discord](https://discord.gg/elixir).
* Read about [bug reports](https://github.com/phoenixframework/phoenix/blob/master/CONTRIBUTING.md#bug-reports) or open an issue in the Phoenix [issue tracker](https://github.com/phoenixframework/phoenix/issues).
* Ask or answer questions about Phoenix on [Elixir Forum](https://elixirforum.com/c/phoenix-forum) or [Stack Overflow](https://stackoverflow.com/questions/tagged/phoenix-framework).
* To discuss new features in the framework, email the [phoenix-core mailing list](https://groups.google.com/group/phoenix-core).
* Follow the Phoenix Framework on [Twitter](https://twitter.com/elixirphoenix).
* The source for these guides is [on GitHub](https://github.com/phoenixframework/phoenix/tree/master/guides). To help improve the guides, please report an [issue](https://github.com/phoenixframework/phoenix/issues) or open a [pull request](https://github.com/phoenixframework/phoenix/pulls).
Books
------
* [Programming Phoenix LiveView - Interactive Elixir Web Programming Without Writing Any JavaScript - 2021 (by Bruce Tate and Sophie DeBenedetto)](https://pragprog.com/titles/liveview/programming-phoenix-liveview/)
* [Real-Time Phoenix - Build Highly Scalable Systems with Channels (by Stephen Bussey - 2020)](https://pragprog.com/book/sbsockets/real-time-phoenix)
* [Programming Phoenix 1.4 (by Bruce Tate and Phoenix core team members Chris McCord and José Valim - 2019)](https://pragprog.com/book/phoenix14/programming-phoenix-1-4)
* [Phoenix in Action (by Geoffrey Lessel - 2019)](https://manning.com/books/phoenix-in-action)
* [Phoenix Inside Out - Book Series (by Shankar Dhanasekaran - 2017)](https://shankardevy.com/phoenix-book/)
* [Functional Web Development with Elixir, OTP, and Phoenix Rethink the Modern Web App (by Lance Halvorsen - 2017)](https://pragprog.com/book/lhelph/functional-web-development-with-elixir-otp-and-phoenix)
Screencasts/Courses
--------------------
* [Phoenix LiveView Free Course (by The Pragmatic Studio - 2020)](https://pragmaticstudio.com/courses/phoenix-liveview)
* [Groxio LiveView: Self Study Program (by Bruce Tate - 2020)](https://grox.io/language/liveview/course)
* [Alchemist Camp: Learn Elixir and Phoenix by building (2018-2022)](https://alchemist.camp/episodes)
* [The Complete Elixir and Phoenix Bootcamp Master Functional Programming Techniques with Elixir and Phoenix while Learning to Build Compelling Web Applications (by Stephen Grider - 2017)](https://www.udemy.com/the-complete-elixir-and-phoenix-bootcamp-and-tutorial/)
* [Discover Elixir & Phoenix (by Tristan Edwards - 2017)](https://www.ludu.co/course/discover-elixir-phoenix)
* [Phoenix Framework Tutorial (by Tensor Programming - 2017)](https://www.youtube.com/watch?v=irDC1nWKhZ8&index=6&list=PLJbE2Yu2zumAgKjSPyFtvYjP5LqgzafQq)
* [Getting Started with Phoenix (by Pluralsight - 2017)](https://www.pluralsight.com/courses/phoenix-getting-started)
* [LearnPhoenix.tv: Learn how to Build Fast, Dependable Web Apps with Phoenix (2017)](https://www.learnphoenix.tv/)
* [LearnPhoenix.io: Build Scalable, Real-Time Apps with Phoenix, React, and React Native (2016)](https://www.learnphoenix.io/)
[← Previous Page Up and Running](up_and_running) [Next Page → Directory structure](directory_structure)
phoenix mix phx mix phx
========
Prints Phoenix tasks and their information.
```
$ mix phx
```
To print the Phoenix version, pass `-v` or `--version`, for example:
```
$ mix phx --version
```
phoenix Phoenix.Router.NoRouteError exception Phoenix.Router.NoRouteError exception
======================================
Exception raised when no route is found.
phoenix mix phx.new.web mix phx.new.web
================
Creates a new Phoenix web project within an umbrella project.
It expects the name of the OTP app as the first argument and for the command to be run inside your umbrella application's apps directory:
```
$ cd my_umbrella/apps
$ mix phx.new.web APP [--module MODULE] [--app APP]
```
This task is intended to create a bare Phoenix project without database integration, which interfaces with your greater umbrella application(s).
Examples
---------
```
$ mix phx.new.web hello_web
```
Is equivalent to:
```
$ mix phx.new.web hello_web --module HelloWeb
```
Supports the same options as the `phx.new` task. See [`Mix.Tasks.Phx.New`](mix.tasks.phx.new) for details.
phoenix Changelog for v1.6 Changelog for v1.6
===================
See the [upgrade guide](https://gist.github.com/chrismccord/2ab350f154235ad4a4d0f4de6decba7b) to upgrade from Phoenix 1.5.x.
Phoenix v1.6 requires Elixir v1.9+.
1.6.11 (2022-07-11)
--------------------
### JavaScript Client Enhancements
* Add convenience for getting longpoll reference with `getLongPollTransport`
### JavaScript Client Bug Fixes
* Cancel inflight longpoll requests on canceled longpoll session
* Do not attempt to flush socket buffer when tearing down socket on `replaceTransport`
1.6.10 (2022-06-01)
--------------------
### JavaScript Client Enhancements
* Add `ping` function to socket
1.6.9 (2022-05-16)
-------------------
### Bug Fixes
* [phx.gen.release] Fix generated .dockerignore comment
1.6.8 (2022-05-06)
-------------------
### Bug Fixes
* [phx.gen.release] Fix Ecto check failing to find Ecto in certain cases
1.6.7 (2022-04-14)
-------------------
### Enhancements
* [Endpoint] Add Endpoint init telemetry event
* [Endpoint] Prioritize user :http configuration for ranch to fix inet\_backend failing to be respected
* [Logger] Support log\_module in router metadata
* [phx.gen.release] Don't handle assets in Docker when directory doesn't exist
* [phx.gen.release] Skip generating migration files when ecto\_sql is not installed
### JavaScript Client Enhancements
* Switch to .mjs files for ESM for better compatibility across build tools
### JavaScript Client Bug Fixes
* Fix LongPoll callbacks in JS client causing errors on connection close
1.6.6 (2022-01-04)
-------------------
### Bug Fixes
* [Endpoint] Fix `check_origin: :conn` failing to match scheme
1.6.5 (2021-12-16)
-------------------
### Enhancements
* [Endpoint] Support `check_origin: :conn` to enforce origin on the connection's host, port, and scheme
### Bug Fixes
* Fix LiveView upload testing errors caused by [`Phoenix.ChannelTest`](phoenix.channeltest)
1.6.4 (2021-12-08)
-------------------
### Bug Fixes
* Fix incorrect `phx.gen.release` output
1.6.3 (2021-12-07)
-------------------
### Enhancements
* Add new `phx.gen.release` task for release and docker based deployments
* Add `fullsweep_after` option to the websocket transport
* Add `:force_watchers` option to [`Phoenix.Endpoint`](phoenix.endpoint) for running watchers even when web server is not started
### Bug Fixes
* Fix Endpoint `log: false` failing to disable logging
### JavaScript Client Bug Fixes
* Do not attempt to reconnect automatically if client gracefully closes connection
1.6.2 (2021-10-08)
-------------------
### Bug Fixes
* [phx.new] Fix external flag to esbuild using incorrect syntax
1.6.1 (2021-10-08)
-------------------
### Enhancements
* [phx.new] Add external flag to esbuild for fonts and image path loading
* [phx.gen.auth] No longer set `argon2` as the default hash algorithm for `phx.gen.auth` in favor of bcrypt for performance reasons on smaller hardware
### Bug Fixes
* Fix race conditions logging debug duplicate channel joins when no duplicate existed
### JavaScript Client Bug Fixes
* Export commonjs modules for backwards compatibility
1.6.0 (2021-09-24) 🚀
---------------------
### Enhancements
* [ConnTest] Add `path_params/2` for retrieving router path parameters out of dynamically returned URLs.
### JavaScript Client Bug Fixes
* Fix LongPoll transport undefined readyState check
1.6.0-rc.1 (2021-09-22)
------------------------
### Enhancements
* [mix phx.gen.auth] Validate bcrypt passwords are no longer than 72 bytes
* re-enable `phx.routes` task to support back to back invocations, such as for aliased mix route tasks
* [mix phx.gen.html] Remove comma after `for={@changeset}` on `form.html.heex`
### JavaScript Client Bug Fixes
* Fix messages for duplicate topic being dispatched to old channels
1.6.0-rc.0 (2021-08-26)
------------------------
### Enhancements
* [CodeReloader] Code reloading can now pick up changes to .beam files if they were compiled in a separate OS process than the Phoenix server
* [Controller] Do not create compile-time dependency for `action_fallback`
* [Endpoint] Allow custom error response from socket handler
* [Endpoint] Do not require a pubsub server in the socket (only inside channels)
* [mix phx.digest.clean] Add `--all` flag to [`mix phx.digest.clean`](mix.tasks.phx.digest.clean)
* [mix phx.gen.auth] Add [`mix phx.gen.auth`](mix.tasks.phx.gen.auth) generator
* [mix phx.gen.context] Support `enum` types and the `redact` option when declaring fields
* [mix phx.gen.notifier] A new generator to build notifiers that by default deliver emails
* [mix phx.new] Update [`mix phx.new`](mix.tasks.phx.new) to require Elixir v1.12 and use the new `config/runtime.exs`
* [mix phx.new] Set `plug_init_mode: :runtime` in generated `config/test.exs`
* [mix phx.new] Add description to Ecto telemetry metrics
* [mix phx.new] Use [`Ecto.Adapters.SQL.Sandbox.start_owner!/2`](https://hexdocs.pm/ecto_sql/3.8.1/Ecto.Adapters.SQL.Sandbox.html#start_owner!/2) in generators - this approach provides proper shutdown semantics for apps using LiveView and Presence
* [mix phx.new] Add `--install` and `--no-install` options to `phx.new`
* [mix phx.new] Add `--database sqlite3` option to `phx.new`
* [mix phx.new] Remove usage of Sass
* [mix phx.new] New applications now depend on Swoosh to deliver emails
* [mix phx.new] No longer generate a socket file by default, instead one can run [`mix phx.gen.socket`](mix.tasks.phx.gen.socket)
* [mix phx.new] No longer generates a home page using LiveView, instead one can run [`mix phx.gen.live`](mix.tasks.phx.gen.live)
* [mix phx.new] LiveView is now included by default. Passing `--no-live` will comment out lines in `app.js` and `Endpoint`
* [mix phx.server] Add `--open` flag
* [Router] Do not add compile time deps in `pipe_through`
* [View] Extracted [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) into its own project to facilitate reuse
### JavaScript Client Enhancements
* Add new `replaceTransport` function to socket with extended `onError` API to allow simplified LongPoll fallback
* Fire each event in a separate task for the LongPoll transport to fix ordering
* Optimize presence syncing
### Bug fixes
* [Controller] Return normalized paths in `current_path/1` and `current_path/2`
* [mix phx.gen.live] Fix a bug where tests with `utc_datetime` and `boolean` fields did not pass out of the box
### JavaScript Client Bug fixes
* Bind to `beforeunload` instead of `unload` to solve Firefox connection issues
* Fix presence onJoin including current metadata in new presence
### Deprecations
* [mix compile.phoenix] Adding the `:phoenix` compiler to your `mix.exs` (`compilers: [:phoenix] ++ Mix.compilers()`) is no longer required from Phoenix v1.6 forward if you are running on Elixir v1.11. Remove it from your `mix.exs` and you should gain faster compilation times too
* [Endpoint] Phoenix now requires Cowboy v2.7+
### Breaking changes
* [View] `@view_module` and `@view_template` are no longer set. Use [`Phoenix.Controller.view_module/1`](phoenix.controller#view_module/1) and [`Phoenix.Controller.view_template/1`](phoenix.controller#view_template/1) respectively, or pass explicit assigns from `Phoenix.View.render`.
v1.5
-----
The CHANGELOG for v1.5 releases can be found in the [v1.5 branch](https://github.com/phoenixframework/phoenix/blob/v1.5/CHANGELOG.md).
[← Previous Page API Reference](api-reference) [Next Page → Overview](overview)
phoenix mix phx.routes mix phx.routes
===============
Prints all routes for the default or a given router.
```
$ mix phx.routes
$ mix phx.routes MyApp.AnotherRouter
```
The default router is inflected from the application name unless a configuration named `:namespace` is set inside your application configuration. For example, the configuration:
```
config :my_app,
namespace: My.App
```
will exhibit the routes for `My.App.Router` when this task is invoked without arguments.
Umbrella projects do not have a default router and therefore always expect a router to be given. An alias can be added to mix.exs to automate this:
```
defp aliases do
[
"phx.routes": "phx.routes MyAppWeb.Router",
# aliases...
]
```
phoenix Phoenix.Socket.Message Phoenix.Socket.Message
=======================
Defines a message dispatched over transport to channels and vice-versa.
The message format requires the following keys:
* `:topic` - The string topic or topic:subtopic pair namespace, for example "messages", "messages:123"
* `:event`- The string event name, for example "phx\_join"
* `:payload` - The message payload
* `:ref` - The unique string ref
* `:join_ref` - The unique string ref when joining
Summary
========
Types
------
[t()](#t:t/0) Functions
----------
[from\_map!(map)](#from_map!/1) Converts a map with string keys into a message struct.
Types
======
### t()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/message.ex#L16)
```
@type t() :: %Phoenix.Socket.Message{
event: term(),
join_ref: term(),
payload: term(),
ref: term(),
topic: term()
}
```
Functions
==========
### from\_map!(map)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/message.ex#L24)
Converts a map with string keys into a message struct.
Raises [`Phoenix.Socket.InvalidMessageError`](phoenix.socket.invalidmessageerror) if not valid.
phoenix Phoenix.Param protocol Phoenix.Param protocol
=======================
A protocol that converts data structures into URL parameters.
This protocol is used by URL helpers and other parts of the Phoenix stack. For example, when you write:
```
user_path(conn, :edit, @user)
```
Phoenix knows how to extract the `:id` from `@user` thanks to this protocol.
By default, Phoenix implements this protocol for integers, binaries, atoms, and structs. For structs, a key `:id` is assumed, but you may provide a specific implementation.
Nil values cannot be converted to param.
Custom parameters
------------------
In order to customize the parameter for any struct, one can simply implement this protocol.
However, for convenience, this protocol can also be derivable. For example:
```
defmodule User do
@derive Phoenix.Param
defstruct [:id, :username]
end
```
By default, the derived implementation will also use the `:id` key. In case the user does not contain an `:id` key, the key can be specified with an option:
```
defmodule User do
@derive {Phoenix.Param, key: :username}
defstruct [:username]
end
```
will automatically use `:username` in URLs.
When using Ecto, you must call `@derive` before your `schema` call:
```
@derive {Phoenix.Param, key: :username}
schema "users" do
```
Summary
========
Types
------
[t()](#t:t/0) Functions
----------
[to\_param(term)](#to_param/1) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/param.ex#L1)
```
@type t() :: term()
```
Functions
==========
### to\_param(term)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/param.ex#L54)
```
@spec to_param(term()) :: String.t()
```
phoenix Phoenix.Token Phoenix.Token
==============
Tokens provide a way to generate and verify bearer tokens for use in Channels or API authentication.
The data stored in the token is signed to prevent tampering but not encrypted. This means it is safe to store identification information (such as user IDs) but should not be used to store confidential information (such as credit card numbers).
Example
--------
When generating a unique token for use in an API or Channel it is advised to use a unique identifier for the user, typically the id from a database. For example:
```
iex> user_id = 1
iex> token = Phoenix.Token.sign(MyAppWeb.Endpoint, "user auth", user_id)
iex> Phoenix.Token.verify(MyAppWeb.Endpoint, "user auth", token, max_age: 86400)
{:ok, 1}
```
In that example we have a user's id, we generate a token and verify it using the secret key base configured in the given `endpoint`. We guarantee the token will only be valid for one day by setting a max age (recommended).
The first argument to both [`sign/4`](#sign/4) and [`verify/4`](#verify/4) can be one of:
* the module name of a Phoenix endpoint (shown above) - where the secret key base is extracted from the endpoint
* [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) - where the secret key base is extracted from the endpoint stored in the connection
* [`Phoenix.Socket`](phoenix.socket) - where the secret key base is extracted from the endpoint stored in the socket
* a string, representing the secret key base itself. A key base with at least 20 randomly generated characters should be used to provide adequate entropy
The second argument is a [cryptographic salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) which must be the same in both calls to [`sign/4`](#sign/4) and [`verify/4`](#verify/4). For instance, it may be called "user auth" and treated as namespace when generating a token that will be used to authenticate users on channels or on your APIs.
The third argument can be any term (string, int, list, etc.) that you wish to codify into the token. Upon valid verification, this same term will be extracted from the token.
Usage
------
Once a token is signed, we can send it to the client in multiple ways.
One is via the meta tag:
```
<%= tag :meta, name: "channel_token",
content: Phoenix.Token.sign(@conn, "user auth", @current_user.id) %>
```
Or an endpoint that returns it:
```
def create(conn, params) do
user = User.create(params)
render(conn, "user.json",
%{token: Phoenix.Token.sign(conn, "user auth", user.id), user: user})
end
```
Once the token is sent, the client may now send it back to the server as an authentication mechanism. For example, we can use it to authenticate a user on a Phoenix channel:
```
defmodule MyApp.UserSocket do
use Phoenix.Socket
def connect(%{"token" => token}, socket, _connect_info) do
case Phoenix.Token.verify(socket, "user auth", token, max_age: 86400) do
{:ok, user_id} ->
socket = assign(socket, :user, Repo.get!(User, user_id))
{:ok, socket}
{:error, _} ->
:error
end
end
def connect(_params, _socket, _connect_info), do: :error
end
```
In this example, the phoenix.js client will send the token in the `connect` command which is then validated by the server.
[`Phoenix.Token`](phoenix.token#content) can also be used for validating APIs, handling password resets, e-mail confirmation and more.
Summary
========
Functions
----------
[decrypt(context, secret, token, opts \\ [])](#decrypt/4) Decrypts the original data from the token and verifies its integrity.
[encrypt(context, secret, data, opts \\ [])](#encrypt/4) Encodes, encrypts, and signs data into a token you can send to clients.
[sign(context, salt, data, opts \\ [])](#sign/4) Encodes and signs data into a token you can send to clients.
[verify(context, salt, token, opts \\ [])](#verify/4) Decodes the original data from the token and verifies its integrity.
Functions
==========
### decrypt(context, secret, token, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/token.ex#L215)
Decrypts the original data from the token and verifies its integrity.
#### Options
* `:max_age` - verifies the token only if it has been generated "max age" ago in seconds. Defaults to the max age signed in the token (86400)
* `:key_iterations` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 1000
* `:key_length` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 32
* `:key_digest` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to `:sha256`
### encrypt(context, secret, data, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/token.ex#L133)
Encodes, encrypts, and signs data into a token you can send to clients.
#### Options
* `:key_iterations` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 1000
* `:key_length` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 32
* `:key_digest` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to `:sha256`
* `:signed_at` - set the timestamp of the token in seconds. Defaults to `System.system_time(:second)`
### sign(context, salt, data, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/token.ex#L112)
Encodes and signs data into a token you can send to clients.
#### Options
* `:key_iterations` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 1000
* `:key_length` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 32
* `:key_digest` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to `:sha256`
* `:signed_at` - set the timestamp of the token in seconds. Defaults to `System.system_time(:second)`
* `:max_age` - the default maximum age of the token. Defaults to 86400 seconds (1 day) and it may be overridden on verify/4.
### verify(context, salt, token, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/token.ex#L193)
Decodes the original data from the token and verifies its integrity.
#### Examples
In this scenario we will create a token, sign it, then provide it to a client application. The client will then use this token to authenticate requests for resources from the server. See [`Phoenix.Token`](phoenix.token#content) summary for more info about creating tokens.
```
iex> user_id = 99
iex> secret = "kjoy3o1zeidquwy1398juxzldjlksahdk3"
iex> namespace = "user auth"
iex> token = Phoenix.Token.sign(secret, namespace, user_id)
```
The mechanism for passing the token to the client is typically through a cookie, a JSON response body, or HTTP header. For now, assume the client has received a token it can use to validate requests for protected resources.
When the server receives a request, it can use [`verify/4`](#verify/4) to determine if it should provide the requested resources to the client:
```
iex> Phoenix.Token.verify(secret, namespace, token, max_age: 86400)
{:ok, 99}
```
In this example, we know the client sent a valid token because [`verify/4`](#verify/4) returned a tuple of type `{:ok, user_id}`. The server can now proceed with the request.
However, if the client had sent an expired token, an invalid token, or `nil`, [`verify/4`](#verify/4) would have returned an error instead:
```
iex> Phoenix.Token.verify(secret, namespace, expired, max_age: 86400)
{:error, :expired}
iex> Phoenix.Token.verify(secret, namespace, invalid, max_age: 86400)
{:error, :invalid}
iex> Phoenix.Token.verify(secret, namespace, nil, max_age: 86400)
{:error, :missing}
```
#### Options
* `:max_age` - verifies the token only if it has been generated "max age" ago in seconds. A reasonable value is 1 day (86400 seconds)
* `:key_iterations` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 1000
* `:key_length` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 32
* `:key_digest` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.2/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to `:sha256`
| programming_docs |
phoenix mix phx.gen.channel mix phx.gen.channel
====================
Generates a Phoenix channel.
```
$ mix phx.gen.channel Room
```
Accepts the module name for the channel
The generated files will contain:
For a regular application:
* a channel in `lib/my_app_web/channels`
* a channel test in `test/my_app_web/channels`
For an umbrella application:
* a channel in `apps/my_app_web/lib/app_name_web/channels`
* a channel test in `apps/my_app_web/test/my_app_web/channels`
phoenix mix phx.digest mix phx.digest
===============
Digests and compresses static files.
```
$ mix phx.digest
$ mix phx.digest priv/static -o /www/public
```
The first argument is the path where the static files are located. The `-o` option indicates the path that will be used to save the digested and compressed files.
If no path is given, it will use `priv/static` as the input and output path.
The output folder will contain:
* the original file
* the file compressed with gzip
* a file containing the original file name and its digest
* a compressed file containing the file name and its digest
* a cache manifest file
Example of generated files:
* app.js
* app.js.gz
* app-eb0a5b9302e8d32828d8a73f137cc8f0.js
* app-eb0a5b9302e8d32828d8a73f137cc8f0.js.gz
* cache\_manifest.json
You can use [`mix phx.digest.clean`](mix.tasks.phx.digest.clean) to prune stale versions of the assets. If you want to remove all produced files, run `mix phx.digest.clean --all`.
vsn
----
It is possible to digest the stylesheet asset references without the query string "?vsn=d" with the option `--no-vsn`.
phoenix Phoenix.Channel behaviour Phoenix.Channel behaviour
==========================
Defines a Phoenix Channel.
Channels provide a means for bidirectional communication from clients that integrate with the [`Phoenix.PubSub`](https://hexdocs.pm/phoenix_pubsub/2.1.1/Phoenix.PubSub.html) layer for soft-realtime functionality.
Topics & Callbacks
-------------------
Every time you join a channel, you need to choose which particular topic you want to listen to. The topic is just an identifier, but by convention it is often made of two parts: `"topic:subtopic"`. Using the `"topic:subtopic"` approach pairs nicely with the [`Phoenix.Socket.channel/3`](phoenix.socket#channel/3) allowing you to match on all topics starting with a given prefix by using a splat (the `*` character) as the last character in the topic pattern:
```
channel "room:*", MyAppWeb.RoomChannel
```
Any topic coming into the router with the `"room:"` prefix would dispatch to `MyAppWeb.RoomChannel` in the above example. Topics can also be pattern matched in your channels' `join/3` callback to pluck out the scoped pattern:
```
# handles the special `"lobby"` subtopic
def join("room:lobby", _payload, socket) do
{:ok, socket}
end
# handles any other subtopic as the room ID, for example `"room:12"`, `"room:34"`
def join("room:" <> room_id, _payload, socket) do
{:ok, socket}
end
```
Authorization
--------------
Clients must join a channel to send and receive PubSub events on that channel. Your channels must implement a `join/3` callback that authorizes the socket for the given topic. For example, you could check if the user is allowed to join that particular room.
To authorize a socket in `join/3`, return `{:ok, socket}`. To refuse authorization in `join/3`, return `{:error, reply}`.
Incoming Events
----------------
After a client has successfully joined a channel, incoming events from the client are routed through the channel's `handle_in/3` callbacks. Within these callbacks, you can perform any action. Typically you'll either forward a message to all listeners with [`broadcast!/3`](#broadcast!/3), or push a message directly down the socket with [`push/3`](#push/3). Incoming callbacks must return the `socket` to maintain ephemeral state.
Here's an example of receiving an incoming `"new_msg"` event from one client, and broadcasting the message to all topic subscribers for this socket.
```
def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
broadcast!(socket, "new_msg", %{uid: uid, body: body})
{:noreply, socket}
end
```
General message payloads are received as maps, and binary data payloads are passed as a `{:binary, data}` tuple:
```
def handle_in("file_chunk", {:binary, chunk}, socket) do
...
{:reply, :ok, socket}
end
```
You can also push a message directly down the socket, in the form of a map, or a tagged `{:binary, data}` tuple:
```
# client asks for their current rank, push sent directly as a new event.
def handle_in("current_rank", _, socket) do
push(socket, "current_rank", %{val: Game.get_rank(socket.assigns[:user])})
push(socket, "photo", {:binary, File.read!(socket.assigns.photo_path)})
{:noreply, socket}
end
```
Replies
--------
In addition to pushing messages out when you receive a `handle_in` event, you can also reply directly to a client event for request/response style messaging. This is useful when a client must know the result of an operation or to simply ack messages.
For example, imagine creating a resource and replying with the created record:
```
def handle_in("create:post", attrs, socket) do
changeset = Post.changeset(%Post{}, attrs)
if changeset.valid? do
post = Repo.insert!(changeset)
response = MyAppWeb.PostView.render("show.json", %{post: post})
{:reply, {:ok, response}, socket}
else
response = MyAppWeb.ChangesetView.render("errors.json", %{changeset: changeset})
{:reply, {:error, response}, socket}
end
end
```
Alternatively, you may just want to ack the status of the operation:
```
def handle_in("create:post", attrs, socket) do
changeset = Post.changeset(%Post{}, attrs)
if changeset.valid? do
Repo.insert!(changeset)
{:reply, :ok, socket}
else
{:reply, :error, socket}
end
end
```
Like binary pushes, binary data is also supported with replies via a `{:binary, data}` tuple:
```
{:reply, {:ok, {:binary, bin}}, socket}
```
Intercepting Outgoing Events
-----------------------------
When an event is broadcasted with [`broadcast/3`](#broadcast/3), each channel subscriber can choose to intercept the event and have their `handle_out/3` callback triggered. This allows the event's payload to be customized on a socket by socket basis to append extra information, or conditionally filter the message from being delivered. If the event is not intercepted with [`Phoenix.Channel.intercept/1`](#intercept/1), then the message is pushed directly to the client:
```
intercept ["new_msg", "user_joined"]
# for every socket subscribing to this topic, append an `is_editable`
# value for client metadata.
def handle_out("new_msg", msg, socket) do
push(socket, "new_msg", Map.merge(msg,
%{is_editable: User.can_edit_message?(socket.assigns[:user], msg)}
))
{:noreply, socket}
end
# do not send broadcasted `"user_joined"` events if this socket's user
# is ignoring the user who joined.
def handle_out("user_joined", msg, socket) do
unless User.ignoring?(socket.assigns[:user], msg.user_id) do
push(socket, "user_joined", msg)
end
{:noreply, socket}
end
```
Broadcasting to an external topic
----------------------------------
In some cases, you will want to broadcast messages without the context of a `socket`. This could be for broadcasting from within your channel to an external topic, or broadcasting from elsewhere in your application like a controller or another process. Such can be done via your endpoint:
```
# within channel
def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
...
broadcast_from!(socket, "new_msg", %{uid: uid, body: body})
MyAppWeb.Endpoint.broadcast_from!(self(), "room:superadmin",
"new_msg", %{uid: uid, body: body})
{:noreply, socket}
end
# within controller
def create(conn, params) do
...
MyAppWeb.Endpoint.broadcast!("room:" <> rid, "new_msg", %{uid: uid, body: body})
MyAppWeb.Endpoint.broadcast!("room:superadmin", "new_msg", %{uid: uid, body: body})
redirect(conn, to: "/")
end
```
Terminate
----------
On termination, the channel callback `terminate/2` will be invoked with the error reason and the socket.
If we are terminating because the client left, the reason will be `{:shutdown, :left}`. Similarly, if we are terminating because the client connection was closed, the reason will be `{:shutdown, :closed}`.
If any of the callbacks return a `:stop` tuple, it will also trigger terminate with the reason given in the tuple.
`terminate/2`, however, won't be invoked in case of errors nor in case of exits. This is the same behaviour as you find in Elixir abstractions like [`GenServer`](https://hexdocs.pm/elixir/GenServer.html) and others. Similar to [`GenServer`](https://hexdocs.pm/elixir/GenServer.html), it would also be possible `:trap_exit` to guarantee that `terminate/2` is invoked. This practice is not encouraged though.
Typically speaking, if you want to clean something up, it is better to monitor your channel process and do the clean up from another process. All channel callbacks including `join/3` are called from within the channel process. Therefore, `self()` in any of them returns the PID to be monitored.
Exit reasons when stopping a channel
-------------------------------------
When the channel callbacks return a `:stop` tuple, such as:
```
{:stop, :shutdown, socket}
{:stop, {:error, :enoent}, socket}
```
the second argument is the exit reason, which follows the same behaviour as standard [`GenServer`](https://hexdocs.pm/elixir/GenServer.html) exits.
You have three options to choose from when shutting down a channel:
* `:normal` - in such cases, the exit won't be logged and linked processes do not exit
* `:shutdown` or `{:shutdown, term}` - in such cases, the exit won't be logged and linked processes exit with the same reason unless they're trapping exits
* any other term - in such cases, the exit will be logged and linked processes exit with the same reason unless they're trapping exits
Subscribing to external topics
-------------------------------
Sometimes you may need to programmatically subscribe a socket to external topics in addition to the internal `socket.topic`. For example, imagine you have a bidding system where a remote client dynamically sets preferences on products they want to receive bidding notifications on. Instead of requiring a unique channel process and topic per preference, a more efficient and simple approach would be to subscribe a single channel to relevant notifications via your endpoint. For example:
```
defmodule MyAppWeb.Endpoint.NotificationChannel do
use Phoenix.Channel
def join("notification:" <> user_id, %{"ids" => ids}, socket) do
topics = for product_id <- ids, do: "product:#{product_id}"
{:ok, socket
|> assign(:topics, [])
|> put_new_topics(topics)}
end
def handle_in("watch", %{"product_id" => id}, socket) do
{:reply, :ok, put_new_topics(socket, ["product:#{id}"])}
end
def handle_in("unwatch", %{"product_id" => id}, socket) do
{:reply, :ok, MyAppWeb.Endpoint.unsubscribe("product:#{id}")}
end
defp put_new_topics(socket, topics) do
Enum.reduce(topics, socket, fn topic, acc ->
topics = acc.assigns.topics
if topic in topics do
acc
else
:ok = MyAppWeb.Endpoint.subscribe(topic)
assign(acc, :topics, [topic | topics])
end
end)
end
end
```
Note: the caller must be responsible for preventing duplicate subscriptions. After calling `subscribe/1` from your endpoint, the same flow applies to handling regular Elixir messages within your channel. Most often, you'll simply relay the `%Phoenix.Socket.Broadcast{}` event and payload:
```
alias Phoenix.Socket.Broadcast
def handle_info(%Broadcast{topic: _, event: event, payload: payload}, socket) do
push(socket, event, payload)
{:noreply, socket}
end
```
Hibernation
------------
From Erlang/OTP 20, channels automatically hibernate to save memory after 15\_000 milliseconds of inactivity. This can be customized by passing the `:hibernate_after` option to `use Phoenix.Channel`:
```
use Phoenix.Channel, hibernate_after: 60_000
```
You can also set it to `:infinity` to fully disable it.
Shutdown
---------
You can configure the shutdown of each channel used when your application is shutting down by setting the `:shutdown` value on use:
```
use Phoenix.Channel, shutdown: 5_000
```
It defaults to 5\_000.
Logging
--------
By default, channel `"join"` and `"handle_in"` events are logged, using the level `:info` and `:debug`, respectively. Logs can be customized per event type or disabled by setting the `:log_join` and `:log_handle_in` options when using [`Phoenix.Channel`](phoenix.channel#content). For example, the following configuration logs join events as `:info`, but disables logging for incoming events:
```
use Phoenix.Channel, log_join: :info, log_handle_in: false
```
Summary
========
Types
------
[payload()](#t:payload/0) [reply()](#t:reply/0) [socket\_ref()](#t:socket_ref/0) Callbacks
----------
[code\_change(old\_vsn, t, extra)](#c:code_change/3) [handle\_call(msg, from, socket)](#c:handle_call/3) Handle regular GenServer call messages.
[handle\_cast(msg, socket)](#c:handle_cast/2) Handle regular GenServer cast messages.
[handle\_in(event, payload, socket)](#c:handle_in/3) Handle incoming `event`s.
[handle\_info(msg, socket)](#c:handle_info/2) Handle regular Elixir process messages.
[handle\_out(event, payload, socket)](#c:handle_out/3) Intercepts outgoing `event`s.
[join(topic, payload, socket)](#c:join/3) Handle channel joins by `topic`.
[terminate( reason, t )](#c:terminate/2) Invoked when the channel process is about to exit.
Functions
----------
[broadcast!(socket, event, message)](#broadcast!/3) Same as [`broadcast/3`](#broadcast/3), but raises if broadcast fails.
[broadcast(socket, event, message)](#broadcast/3) Broadcast an event to all subscribers of the socket topic.
[broadcast\_from!(socket, event, message)](#broadcast_from!/3) Same as [`broadcast_from/3`](#broadcast_from/3), but raises if broadcast fails.
[broadcast\_from(socket, event, message)](#broadcast_from/3) Broadcast event from pid to all subscribers of the socket topic.
[intercept(events)](#intercept/1) Defines which Channel events to intercept for `handle_out/3` callbacks.
[push(socket, event, message)](#push/3) Sends event to the socket.
[reply(socket\_ref, status)](#reply/2) Replies asynchronously to a socket push.
[socket\_ref(socket)](#socket_ref/1) Generates a `socket_ref` for an async reply.
Types
======
### payload()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L303)
```
@type payload() :: map() | {:binary, binary()}
```
### reply()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L304)
```
@type reply() :: status :: atom() | {status :: atom(), response :: payload()}
```
### socket\_ref()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L305)
```
@type socket_ref() ::
{transport_pid :: Pid, serializer :: module(), topic :: binary(),
ref :: binary(), join_ref :: binary()}
```
Callbacks
==========
### code\_change(old\_vsn, t, extra)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L387)
```
@callback code_change(old_vsn, Phoenix.Socket.t(), extra :: term()) ::
{:ok, Phoenix.Socket.t()} | {:error, reason :: term()}
when old_vsn: term() | {:down, term()}
```
### handle\_call(msg, from, socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L372)
```
@callback handle_call(
msg :: term(),
from :: {pid(), tag :: term()},
socket :: Phoenix.Socket.t()
) ::
{:reply, response :: term(), Phoenix.Socket.t()}
| {:noreply, Phoenix.Socket.t()}
| {:stop, reason :: term(), Phoenix.Socket.t()}
```
Handle regular GenServer call messages.
See [`GenServer.handle_call/3`](https://hexdocs.pm/elixir/GenServer.html#c:handle_call/3).
### handle\_cast(msg, socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L382)
```
@callback handle_cast(msg :: term(), socket :: Phoenix.Socket.t()) ::
{:noreply, Phoenix.Socket.t()} | {:stop, reason :: term(), Phoenix.Socket.t()}
```
Handle regular GenServer cast messages.
See [`GenServer.handle_cast/2`](https://hexdocs.pm/elixir/GenServer.html#c:handle_cast/2).
### handle\_in(event, payload, socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L341)
```
@callback handle_in(
event :: String.t(),
payload :: payload(),
socket :: Phoenix.Socket.t()
) ::
{:noreply, Phoenix.Socket.t()}
| {:noreply, Phoenix.Socket.t(), timeout() | :hibernate}
| {:reply, reply(), Phoenix.Socket.t()}
| {:stop, reason :: term(), Phoenix.Socket.t()}
| {:stop, reason :: term(), reply(), Phoenix.Socket.t()}
```
Handle incoming `event`s.
#### Example
```
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
```
### handle\_info(msg, socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L363)
```
@callback handle_info(msg :: term(), socket :: Phoenix.Socket.t()) ::
{:noreply, Phoenix.Socket.t()} | {:stop, reason :: term(), Phoenix.Socket.t()}
```
Handle regular Elixir process messages.
See [`GenServer.handle_info/2`](https://hexdocs.pm/elixir/GenServer.html#c:handle_info/2).
### handle\_out(event, payload, socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L353)
```
@callback handle_out(
event :: String.t(),
payload :: payload(),
socket :: Phoenix.Socket.t()
) ::
{:noreply, Phoenix.Socket.t()}
| {:noreply, Phoenix.Socket.t(), timeout() | :hibernate}
| {:stop, reason :: term(), Phoenix.Socket.t()}
```
Intercepts outgoing `event`s.
See [`intercept/1`](#intercept/1).
### join(topic, payload, socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L326)
```
@callback join(topic :: binary(), payload :: payload(), socket :: Phoenix.Socket.t()) ::
{:ok, Phoenix.Socket.t()}
| {:ok, reply :: payload(), Phoenix.Socket.t()}
| {:error, reason :: map()}
```
Handle channel joins by `topic`.
To authorize a socket, return `{:ok, socket}` or `{:ok, reply, socket}`. To refuse authorization, return `{:error, reason}`.
#### Example
```
def join("room:lobby", payload, socket) do
if authorized?(payload) do
{:ok, socket}
else
{:error, %{reason: "unauthorized"}}
end
end
```
### terminate( reason, t )[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L400)
```
@callback terminate(
reason :: :normal | :shutdown | {:shutdown, :left | :closed | term()},
Phoenix.Socket.t()
) :: term()
```
Invoked when the channel process is about to exit.
See [`GenServer.terminate/2`](https://hexdocs.pm/elixir/GenServer.html#c:terminate/2).
Functions
==========
### broadcast!(socket, event, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L528)
Same as [`broadcast/3`](#broadcast/3), but raises if broadcast fails.
### broadcast(socket, event, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L520)
Broadcast an event to all subscribers of the socket topic.
The event's message must be a serializable map or a tagged `{:binary, data}` tuple where `data` is binary data.
#### Examples
```
iex> broadcast(socket, "new_message", %{id: 1, content: "hello"})
:ok
iex> broadcast(socket, "new_message", {:binary, "hello"})
:ok
```
### broadcast\_from!(socket, event, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L559)
Same as [`broadcast_from/3`](#broadcast_from/3), but raises if broadcast fails.
### broadcast\_from(socket, event, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L549)
Broadcast event from pid to all subscribers of the socket topic.
The channel that owns the socket will not receive the published message. The event's message must be a serializable map or a tagged `{:binary, data}` tuple where `data` is binary data.
#### Examples
```
iex> broadcast_from(socket, "new_message", %{id: 1, content: "hello"})
:ok
iex> broadcast_from(socket, "new_message", {:binary, "hello"})
:ok
```
### intercept(events)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L483)
Defines which Channel events to intercept for `handle_out/3` callbacks.
By default, broadcasted events are pushed directly to the client, but intercepting events gives your channel a chance to customize the event for the client to append extra information or filter the message from being delivered.
*Note*: intercepting events can introduce significantly more overhead if a large number of subscribers must customize a message since the broadcast will be encoded N times instead of a single shared encoding across all subscribers.
#### Examples
```
intercept ["new_msg"]
def handle_out("new_msg", payload, socket) do
push(socket, "new_msg", Map.merge(payload,
is_editable: User.can_edit_message?(socket.assigns[:user], payload)
))
{:noreply, socket}
end
```
`handle_out/3` callbacks must return one of:
```
{:noreply, Socket.t} |
{:noreply, Socket.t, timeout | :hibernate} |
{:stop, reason :: term, Socket.t}
```
### push(socket, event, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L581)
Sends event to the socket.
The event's message must be a serializable map or a tagged `{:binary, data}` tuple where `data` is binary data.
#### Examples
```
iex> push(socket, "new_message", %{id: 1, content: "hello"})
:ok
iex> push(socket, "new_message", {:binary, "hello"})
:ok
```
### reply(socket\_ref, status)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L615)
```
@spec reply(socket_ref(), reply()) :: :ok
```
Replies asynchronously to a socket push.
Useful when you need to reply to a push that can't otherwise be handled using the `{:reply, {status, payload}, socket}` return from your `handle_in` callbacks. [`reply/2`](#reply/2) will be used in the rare cases you need to perform work in another process and reply when finished by generating a reference to the push with [`socket_ref/1`](#socket_ref/1).
*Note*: In such cases, a `socket_ref` should be generated and passed to the external process, so the `socket` itself is not leaked outside the channel. The `socket` holds information such as assigns and transport configuration, so it's important to not copy this information outside of the channel that owns it.
#### Examples
```
def handle_in("work", payload, socket) do
Worker.perform(payload, socket_ref(socket))
{:noreply, socket}
end
def handle_info({:work_complete, result, ref}, socket) do
reply(ref, {:ok, result})
{:noreply, socket}
end
```
### socket\_ref(socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/channel.ex#L629)
```
@spec socket_ref(Phoenix.Socket.t()) :: socket_ref()
```
Generates a `socket_ref` for an async reply.
See [`reply/2`](#reply/2) for example usage.
| programming_docs |
phoenix Phoenix.Digester.Compressor behaviour Phoenix.Digester.Compressor behaviour
======================================
Defines the [`Phoenix.Digester.Compressor`](phoenix.digester.compressor#content) behaviour for implementing static file compressors.
A custom compressor expects 2 functions to be implemented.
By default, Phoenix uses only [`Phoenix.Digester.Gzip`](phoenix.digester.gzip) to compress static files, but additional compressors can be defined and added to the digest process.
Example
--------
If you wanted to compress files using an external brotli compression library, you could define a new module implementing the behaviour and add the module to the list of configured Phoenix static compressors.
```
defmodule MyApp.BrotliCompressor do
@behaviour Phoenix.Digester.Compressor
def compress_file(file_path, content) do
valid_extension = Path.extname(file_path) in Application.fetch_env!(:phoenix, :gzippable_exts)
compressed_content = :brotli.encode(content)
if valid_extension && byte_size(compressed_content) < byte_size(content) do
{:ok, compressed_content}
else
:error
end
end
def file_extensions do
[".br"]
end
end
# config/config.exs
config :phoenix,
static_compressors: [Phoenix.Digester.Gzip, MyApp.BrotliCompressor],
# ...
```
Summary
========
Callbacks
----------
[compress\_file(t, binary)](#c:compress_file/2) [file\_extensions()](#c:file_extensions/0) Callbacks
==========
### compress\_file(t, binary)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/digester/compressor.ex#L42)
```
@callback compress_file(Path.t(), binary()) :: {:ok, binary()} | :error
```
### file\_extensions()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/digester/compressor.ex#L43)
```
@callback file_extensions() :: [String.t(), ...]
```
phoenix Phoenix.Naming Phoenix.Naming
===============
Conveniences for inflecting and working with names in Phoenix.
Summary
========
Functions
----------
[camelize(value)](#camelize/1) Converts a string to camel case.
[camelize(value, atom)](#camelize/2) [humanize(atom)](#humanize/1) Converts an attribute/form field into its humanize version.
[resource\_name(alias, suffix \\ "")](#resource_name/2) Extracts the resource name from an alias.
[underscore(value)](#underscore/1) Converts a string to underscore case.
[unsuffix(value, suffix)](#unsuffix/2) Removes the given suffix from the name if it exists.
Functions
==========
### camelize(value)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/naming.ex#L94)
```
@spec camelize(String.t()) :: String.t()
```
Converts a string to camel case.
Takes an optional `:lower` flag to return lowerCamelCase.
#### Examples
```
iex> Phoenix.Naming.camelize("my_app")
"MyApp"
iex> Phoenix.Naming.camelize("my_app", :lower)
"myApp"
```
In general, `camelize` can be thought of as the reverse of `underscore`, however, in some cases formatting may be lost:
```
Phoenix.Naming.underscore "SAPExample" #=> "sap_example"
Phoenix.Naming.camelize "sap_example" #=> "SapExample"
```
### camelize(value, atom)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/naming.ex#L97)
```
@spec camelize(String.t(), :lower) :: String.t()
```
### humanize(atom)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/naming.ex#L120)
```
@spec humanize(atom() | String.t()) :: String.t()
```
Converts an attribute/form field into its humanize version.
#### Examples
```
iex> Phoenix.Naming.humanize(:username)
"Username"
iex> Phoenix.Naming.humanize(:created_at)
"Created at"
iex> Phoenix.Naming.humanize("user_id")
"User"
```
### resource\_name(alias, suffix \\ "")[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/naming.ex#L19)
```
@spec resource_name(String.Chars.t(), String.t()) :: String.t()
```
Extracts the resource name from an alias.
#### Examples
```
iex> Phoenix.Naming.resource_name(MyApp.User)
"user"
iex> Phoenix.Naming.resource_name(MyApp.UserView, "View")
"user"
```
### underscore(value)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/naming.ex#L68)
```
@spec underscore(String.t()) :: String.t()
```
Converts a string to underscore case.
#### Examples
```
iex> Phoenix.Naming.underscore("MyApp")
"my_app"
```
In general, `underscore` can be thought of as the reverse of `camelize`, however, in some cases formatting may be lost:
```
Phoenix.Naming.underscore "SAPExample" #=> "sap_example"
Phoenix.Naming.camelize "sap_example" #=> "SapExample"
```
### unsuffix(value, suffix)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/naming.ex#L41)
```
@spec unsuffix(String.t(), String.t()) :: String.t()
```
Removes the given suffix from the name if it exists.
#### Examples
```
iex> Phoenix.Naming.unsuffix("MyApp.User", "View")
"MyApp.User"
iex> Phoenix.Naming.unsuffix("MyApp.UserView", "View")
"MyApp.User"
```
phoenix Deploying with Releases Deploying with Releases
========================
What we'll need
----------------
The only thing we'll need for this guide is a working Phoenix application. For those of us who need a simple application to deploy, please follow the [Up and Running guide](up_and_running).
Goals
------
Our main goal for this guide is to package your Phoenix application into a self-contained directory that includes the Erlang VM, Elixir, all of your code and dependencies. This package can then be dropped into a production machine.
Releases, assemble!
--------------------
To assemble a release, you will need at least Elixir v1.9, however this guide assumes you are using Elixir v1.12 or later to take advantage of latest releases improvements:
```
$ elixir -v
1.12.0
```
If you are not familiar with Elixir releases yet, we recommend you to read [Elixir's excellent docs](https://hexdocs.pm/mix/Mix.Tasks.Release.html) before continuing.
Once that is done, you can assemble a release by going through all of the steps in our general [deployment guide](deployment) with [`mix release`](https://hexdocs.pm/mix/Mix.Tasks.Release.html) at the end. Let's recap.
First set the environment variables:
```
$ mix phx.gen.secret
REALLY_LONG_SECRET
$ export SECRET_KEY_BASE=REALLY_LONG_SECRET
$ export DATABASE_URL=ecto://USER:PASS@HOST/database
```
Then load dependencies to compile code and assets:
```
# Initial setup
$ mix deps.get --only prod
$ MIX_ENV=prod mix compile
# Compile assets
$ MIX_ENV=prod mix assets.deploy
```
And now run [`mix phx.gen.release`](mix.tasks.phx.gen.release):
```
$ mix phx.gen.release
==> my_app
* creating rel/overlays/bin/server
* creating rel/overlays/bin/server.bat
* creating rel/overlays/bin/migrate
* creating rel/overlays/bin/migrate.bat
* creating lib/my_app/release.ex
Your application is ready to be deployed in a release!
# To start your system
_build/dev/rel/my_app/bin/my_app start
# To start your system with the Phoenix server running
_build/dev/rel/my_app/bin/server
# To run migrations
_build/dev/rel/my_app/bin/migrate
Once the release is running:
# To connect to it remotely
_build/dev/rel/my_app/bin/my_app remote
# To stop it gracefully (you may also send SIGINT/SIGTERM)
_build/dev/rel/my_app/bin/my_app stop
To list all commands:
_build/dev/rel/my_app/bin/my_app
```
The `phx.gen.release` task generated a few files for us to assist in releases. First, it created `server` and `migrate` *overlay* scripts for conveniently running the phoenix server inside a release or invoking migrations from a release. The files in the `rel/overlays` directory are copied into every release environment. Next, it generated a `release.ex` file which is used to invoked Ecto migrations without a dependency on `mix` itself.
*Note*: If you are a docker user, you can pass the `--docker` flag to [`mix phx.gen.release`](mix.tasks.phx.gen.release) to generate a Dockerfile ready for deployment.
Next, we can invoke [`mix release`](https://hexdocs.pm/mix/Mix.Tasks.Release.html) to build the release:
```
$ MIX_ENV=prod mix release
Generated my_app app
* assembling my_app-0.1.0 on MIX_ENV=prod
* using config/runtime.exs to configure the release at runtime
Release created at _build/prod/rel/my_app!
# To start your system
_build/prod/rel/my_app/bin/my_app start
...
```
You can start the release by calling `_build/prod/rel/my_app/bin/my_app start`, or boot your webserver by calling `_build/prod/rel/my_app/bin/server`, where you have to replace `my_app` by your current application name.
Now you can get all of the files under the `_build/prod/rel/my_app` directory, package it, and run it in any production machine with the same OS and architecture as the one that assembled the release. For more details, check the [docs for `mix release`](https://hexdocs.pm/mix/Mix.Tasks.Release.html).
But before we finish this guide, there is one more feature from releases that most Phoenix application will use, so let's talk about that.
Ecto migrations and custom commands
------------------------------------
A common need in production systems is to execute custom commands required to set up the production environment. One of such commands is precisely migrating the database. Since we don't have [`Mix`](https://hexdocs.pm/mix/Mix.html), a *build* tool, inside releases, which are a production artifact, we need to bring said commands directly into the release.
The `phx.gen.release` command created the following `release.ex` file in your project `lib/my_app/release.ex`, with the following content:
```
defmodule MyApp.Release do
@app :my_app
def migrate do
load_app()
for repo <- repos() do
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true))
end
end
def rollback(repo, version) do
load_app()
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
end
defp repos do
Application.fetch_env!(@app, :ecto_repos)
end
defp load_app do
Application.load(@app)
end
end
```
Where you replace the first two lines by your application names.
Now you can assemble a new release with `MIX_ENV=prod mix release` and you can invoke any code, including the functions in the module above, by calling the `eval` command:
```
$ _build/prod/rel/my_app/bin/my_app eval "MyApp.Release.migrate"
```
And that's it! If you peek inside the `migrate` script, you'll see it wraps exactly this invocation.
You can use this approach to create any custom command to run in production. In this case, we used `load_app`, which calls [`Application.load/1`](https://hexdocs.pm/elixir/Application.html#load/1) to load the current application without starting it. However, you may want to write a custom command that starts the whole application. In such cases, [`Application.ensure_all_started/1`](https://hexdocs.pm/elixir/Application.html#ensure_all_started/1) must be used. Keep in mind, starting the application will start all processes for the current application, including the Phoenix endpoint. This can be circumvented by changing your supervision tree to not start certain children under certain conditions. For example, in the release commands file you could do:
```
defp start_app do
load_app()
Application.put_env(@app, :minimal, true)
Application.ensure_all_started(@app)
end
```
And then in your application you check `Application.get_env(@app, :minimal)` and start only part of the children when it is set.
Containers
-----------
Elixir releases work well with container technologies, such as Docker. The idea is that you assemble the release inside the Docker container and then build an image based on the release artifacts.
If you call `mix phx.gen.release --docker` you'll see a new file with these contents:
```
# Find eligible builder and runner images on Docker Hub. We use Ubuntu/Debian instead of
# Alpine to avoid DNS resolution issues in production.
#
# https://hub.docker.com/r/hexpm/elixir/tags?page=1&name=ubuntu
# https://hub.docker.com/_/ubuntu?tab=tags
#
#
# This file is based on these images:
#
# - https://hub.docker.com/r/hexpm/elixir/tags - for the build image
# - https://hub.docker.com/_/debian?tab=tags&page=1&name=bullseye-20210902-slim - for the release image
# - https://pkgs.org/ - resource for finding needed packages
# - Ex: hexpm/elixir:1.12.0-erlang-24.0.1-debian-bullseye-20210902-slim
#
ARG ELIXIR_VERSION=1.12.0
ARG OTP_VERSION=24.0.1
ARG DEBIAN_VERSION=bullseye-20210902-slim
ARG BUILDER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}"
ARG RUNNER_IMAGE="debian:${DEBIAN_VERSION}"
FROM ${BUILDER_IMAGE} as builder
# install build dependencies
RUN apt-get update -y && apt-get install -y build-essential git \
&& apt-get clean && rm -f /var/lib/apt/lists/*_*
# prepare build dir
WORKDIR /app
# install hex + rebar
RUN mix local.hex --force && \
mix local.rebar --force
# set build ENV
ENV MIX_ENV="prod"
# install mix dependencies
COPY mix.exs mix.lock ./
RUN mix deps.get --only $MIX_ENV
RUN mkdir config
# copy compile-time config files before we compile dependencies
# to ensure any relevant config change will trigger the dependencies
# to be re-compiled.
COPY config/config.exs config/${MIX_ENV}.exs config/
RUN mix deps.compile
COPY priv priv
# note: if your project uses a tool like https://purgecss.com/,
# which customizes asset compilation based on what it finds in
# your Elixir templates, you will need to move the asset compilation
# step down so that `lib` is available.
COPY assets assets
# compile assets
RUN mix assets.deploy
# Compile the release
COPY lib lib
RUN mix compile
# Changes to config/runtime.exs don't require recompiling the code
COPY config/runtime.exs config/
COPY rel rel
RUN mix release
# start a new build stage so that the final image will only contain
# the compiled release and other runtime necessities
FROM ${RUNNER_IMAGE}
RUN apt-get update -y && apt-get install -y libstdc++6 openssl libncurses5 locales \
&& apt-get clean && rm -f /var/lib/apt/lists/*_*
# Set the locale
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
WORKDIR "/app"
RUN chown nobody /app
# set runner ENV
ENV MIX_ENV="prod"
# Only copy the final release from the build stage
COPY --from=builder --chown=nobody:root /app/_build/${MIX_ENV}/rel/my_app ./
USER nobody
CMD /app/bin/server
```
Where `my_app` is the name of your app. At the end, you will have an application in `/app` ready to run as `/app/bin/server`.
A few points about configuring a containerized application:
* If you run your app in a container, the `Endpoint` needs to be configured to listen on a "public" `:ip` address (like `0.0.0.0`) so that the app can be reached from outside the container. Whether the host should publish the container's ports to its own public IP or to localhost depends on your needs.
* The more configuration you can provide at runtime (using `config/runtime.exs`), the more reusable your images will be across environments. In particular, secrets like database credentials and API keys should not be compiled into the image, but rather should be provided when creating containers based on that image. This is why the `Endpoint`'s `:secret_key_base` is configured in `config/runtime.exs` by default.
* If possible, any environment variables that are needed at runtime should be read in `config/runtime.exs`, not scattered throughout your code. Having them all visible in one place will make it easier to ensure the containers get what they need, especially if the person doing the infrastructure work does not work on the Elixir code. Libraries in particular should never directly read environment variables; all their configuration should be handed to them by the top-level application, preferably [without using the application environment](https://hexdocs.pm/elixir/library-guidelines.html#avoid-application-configuration).
[← Previous Page Introduction to Deployment](deployment) [Next Page → Deploying on Gigalixir](gigalixir)
phoenix Phoenix.Socket.Transport behaviour Phoenix.Socket.Transport behaviour
===================================
Outlines the Socket <-> Transport communication.
This module specifies a behaviour that all sockets must implement. [`Phoenix.Socket`](phoenix.socket) is just one possible implementation of a socket that multiplexes events over multiple channels. Developers can implement their own sockets as long as they implement the behaviour outlined here.
Developers interested in implementing custom transports must invoke the socket API defined in this module. This module also provides many conveniences that invokes the underlying socket API to make it easier to build custom transports.
Booting sockets
----------------
Whenever your endpoint starts, it will automatically invoke the `child_spec/1` on each listed socket and start that specification under the endpoint supervisor.
Since the socket supervision tree is started by the endpoint, any custom transport must be started after the endpoint in a supervision tree.
Operating sockets
------------------
Sockets are operated by a transport. When a transport is defined, it usually receives a socket module and the module will be invoked when certain events happen at the transport level.
Whenever the transport receives a new connection, it should invoke the [`connect/1`](#c:connect/1) callback with a map of metadata. Different sockets may require different metadatas.
If the connection is accepted, the transport can move the connection to another process, if so desires, or keep using the same process. The process responsible for managing the socket should then call [`init/1`](#c:init/1).
For each message received from the client, the transport must call [`handle_in/2`](#c:handle_in/2) on the socket. For each informational message the transport receives, it should call [`handle_info/2`](#c:handle_info/2) on the socket.
Transports can optionally implement [`handle_control/2`](#c:handle_control/2) for handling control frames such as `:ping` and `:pong`.
On termination, [`terminate/2`](#c:terminate/2) must be called. A special atom with reason `:closed` can be used to specify that the client terminated the connection.
Example
--------
Here is a simple echo socket implementation:
```
defmodule EchoSocket do
@behaviour Phoenix.Socket.Transport
def child_spec(opts) do
# We won't spawn any process, so let's return a dummy task
%{id: __MODULE__, start: {Task, :start_link, [fn -> :ok end]}, restart: :transient}
end
def connect(state) do
# Callback to retrieve relevant data from the connection.
# The map contains options, params, transport and endpoint keys.
{:ok, state}
end
def init(state) do
# Now we are effectively inside the process that maintains the socket.
{:ok, state}
end
def handle_in({text, _opts}, state) do
{:reply, :ok, {:text, text}, state}
end
def handle_info(_, state) do
{:ok, state}
end
def terminate(_reason, _state) do
:ok
end
end
```
It can be mounted in your endpoint like any other socket:
```
socket "/socket", EchoSocket, websocket: true, longpoll: true
```
You can now interact with the socket under `/socket/websocket` and `/socket/longpoll`.
Security
---------
This module also provides functions to enable a secure environment on transports that, at some point, have access to a [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html).
The functionality provided by this module helps in performing "origin" header checks and ensuring only SSL connections are allowed.
Summary
========
Types
------
[state()](#t:state/0) Callbacks
----------
[child\_spec(keyword)](#c:child_spec/1) Returns a child specification for socket management.
[connect(transport\_info)](#c:connect/1) Connects to the socket.
[handle\_control( {}, state )](#c:handle_control/2) Handles incoming control frames.
[handle\_in( {}, state )](#c:handle_in/2) Handles incoming socket messages.
[handle\_info(message, state)](#c:handle_info/2) Handles info messages.
[init(state)](#c:init/1) Initializes the socket state.
[terminate(reason, state)](#c:terminate/2) Invoked on termination.
Functions
----------
[check\_origin(conn, handler, endpoint, opts, sender \\ &Plug.Conn.send\_resp/1)](#check_origin/5) Checks the origin request header against the list of allowed origins.
[check\_subprotocols(conn, subprotocols)](#check_subprotocols/2) Checks the Websocket subprotocols request header against the allowed subprotocols.
[code\_reload(conn, endpoint, opts)](#code_reload/3) Runs the code reloader if enabled.
[connect\_info(conn, endpoint, keys)](#connect_info/3) Extracts connection information from `conn` and returns a map.
[force\_ssl(conn, socket, endpoint, opts)](#force_ssl/4) Forces SSL in the socket connection.
[transport\_log(conn, level)](#transport_log/2) Logs the transport request.
Types
======
### state()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L103)
```
@type state() :: term()
```
Callbacks
==========
### child\_spec(keyword)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L127)
```
@callback child_spec(keyword()) :: :supervisor.child_spec()
```
Returns a child specification for socket management.
This is invoked only once per socket regardless of the number of transports and should be responsible for setting up any process structure used exclusively by the socket regardless of transports.
Each socket connection is started by the transport and the process that controls the socket likely belongs to the transport. However, some sockets spawn new processes, such as [`Phoenix.Socket`](phoenix.socket) which spawns channels, and this gives the ability to start a supervision tree associated to the socket.
It receives the socket options from the endpoint, for example:
```
socket "/my_app", MyApp.Socket, shutdown: 5000
```
means `child_spec([shutdown: 5000])` will be invoked.
### connect(transport\_info)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L153)
```
@callback connect(transport_info :: map()) :: {:ok, state()} | :error
```
Connects to the socket.
The transport passes a map of metadata and the socket returns `{:ok, state}` or `:error`. The state must be stored by the transport and returned in all future operations.
This function is used for authorization purposes and it may be invoked outside of the process that effectively runs the socket.
In the default [`Phoenix.Socket`](phoenix.socket) implementation, the metadata expects the following keys:
* `:endpoint` - the application endpoint
* `:transport` - the transport name
* `:params` - the connection parameters
* `:options` - a keyword list of transport options, often given by developers when configuring the transport. It must include a `:serializer` field with the list of serializers and their requirements
### handle\_control( {}, state )[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L201)
```
@callback handle_control(
{message :: term(), opts :: keyword()},
state()
) ::
{:ok, state()}
| {:reply, :ok | :error, {opcode :: atom(), message :: term()}, state()}
| {:stop, reason :: term(), state()}
```
Handles incoming control frames.
The message is represented as `{payload, options}`. It must return one of:
* `{:ok, state}` - continues the socket with no reply
* `{:reply, status, reply, state}` - continues the socket with reply
* `{:stop, reason, state}` - stops the socket
Control frames only supported when using websockets.
The `options` contains an `opcode` key, this will be either `:ping` or `:pong`.
If a control frame doesn't have a payload, then the payload value will be `nil`.
### handle\_in( {}, state )[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L178)
```
@callback handle_in(
{message :: term(), opts :: keyword()},
state()
) ::
{:ok, state()}
| {:reply, :ok | :error, {opcode :: atom(), message :: term()}, state()}
| {:stop, reason :: term(), state()}
```
Handles incoming socket messages.
The message is represented as `{payload, options}`. It must return one of:
* `{:ok, state}` - continues the socket with no reply
* `{:reply, status, reply, state}` - continues the socket with reply
* `{:stop, reason, state}` - stops the socket
The `reply` is a tuple contain an `opcode` atom and a message that can be any term. The built-in websocket transport supports both `:text` and `:binary` opcode and the message must be always iodata. Long polling only supports text opcode.
### handle\_info(message, state)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L220)
```
@callback handle_info(message :: term(), state()) ::
{:ok, state()}
| {:push, {opcode :: atom(), message :: term()}, state()}
| {:stop, reason :: term(), state()}
```
Handles info messages.
The message is a term. It must return one of:
* `{:ok, state}` - continues the socket with no reply
* `{:push, reply, state}` - continues the socket with reply
* `{:stop, reason, state}` - stops the socket
The `reply` is a tuple contain an `opcode` atom and a message that can be any term. The built-in websocket transport supports both `:text` and `:binary` opcode and the message must be always iodata. Long polling only supports text opcode.
### init(state)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L161)
```
@callback init(state()) :: {:ok, state()}
```
Initializes the socket state.
This must be executed from the process that will effectively operate the socket.
### terminate(reason, state)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L232)
```
@callback terminate(reason :: term(), state()) :: :ok
```
Invoked on termination.
If `reason` is `:closed`, it means the client closed the socket. This is considered a `:normal` exit signal, so linked process will not automatically exit. See [`Process.exit/2`](https://hexdocs.pm/elixir/Process.html#exit/2) for more details on exit signals.
Functions
==========
### check\_origin(conn, handler, endpoint, opts, sender \\ &Plug.Conn.send\_resp/1)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L342)
Checks the origin request header against the list of allowed origins.
Should be called by transports before connecting when appropriate. If the origin header matches the allowed origins, no origin header was sent or no origin was configured, it will return the given connection.
Otherwise a 403 Forbidden response will be sent and the connection halted. It is a noop if the connection has been halted.
### check\_subprotocols(conn, subprotocols)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L400)
Checks the Websocket subprotocols request header against the allowed subprotocols.
Should be called by transports before connecting when appropriate. If the sec-websocket-protocol header matches the allowed subprotocols, it will put sec-websocket-protocol response header and return the given connection. If no sec-websocket-protocol header was sent it will return the given connection.
Otherwise a 403 Forbidden response will be sent and the connection halted. It is a noop if the connection has been halted.
### code\_reload(conn, endpoint, opts)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L283)
Runs the code reloader if enabled.
### connect\_info(conn, endpoint, keys)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L444)
Extracts connection information from `conn` and returns a map.
Keys are retrieved from the optional transport option `:connect_info`. This functionality is transport specific. Please refer to your transports' documentation for more information.
The supported keys are:
* `:peer_data` - the result of [`Plug.Conn.get_peer_data/1`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#get_peer_data/1)
* `:trace_context_headers` - a list of all trace context headers
* `:x_headers` - a list of all request headers that have an "x-" prefix
* `:uri` - a `%URI{}` derived from the conn
* `:user_agent` - the value of the "user-agent" request header
### force\_ssl(conn, socket, endpoint, opts)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L295)
Forces SSL in the socket connection.
Uses the endpoint configuration to decide so. It is a noop if the connection has been halted.
### transport\_log(conn, level)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/transport.ex#L324)
Logs the transport request.
Available for transports that generate a connection.
| programming_docs |
phoenix mix phx.new.ecto mix phx.new.ecto
=================
Creates a new Ecto project within an umbrella project.
This task is intended to create a bare Ecto project without web integration, which serves as a core application of your domain for web applications and your greater umbrella platform to integrate with.
It expects the name of the project as an argument.
```
$ cd my_umbrella/apps
$ mix phx.new.ecto APP [--module MODULE] [--app APP]
```
A project at the given APP directory will be created. The application name and module name will be retrieved from the application name, unless `--module` or `--app` is given.
Options
--------
* `--app` - the name of the OTP application
* `--module` - the name of the base module in the generated skeleton
* `--database` - specify the database adapter for Ecto. One of:
+ `postgres` - via <https://github.com/elixir-ecto/postgrex>
+ `mysql` - via <https://github.com/elixir-ecto/myxql>
+ `mssql` - via <https://github.com/livehelpnow/tds>
+ `sqlite3` - via <https://github.com/elixir-sqlite/ecto_sqlite3>Please check the driver docs for more information and requirements. Defaults to "postgres".
* `--binary-id` - use `binary_id` as primary key type in Ecto schemas
Examples
---------
```
$ mix phx.new.ecto hello_ecto
```
Is equivalent to:
```
$ mix phx.new.ecto hello_ecto --module HelloEcto
```
phoenix mix local.phx mix local.phx
==============
Updates the Phoenix project generator locally.
```
$ mix local.phx
```
Accepts the same command line options as `archive.install hex phx_new`.
phoenix Request life-cycle Request life-cycle
===================
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
The goal of this guide is to talk about Phoenix's request life-cycle. This guide will take a practical approach where we will learn by doing: we will add two new pages to our Phoenix project and comment on how the pieces fit together along the way.
Let's get on with our first new Phoenix page!
Adding a new page
------------------
When your browser accesses <http://localhost:4000/>, it sends a HTTP request to whatever service is running on that address, in this case our Phoenix application. The HTTP request is made of a verb and a path. For example, the following browser requests translate into:
| Browser address bar | Verb | Path |
| --- | --- | --- |
| <http://localhost:4000/> | GET | / |
| <http://localhost:4000/hello> | GET | /hello |
| <http://localhost:4000/hello/world> | GET | /hello/world |
There are other HTTP verbs. For example, submitting a form typically uses the POST verb.
Web applications typically handle requests by mapping each verb/path pair into a specific part of your application. This matching in Phoenix is done by the router. For example, we may map "/articles" to a portion of our application that shows all articles. Therefore, to add a new page, our first task is to add a new route.
### A new route
The router maps unique HTTP verb/path pairs to controller/action pairs which will handle them. Controllers in Phoenix are simply Elixir modules. Actions are functions that are defined within these controllers.
Phoenix generates a router file for us in new applications at `lib/hello_web/router.ex`. This is where we will be working for this section.
The route for our "Welcome to Phoenix!" page from the previous [Up And Running Guide](up_and_running) looks like this.
```
get "/", PageController, :index
```
Let's digest what this route is telling us. Visiting <http://localhost:4000/> issues an HTTP `GET` request to the root path. All requests like this will be handled by the `index/2` function in the `HelloWeb.PageController` module defined in `lib/hello_web/controllers/page_controller.ex`.
The page we are going to build will say "Hello World, from Phoenix!" when we point our browser to <http://localhost:4000/hello>.
The first thing we need to do is to create the page route for a new page. Let's open up `lib/hello_web/router.ex` in a text editor. For a brand new application, it looks like this:
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
end
# Other scopes may use custom stacks.
# scope "/api", HelloWeb do
# pipe_through :api
# end
# ...
end
```
For now, we'll ignore the pipelines and the use of `scope` here and just focus on adding a route. We will discuss those in the [Routing guide](routing).
Let's add a new route to the router that maps a `GET` request for `/hello` to the `index` action of a soon-to-be-created `HelloWeb.HelloController` inside the `scope "/" do` block of the router:
```
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
get "/hello", HelloController, :index
end
```
### A new controller
Controllers are Elixir modules, and actions are Elixir functions defined in them. The purpose of actions is to gather the data and perform the tasks needed for rendering. Our route specifies that we need a `HelloWeb.HelloController` module with an `index/2` function.
To make the `index` action happen, let's create a new `lib/hello_web/controllers/hello_controller.ex` file, and make it look like the following:
```
defmodule HelloWeb.HelloController do
use HelloWeb, :controller
def index(conn, _params) do
render(conn, "index.html")
end
end
```
We'll save a discussion of `use HelloWeb, :controller` for the [Controllers guide](controllers). For now, let's focus on the `index` action.
All controller actions take two arguments. The first is `conn`, a struct which holds a ton of data about the request. The second is `params`, which are the request parameters. Here, we are not using `params`, and we avoid compiler warnings by prefixing it with `_`.
The core of this action is `render(conn, "index.html")`. It tells Phoenix to render `"index.html"`. The modules responsible for rendering are called views. By default, Phoenix views are named after the controller, so Phoenix is expecting a `HelloWeb.HelloView` to exist and handle `"index.html"` for us.
> Note: Using an atom as the template name also works `render(conn, :index)`. In these cases, the template will be chosen based off the Accept headers, e.g. `"index.html"` or `"index.json"`.
>
>
### A new view
Phoenix views act as the presentation layer. For example, we expect the output of rendering `"index.html"` to be a complete HTML page. To make our lives easier, we often use templates for creating those HTML pages.
Let's create a new view. Create `lib/hello_web/views/hello_view.ex` and make it look like this:
```
defmodule HelloWeb.HelloView do
use HelloWeb, :view
end
```
Now in order to add templates to this view, we need to add files to the `lib/hello_web/templates/hello` directory. Note the controller name (`HelloController`), the view name (`HelloView`), and the template directory (`hello`) all follow the same naming convention and are named after each other.
A template file has the following structure: `NAME.FORMAT.TEMPLATING_LANGUAGE`. In our case, we will create an `index.html.heex` file at `lib/hello_web/templates/hello/index.html.heex`. ".heex" stands for "HTML+EEx". [`EEx`](https://hexdocs.pm/eex/EEx.html) is a library for embedding Elixir that ships as part of Elixir itself. "HTML+EEx" is a Phoenix extension of EEx that is HTML aware, with support for HTML validation, components, and automatic escaping of values. The latter protects you from security vulnerabilities like Cross-Site-Scripting with no extra work on your part.
Create `lib/hello_web/templates/hello/index.html.heex` and make it look like this:
```
<section class="phx-hero">
<h2>Hello World, from Phoenix!</h2>
</section>
```
Now that we've got the route, controller, view, and template, we should be able to point our browsers at <http://localhost:4000/hello> and see our greeting from Phoenix! (In case you stopped the server along the way, the task to restart it is [`mix phx.server`](mix.tasks.phx.server).)
There are a couple of interesting things to notice about what we just did. We didn't need to stop and restart the server while we made these changes. Yes, Phoenix has hot code reloading! Also, even though our `index.html.heex` file consists of only a single `section` tag, the page we get is a full HTML document. Our index template is rendered into the application layout: `lib/hello_web/templates/layout/app.html.heex`. If you open it, you'll see a line that looks like this:
```
<%= @inner_content %>
```
Which injects our template into the layout before the HTML is sent off to the browser.
> A note on hot code reloading: Some editors with their automatic linters may prevent hot code reloading from working. If it's not working for you, please see the discussion in [this issue](https://github.com/phoenixframework/phoenix/issues/1165).
>
>
From endpoint to views
-----------------------
As we built our first page, we could start to understand how the request life-cycle is put together. Now let's take a more holistic look at it.
All HTTP requests start in our application endpoint. You can find it as a module named `HelloWeb.Endpoint` in `lib/hello_web/endpoint.ex`. Once you open up the endpoint file, you will see that, similar to the router, the endpoint has many calls to `plug`. [`Plug`](https://hexdocs.pm/plug/1.13.6/Plug.html) is a library and a specification for stitching web applications together. It is an essential part of how Phoenix handles requests and we will discuss it in detail in the [Plug guide](plug) coming next.
For now, it suffices to say that each plug defines a slice of request processing. In the endpoint you will find a skeleton roughly like this:
```
defmodule HelloWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :hello
plug Plug.Static, ...
plug Plug.RequestId
plug Plug.Telemetry, ...
plug Plug.Parsers, ...
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, ...
plug HelloWeb.Router
end
```
Each of these plugs have a specific responsibility that we will learn later. The last plug is precisely the `HelloWeb.Router` module. This allows the endpoint to delegate all further request processing to the router. As we now know, its main responsibility is to map verb/path pairs to controllers. The controller then tells a view to render a template.
At this moment, you may be thinking this can be a lot of steps to simply render a page. However, as our application grows in complexity, we will see that each layer serves a distinct purpose:
* endpoint ([`Phoenix.Endpoint`](phoenix.endpoint)) - the endpoint contains the common and initial path that all requests go through. If you want something to happen on all requests, it goes to the endpoint.
* router ([`Phoenix.Router`](phoenix.router)) - the router is responsible for dispatching verb/path to controllers. The router also allows us to scope functionality. For example, some pages in your application may require user authentication, others may not.
* controller ([`Phoenix.Controller`](phoenix.controller)) - the job of the controller is to retrieve request information, talk to your business domain, and prepare data for the presentation layer.
* view ([`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html)) - the view handles the structured data from the controller and converts it to a presentation to be shown to users.
Let's do a quick recap and how the last three components work together by adding another page.
Another new page
-----------------
Let's add just a little complexity to our application. We're going to add a new page that will recognize a piece of the URL, label it as a "messenger" and pass it through the controller into the template so our messenger can say hello.
As we did last time, the first thing we'll do is create a new route.
### Another new route
For this exercise, we're going to reuse `HelloController` created at the [previous step](request_lifecycle#a-new-controller) and add a new `show` action. We'll add a line just below our last route, like this:
```
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
get "/hello", HelloController, :index
get "/hello/:messenger", HelloController, :show
end
```
Notice that we use the `:messenger` syntax in the path. Phoenix will take whatever value that appears in that position in the URL and convert it into a parameter. For example, if we point the browser at: `http://localhost:4000/hello/Frank`, the value of `"messenger"` will be `"Frank"`.
### Another new Action
Requests to our new route will be handled by the `HelloWeb.HelloController` `show` action. We already have the controller at `lib/hello_web/controllers/hello_controller.ex`, so all we need to do is edit that controller and add a `show` action to it. This time, we'll need to extract the messenger from the parameters so that we can pass it (the messenger) to the template. To do that, we add this show function to the controller:
```
def show(conn, %{"messenger" => messenger}) do
render(conn, "show.html", messenger: messenger)
end
```
Within the body of the `show` action, we also pass a third argument to the render function, a key-value pair where `:messenger` is the key, and the `messenger` variable is passed as the value.
If the body of the action needs access to the full map of parameters bound to the `params` variable, in addition to the bound messenger variable, we could define `show/2` like this:
```
def show(conn, %{"messenger" => messenger} = params) do
...
end
```
It's good to remember that the keys of the `params` map will always be strings, and that the equals sign does not represent assignment, but is instead a [pattern match](https://elixir-lang.org/getting-started/pattern-matching.html) assertion.
### Another new template
For the last piece of this puzzle, we'll need a new template. Since it is for the `show` action of `HelloController`, it will go into the `lib/hello_web/templates/hello` directory and be called `show.html.heex`. It will look surprisingly like our `index.html.heex` template, except that we will need to display the name of our messenger.
To do that, we'll use the special EEx tags for executing Elixir expressions: `<%= %>`. Notice that the initial tag has an equals sign like this: `<%=` . That means that any Elixir code that goes between those tags will be executed, and the resulting value will replace the tag in the HTML output. If the equals sign were missing, the code would still be executed, but the value would not appear on the page.
And this is what the template should look like:
```
<section class="phx-hero">
<h2>Hello World, from <%= @messenger %>!</h2>
</section>
```
Our messenger appears as `@messenger`. We call "assigns" the values passed from the controller to views. It is a special bit of metaprogrammed syntax which stands in for `assigns.messenger`. The result is much nicer on the eyes and much easier to work with in a template.
We're done. If you point your browser to <http://localhost:4000/hello/Frank>, you should see a page that looks like this:
Play around a bit. Whatever you put after `/hello/` will appear on the page as your messenger.
[← Previous Page Directory structure](directory_structure) [Next Page → Plug](plug)
phoenix Phoenix.Socket.Serializer behaviour Phoenix.Socket.Serializer behaviour
====================================
A behaviour that serializes incoming and outgoing socket messages.
By default Phoenix provides a serializer that encodes to JSON and decodes JSON messages.
Custom serializers may be configured in the socket.
Summary
========
Callbacks
----------
[decode!(iodata, options)](#c:decode!/2) Decodes iodata into [`Phoenix.Socket.Message`](phoenix.socket.message) struct.
[encode!(arg1)](#c:encode!/1) Encodes [`Phoenix.Socket.Message`](phoenix.socket.message) and [`Phoenix.Socket.Reply`](phoenix.socket.reply) structs to push format.
[fastlane!(t)](#c:fastlane!/1) Encodes a [`Phoenix.Socket.Broadcast`](phoenix.socket.broadcast) struct to fastlane format.
Callbacks
==========
### decode!(iodata, options)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/serializer.ex#L28)
```
@callback decode!(iodata(), options :: Keyword.t()) :: Phoenix.Socket.Message.t()
```
Decodes iodata into [`Phoenix.Socket.Message`](phoenix.socket.message) struct.
### encode!(arg1)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/serializer.ex#L21)
```
@callback encode!(Phoenix.Socket.Message.t() | Phoenix.Socket.Reply.t()) ::
{:socket_push, :text, iodata()} | {:socket_push, :binary, iodata()}
```
Encodes [`Phoenix.Socket.Message`](phoenix.socket.message) and [`Phoenix.Socket.Reply`](phoenix.socket.reply) structs to push format.
### fastlane!(t)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/serializer.ex#L14)
```
@callback fastlane!(Phoenix.Socket.Broadcast.t()) ::
{:socket_push, :text, iodata()} | {:socket_push, :binary, iodata()}
```
Encodes a [`Phoenix.Socket.Broadcast`](phoenix.socket.broadcast) struct to fastlane format.
phoenix Telemetry Telemetry
==========
In this guide, we will show you how to instrument and report on `:telemetry` events in your Phoenix application.
> `te·lem·e·try` - the process of recording and transmitting the readings of an instrument.
>
>
As you follow along with this guide, we will introduce you to the core concepts of Telemetry, you will initialize a reporter to capture your application's events as they occur, and we will guide you through the steps to properly instrument your own functions using `:telemetry`. Let's take a closer look at how Telemetry works in your application.
Overview
---------
The `[:telemetry]` library allows you to emit events at various stages of an application's lifecycle. You can then respond to these events by, among other things, aggregating them as metrics and sending the metrics data to a reporting destination.
Telemetry stores events by their name in an ETS table, along with the handler for each event. Then, when a given event is executed, Telemetry looks up its handler and invokes it.
Phoenix's Telemetry tooling provides you with a supervisor that uses [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html) to define the list of Telemetry events to handle and how to handle those events, i.e. how to structure them as a certain type of metric. This supervisor works together with Telemetry reporters to respond to the specified Telemetry events by aggregating them as the appropriate metric and sending them to the correct reporting destination.
The Telemetry supervisor
-------------------------
Since v1.5, new Phoenix applications are generated with a Telemetry supervisor. This module is responsible for managing the lifecycle of your Telemetry processes. It also defines a `metrics/0` function, which returns a list of [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics) that you define for your application.
By default, the supervisor also starts [`:telemetry_poller`](https://hexdocs.pm/telemetry_poller). By simply adding `:telemetry_poller` as a dependency, you can receive VM-related events on a specified interval.
If you are coming from an older version of Phoenix, install the `:telemetry_metrics` and `:telemetry_poller` packages:
```
{:telemetry_metrics, "~> 0.6"},
{:telemetry_poller, "~> 1.0"}
```
and create your Telemetry supervisor at `lib/my_app_web/telemetry.ex`:
```
# lib/my_app_web/telemetry.ex
defmodule MyAppWeb.Telemetry do
use Supervisor
import Telemetry.Metrics
def start_link(arg) do
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
end
def init(_arg) do
children = [
{:telemetry_poller, measurements: periodic_measurements(), period: 10_000}
# Add reporters as children of your supervision tree.
# {Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
]
Supervisor.init(children, strategy: :one_for_one)
end
def metrics do
[
# Phoenix Metrics
summary("phoenix.endpoint.stop.duration",
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.stop.duration",
tags: [:route],
unit: {:native, :millisecond}
),
# VM Metrics
summary("vm.memory.total", unit: {:byte, :kilobyte}),
summary("vm.total_run_queue_lengths.total"),
summary("vm.total_run_queue_lengths.cpu"),
summary("vm.total_run_queue_lengths.io")
]
end
defp periodic_measurements do
[
# A module, function and arguments to be invoked periodically.
# This function must call :telemetry.execute/3 and a metric must be added above.
# {MyApp, :count_users, []}
]
end
end
```
Make sure to replace MyApp by your actual application name.
Then add to your main application's supervision tree (usually in `lib/my_app/application.ex`):
```
children = [
MyApp.Repo,
MyAppWeb.Telemetry,
MyAppWeb.Endpoint,
...
]
```
Telemetry Events
-----------------
Many Elixir libraries (including Phoenix) are already using the [`:telemetry`](https://hexdocs.pm/telemetry) package as a way to give users more insight into the behavior of their applications, by emitting events at key moments in the application lifecycle.
A Telemetry event is made up of the following:
* `name` - A string (e.g. `"my_app.worker.stop"`) or a list of atoms that uniquely identifies the event.
* `measurements` - A map of atom keys (e.g. `:duration`) and numeric values.
* `metadata` - A map of key-value pairs that can be used for tagging metrics.
### A Phoenix Example
Here is an example of an event from your endpoint:
* `[:phoenix, :endpoint, :stop]` - dispatched by [`Plug.Telemetry`](https://hexdocs.pm/plug/1.13.6/Plug.Telemetry.html), one of the default plugs in your endpoint, whenever the response is sent
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{conn: Plug.Conn.t}`
This means that after each request, [`Plug`](https://hexdocs.pm/plug/1.13.6/Plug.html), via `:telemetry`, will emit a "stop" event, with a measurement of how long it took to get the response:
```
:telemetry.execute([:phoenix, :endpoint, :stop], %{duration: duration}, %{conn: conn})
```
### Phoenix Telemetry Events
A full list of all Phoenix telemetry events can be found in [`Phoenix.Logger`](phoenix.logger)
Metrics
--------
>
> Metrics are aggregations of Telemetry events with a specific name, providing a view of the system's behaviour over time.
>
>
> ― [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html)
>
>
>
The Telemetry.Metrics package provides a common interface for defining metrics. It exposes a set of [five metric type functions](https://hexdocs.pm/telemetry_metrics/Telemetry.Metrics.html#module-metrics) that are responsible for structuring a given Telemetry event as a particular measurement.
The package does not perform any aggregation of the measurements itself. Instead, it provides a reporter with the Telemetry event-as-measurement definition and the reporter uses that definition to perform aggregations and report them.
We will discuss reporters in the next section.
Let's take a look at some examples.
Using [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html), you can define a counter metric, which counts how many HTTP requests were completed:
```
Telemetry.Metrics.counter("phoenix.endpoint.stop.duration")
```
or you could use a distribution metric to see how many requests were completed in particular time buckets:
```
Telemetry.Metrics.distribution("phoenix.endpoint.stop.duration")
```
This ability to introspect HTTP requests is really powerful -- and this is but one of *many* telemetry events emitted by the Phoenix framework! We'll discuss more of these events, as well as specific patterns for extracting valuable data from Phoenix/Plug events in the [Phoenix Metrics](#phoenix-metrics) section later in this guide.
> The full list of `:telemetry` events emitted from Phoenix, along with their measurements and metadata, is available in the "Instrumentation" section of the [`Phoenix.Logger`](phoenix.logger) module documentation.
>
>
### An Ecto Example
Like Phoenix, Ecto ships with built-in Telemetry events. This means that you can gain introspection into your web and database layers using the same tools.
Here is an example of a Telemetry event executed by Ecto when an Ecto repository starts:
* `[:ecto, :repo, :init]` - dispatched by [`Ecto.Repo`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html)
+ Measurement: `%{system_time: native_time}`
+ Metadata: `%{repo: Ecto.Repo, opts: Keyword.t()}`
This means that whenever the [`Ecto.Repo`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html) starts, it will emit an event, via `:telemetry`, with a measurement of the time at start-up.
```
:telemetry.execute([:ecto, :repo, :init], %{system_time: System.system_time()}, %{repo: repo, opts: opts})
```
Additional Telemetry events are executed by Ecto adapters.
One such adapter-specific event is the `[:my_app, :repo, :query]` event. For instance, if you want to graph query execution time, you can use the [`Telemetry.Metrics.summary/2`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html#summary/2) function to instruct your reporter to calculate statistics of the `[:my_app, :repo, :query]` event, like maximum, mean, percentiles etc.:
```
Telemetry.Metrics.summary("my_app.repo.query.query_time",
unit: {:native, :millisecond}
)
```
Or you could use the [`Telemetry.Metrics.distribution/2`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html#distribution/2) function to define a histogram for another adapter-specific event: `[:my_app, :repo, :query, :queue_time]`, thus visualizing how long queries spend queued:
```
Telemetry.Metrics.distribution("my_app.repo.query.queue_time",
unit: {:native, :millisecond}
)
```
> You can learn more about Ecto Telemetry in the "Telemetry Events" section of the [`Ecto.Repo`](../ecto/ecto.repo) module documentation.
>
>
So far we have seen some of the Telemetry events common to Phoenix applications, along with some examples of their various measurements and metadata. With all of this data just waiting to be consumed, let's talk about reporters.
Reporters
----------
Reporters subscribe to Telemetry events using the common interface provided by [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html). They then aggregate the measurements (data) into metrics to provide meaningful information about your application.
For example, if the following [`Telemetry.Metrics.summary/2`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html#summary/2) call is added to the `metrics/0` function of your Telemetry supervisor:
```
summary("phoenix.endpoint.stop.duration",
unit: {:native, :millisecond}
)
```
Then the reporter will attach a listener for the `"phoenix.endpoint.stop.duration"` event and will respond to this event by calculating a summary metric with the given event metadata and reporting on that metric to the appropriate source.
### Phoenix.LiveDashboard
For developers interested in real-time visualizations for their Telemetry metrics, you may be interested in installing [`LiveDashboard`](https://hexdocs.pm/phoenix_live_dashboard). LiveDashboard acts as a Telemetry.Metrics reporter to render your data as beautiful, real-time charts on the dashboard.
### Telemetry.Metrics.ConsoleReporter
[`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html) ships with a `ConsoleReporter` that can be used to print events and metrics to the terminal. You can use this reporter to experiment with the metrics discussed in this guide.
Uncomment or add the following to this list of children in your Telemetry supervision tree (usually in `lib/my_app_web/telemetry.ex`):
```
{Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
```
> There are numerous reporters available, for services like StatsD, Prometheus, and more. You can find them by searching for "telemetry\_metrics" on [hex.pm](https://hex.pm/packages?search=telemetry_metrics).
>
>
Phoenix Metrics
----------------
Earlier we looked at the "stop" event emitted by [`Plug.Telemetry`](https://hexdocs.pm/plug/1.13.6/Plug.Telemetry.html), and used it to count the number of HTTP requests. In reality, it's only somewhat helpful to be able to see just the total number of requests. What if you wanted to see the number of requests per route, or per route *and* method?
Let's take a look at another event emitted during the HTTP request lifecycle, this time from [`Phoenix.Router`](phoenix.router):
* `[:phoenix, :router_dispatch, :stop]` - dispatched by Phoenix.Router after successfully dispatching to a matched route
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{conn: Plug.Conn.t, route: binary, plug: module, plug_opts: term, path_params: map, pipe_through: [atom]}`
Let's start by grouping these events by route. Add the following (if it does not already exist) to the `metrics/0` function of your Telemetry supervisor (usually in `lib/my_app_web/telemetry.ex`):
```
# lib/my_app_web/telemetry.ex
def metrics do
[
...metrics...
summary("phoenix.router_dispatch.stop.duration",
tags: [:route],
unit: {:native, :millisecond}
)
]
end
```
Restart your server, and then make requests to a page or two. In your terminal, you should see the ConsoleReporter print logs for the Telemetry events it received as a result of the metrics definitions you provided.
The log line for each request contains the specific route for that request. This is due to specifying the `:tags` option for the summary metric, which takes care of our first requirement; we can use `:tags` to group metrics by route. Note that reporters will necessarily handle tags differently depending on the underlying service in use.
Looking more closely at the Router "stop" event, you can see that the [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) struct representing the request is present in the metadata, but how do you access the properties in `conn`?
Fortunately, [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html) provides the following options to help you classify your events:
* `:tags` - A list of metadata keys for grouping;
* `:tag_values` - A function which transforms the metadata into the desired shape; Note that this function is called for each event, so it's important to keep it fast if the rate of events is high.
> Learn about all the available metrics options in the [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html) module documentation.
>
>
Let's find out how to extract more tags from events that include a `conn` in their metadata.
### Extracting tag values from Plug.Conn
Let's add another metric for the route event, this time to group by route and method:
```
summary("phoenix.router_dispatch.stop.duration",
tags: [:method, :route],
tag_values: &get_and_put_http_method/1,
unit: {:native, :millisecond}
)
```
We've introduced the `:tag_values` option here, because we need to perform a transformation on the event metadata in order to get to the values we need.
Add the following private function to your Telemetry module to lift the `:method` value from the [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) struct:
```
# lib/my_app_web/telemetry.ex
defp get_and_put_http_method(%{conn: %{method: method}} = metadata) do
Map.put(metadata, :method, method)
end
```
Restart your server and make some more requests. You should begin to see logs with tags for both the HTTP method and the route.
Note the `:tags` and `:tag_values` options can be applied to all [`Telemetry.Metrics`](https://hexdocs.pm/telemetry_metrics/0.6.1/Telemetry.Metrics.html) types.
### Renaming value labels using tag values
Sometimes when displaying a metric, the value label may need to be transformed to improve readability. Take for example the following metric that displays the duration of the each LiveView's `mount/3` callback by `connected?` status.
```
summary("phoenix.live_view.mount.stop.duration",
unit: {:native, :millisecond},
tags: [:view, :connected?],
tag_values: &live_view_metric_tag_values/1
)
```
The following function lifts `metadata.socket.view` and `metadata.socket.connected?` to be top-level keys on `metadata`, as we did in the previous example.
```
# lib/my_app_web/telemetry.ex
defp live_view_metric_tag_values(metadata) do
metadata
|> Map.put(:view, metadata.socket.view)
|> Map.put(:connected?, metadata.socket.connected?)
end
```
However, when rendering these metrics in LiveDashboard, the value label is output as `"Elixir.Phoenix.LiveDashboard.MetricsLive true"`.
To make the value label easier to read, we can update our private function to generate more user friendly names. We'll run the value of the `:view` through [`inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1) to remove the `Elixir.` prefix and call another private function to convert the `connected?` boolean into human readable text.
```
# lib/my_app_web/telemetry.ex
defp live_view_metric_tag_values(metadata) do
metadata
|> Map.put(:view, inspect(metadata.socket.view))
|> Map.put(:connected?, get_connection_status(metadata.socket))
end
defp get_connection_status(%{connected?: true}), do: "Connected"
defp get_connection_status(%{connected?: false}), do: "Disconnected"
```
Now the value label will be rendered like `"Phoenix.LiveDashboard.MetricsLive Connected"`.
Hopefully, this gives you some inspiration on how to use the `:tag_values` option. Just remember to keep this function fast since it is called on every event.
Periodic measurements
----------------------
You might want to periodically measure key-value pairs within your application. Fortunately the [`:telemetry_poller`](https://hexdocs.pm/telemetry_poller) package provides a mechanism for custom measurements, which is useful for retrieving process information or for performing custom measurements periodically.
Add the following to the list in your Telemetry supervisor's `periodic_measurements/0` function, which is a private function that returns a list of measurements to take on a specified interval.
```
# lib/my_app_web/telemetry.ex
defp periodic_measurements do
[
{MyApp, :measure_users, []},
{:process_info,
event: [:my_app, :my_server],
name: MyApp.MyServer,
keys: [:message_queue_len, :memory]}
]
end
```
where `MyApp.measure_users/0` could be written like this:
```
# lib/my_app.ex
defmodule MyApp do
def measure_users do
:telemetry.execute([:my_app, :users], %{total: MyApp.users_count()}, %{})
end
end
```
Now with measurements in place, you can define the metrics for the events above:
```
# lib/my_app_web/telemetry.ex
def metrics do
[
...metrics...
# MyApp Metrics
last_value("my_app.users.total"),
last_value("my_app.my_server.memory", unit: :byte),
last_value("my_app.my_server.message_queue_len")
summary("my_app.my_server.call.stop.duration"),
counter("my_app.my_server.call.exception")
]
end
```
> You will implement MyApp.MyServer in the [Custom Events](#custom-events) section.
>
>
Libraries using Telemetry
--------------------------
Telemetry is quickly becoming the de-facto standard for package instrumentation in Elixir. Here is a list of libraries currently emitting `:telemetry` events.
Library authors are actively encouraged to send a PR adding their own (in alphabetical order, please):
* [Absinthe](https://hexdocs.pm/absinthe) - [Events](https://hexdocs.pm/absinthe/telemetry.html)
* [Broadway](https://hexdocs.pm/broadway) - [Events](https://hexdocs.pm/broadway/Broadway.html#module-telemetry)
* [Ecto](https://hexdocs.pm/ecto) - [Events](../ecto/ecto.repo#module-telemetry-events)
* [Oban](https://hexdocs.pm/oban) - [Events](https://hexdocs.pm/oban/Oban.Telemetry.html)
* [Phoenix](https://hexdocs.pm/phoenix) - [Events](phoenix.logger#module-instrumentation)
* [Plug](https://hexdocs.pm/plug) - [Events](../plug/plug.telemetry)
* [Tesla](https://hexdocs.pm/tesla) - [Events](https://hexdocs.pm/tesla/Tesla.Middleware.Telemetry.html)
Custom Events
--------------
If you need custom metrics and instrumentation in your application, you can utilize the `:telemetry` package (<https://hexdocs.pm/telemetry>) just like your favorite frameworks and libraries.
Here is an example of a simple GenServer that emits telemetry events. Create this file in your app at `lib/my_app/my_server.ex`:
```
# lib/my_app/my_server.ex
defmodule MyApp.MyServer do
@moduledoc """
An example GenServer that runs arbitrary functions and emits telemetry events when called.
"""
use GenServer
# A common prefix for :telemetry events
@prefix [:my_app, :my_server, :call]
def start_link(fun) do
GenServer.start_link(__MODULE__, fun, name: __MODULE__)
end
@doc """
Runs the function contained within this server.
## Events
The following events may be emitted:
* `[:my_app, :my_server, :call, :start]` - Dispatched
immediately before invoking the function. This event
is always emitted.
* Measurement: `%{system_time: system_time}`
* Metadata: `%{}`
* `[:my_app, :my_server, :call, :stop]` - Dispatched
immediately after successfully invoking the function.
* Measurement: `%{duration: native_time}`
* Metadata: `%{}`
* `[:my_app, :my_server, :call, :exception]` - Dispatched
immediately after invoking the function, in the event
the function throws or raises.
* Measurement: `%{duration: native_time}`
* Metadata: `%{kind: kind, reason: reason, stacktrace: stacktrace}`
"""
def call!, do: GenServer.call(__MODULE__, :called)
@impl true
def init(fun) when is_function(fun, 0), do: {:ok, fun}
@impl true
def handle_call(:called, _from, fun) do
# Wrap the function invocation in a "span"
result = telemetry_span(fun)
{:reply, result, fun}
end
# Emits telemetry events related to invoking the function
defp telemetry_span(fun) do
start_time = emit_start()
try do
fun.()
catch
kind, reason ->
stacktrace = System.stacktrace()
duration = System.monotonic_time() - start_time
emit_exception(duration, kind, reason, stacktrace)
:erlang.raise(kind, reason, stacktrace)
else
result ->
duration = System.monotonic_time() - start_time
emit_stop(duration)
result
end
end
defp emit_start do
start_time_mono = System.monotonic_time()
:telemetry.execute(
@prefix ++ [:start],
%{system_time: System.system_time()},
%{}
)
start_time_mono
end
defp emit_stop(duration) do
:telemetry.execute(
@prefix ++ [:stop],
%{duration: duration},
%{}
)
end
defp emit_exception(duration, kind, reason, stacktrace) do
:telemetry.execute(
@prefix ++ [:exception],
%{duration: duration},
%{
kind: kind,
reason: reason,
stacktrace: stacktrace
}
)
end
end
```
and add it to your application's supervisor tree (usually in `lib/my_app/application.ex`), giving it a function to invoke when called:
```
# lib/my_app/application.ex
children = [
# Start a server that greets the world
{MyApp.MyServer, fn -> "Hello, world!" end},
]
```
Now start an IEx session and call the server:
```
iex> MyApp.MyServer.call!
```
and you should see something like the following output:
```
[Telemetry.Metrics.ConsoleReporter] Got new event!
Event name: my_app.my_server.call.stop
All measurements: %{duration: 4000}
All metadata: %{}
Metric measurement: #Function<2.111777250/1 in Telemetry.Metrics.maybe_convert_measurement/2> (summary)
With value: 0.004 millisecond
Tag values: %{}
"Hello, world!"
```
[← Previous Page Mix tasks](mix_tasks) [Next Page → Asset Management](asset_management)
| programming_docs |
phoenix mix phx.gen.embedded mix phx.gen.embedded
=====================
Generates an embedded Ecto schema for casting/validating data outside the DB.
```
mix phx.gen.embedded Blog.Post title:string views:integer
```
The first argument is the schema module followed by the schema attributes.
The generated schema above will contain:
* an embedded schema file in `lib/my_app/blog/post.ex`
Attributes
-----------
The resource fields are given using `name:type` syntax where type are the types supported by Ecto. Omitting the type makes it default to `:string`:
```
mix phx.gen.embedded Blog.Post title views:integer
```
The following types are supported:
* `:integer`
* `:float`
* `:decimal`
* `:boolean`
* `:map`
* `:string`
* `:array`
* `:references`
* `:text`
* `:date`
* `:time`
* `:time_usec`
* `:naive_datetime`
* `:naive_datetime_usec`
* `:utc_datetime`
* `:utc_datetime_usec`
* `:uuid`
* `:binary`
* `:enum`
* `:datetime` - An alias for `:naive_datetime`
phoenix mix phx.gen.socket mix phx.gen.socket
===================
Generates a Phoenix socket handler.
```
$ mix phx.gen.socket User
```
Accepts the module name for the socket
The generated files will contain:
For a regular application:
* a client in `assets/js`
* a socket in `lib/my_app_web/channels`
For an umbrella application:
* a client in `apps/my_app_web/assets/js`
* a socket in `apps/my_app_web/lib/app_name_web/channels`
You can then generated channels with [`mix phx.gen.channel`](mix.tasks.phx.gen.channel).
phoenix Asset Management Asset Management
=================
Beside producing HTML, most web applications have various assets (JavaScript, CSS, images, fonts and so on).
From Phoenix v1.6, new applications use [esbuild](https://esbuild.github.io/) to prepare assets via the [Elixir esbuild wrapper](https://github.com/phoenixframework/esbuild). This direct integration with `esbuild` means that newly generated applications do not have dependencies on Node.js or an external build system (e.g. Webpack).
Your JavaScript is typically placed at "assets/js/app.js" and `esbuild` will extract it to "priv/static/assets/app.js". In development, this is done automatically via the `esbuild` watcher. In production, this is done by running `mix assets.deploy`.
`esbuild` can also handle your CSS files. For this, there is typically an `import "../css/app.css"` at the top of your "assets/js/app.js". We will explore alternatives below.
Finally, all other assets, that usually don't have to be preprocessed, go directly to "priv/static".
Third-party JS packages
------------------------
If you want to import JavaScript dependencies, you have two options to add them to your application:
1. Vendor those dependencies inside your project and import them in your "assets/js/app.js" using a relative path:
```
import topbar from "../vendor/topbar"
```
2. Call `npm install topbar --save` inside your assets directory and `esbuild` will be able to automatically pick them up:
```
import topbar from "topbar"
```
CSS
----
`esbuild` has basic support for CSS. If you import a `.css` file at the top of your main `.js` file, `esbuild` will also bundle it, and write it to the same directory as your final `app.js`. That's what Phoenix does by default:
```
import "../css/app.css"
```
However, if you want to use a CSS framework, you will need to use a separate tool. Here are some options to do so:
* Use [standalone Tailwind](https://github.com/phoenixframework/tailwind) or [standalone SASS](https://github.com/CargoSense/dart_sass). Both similar to `esbuild`.
* You can use `esbuild` plugins (requires `npm`). See the "Esbuild plugins" section below
Don't forget to remove the `import "../css/app.css"` from your JavaScript file when doing so.
Images, fonts, and external files
----------------------------------
If you reference an external file in your CSS or JavaScript files, `esbuild` will attempt to validate and manage them, unless told otherwise.
For example, imagine you want to reference `priv/static/images/bg.png`, served at `/images/bg.png`, from your CSS file:
```
body {
background-image: url(/images/bg.png);
}
```
The above may fail with the following message:
```
error: Could not resolve "/images/bg.png" (mark it as external to exclude it from the bundle)
```
Given the images are already managed by Phoenix, you need to mark all resources from `/images` (and also `/fonts`) as external, as the error message says. This is what Phoenix does by default for new apps since v1.6.1+. In your `config/config.exs`, you will find:
```
args: ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
```
If you need to reference other directories, you need to update the arguments above accordingly. Note running [`mix phx.digest`](mix.tasks.phx.digest) will create digested files for all of the assets in `priv/static`, so your images and fonts are still cache-busted.
Esbuild plugins
----------------
Phoenix's default configuration of `esbuild` (via the Elixir wrapper) does not allow you to use [esbuild plugins](https://esbuild.github.io/plugins/). If you want to use an esbuild plugin, for example to compile SASS files to CSS, you can replace the default build system with a custom build script.
The following is an example of a custom build using esbuild via Node.JS. First of all, you'll need to install Node.js in development and make it available for your production build step.
Then you'll need to add `esbuild` to your Node.js packages and the Phoenix packages. Inside the `assets` directory, run:
```
$ npm install esbuild --save-dev
$ npm install ../deps/phoenix ../deps/phoenix_html ../deps/phoenix_live_view --save
```
or, for Yarn:
```
$ yarn add --dev esbuild
$ yarn add ../deps/phoenix ../deps/phoenix_html ../deps/phoenix_live_view
```
Next, add a custom Javascript build script. We'll call the example `assets/build.js`:
```
const esbuild = require('esbuild')
const args = process.argv.slice(2)
const watch = args.includes('--watch')
const deploy = args.includes('--deploy')
const loader = {
// Add loaders for images/fonts/etc, e.g. { '.svg': 'file' }
}
const plugins = [
// Add and configure plugins here
]
let opts = {
entryPoints: ['js/app.js'],
bundle: true,
target: 'es2017',
outdir: '../priv/static/assets',
logLevel: 'info',
loader,
plugins
}
if (watch) {
opts = {
...opts,
watch,
sourcemap: 'inline'
}
}
if (deploy) {
opts = {
...opts,
minify: true
}
}
const promise = esbuild.build(opts)
if (watch) {
promise.then(_result => {
process.stdin.on('close', () => {
process.exit(0)
})
process.stdin.resume()
})
}
```
This script covers following use cases:
* `node build.js`: builds for development & testing (useful on CI)
* `node build.js --watch`: like above, but watches for changes continuously
* `node build.js --deploy`: builds minified assets for production
Modify `config/dev.exs` so that the script runs whenever you change files, replacing the existing `:esbuild` configuration under `watchers`:
```
config :hello, HelloWeb.Endpoint,
...
watchers: [
node: ["build.js", "--watch", cd: Path.expand("../assets", __DIR__)]
],
...
```
Modify the `aliases` task in `mix.exs` to install `npm` packages during `mix setup` and use the new `esbuild` on `mix assets.deploy`:
```
defp aliases do
[
setup: ["deps.get", "ecto.setup", "cmd --cd assets npm install"],
...,
"assets.deploy": ["cmd --cd assets node build.js --deploy", "phx.digest"]
]
end
```
Finally, remove the `esbuild` configuration from `config/config.exs` and remove the dependency from the `deps` function in your `mix.exs`, and you are done!
Removing esbuild
-----------------
If you are writing an API, or for some other reason you do not need to serve any assets, you can disable asset management completely.
1. Remove the `esbuild` configuration in `config/config.exs` and `config/dev.exs`,
2. Remove the `assets.deploy` task defined in `mix.exs`,
3. Remove the `esbuild` dependency from `mix.exs`,
4. Unlock the `esbuild` dependency:
```
$ mix deps.unlock esbuild
```
[← Previous Page Telemetry](telemetry) [Next Page → mix phx.gen.auth](mix_phx_gen_auth)
phoenix Mix tasks Mix tasks
==========
There are currently a number of built-in Phoenix-specific and Ecto-specific [Mix tasks](https://hexdocs.pm/mix/Mix.Task.html) available to us within a newly-generated application. We can also create our own application specific tasks.
> Note to learn more about `mix`, you can read Elixir's official [Introduction to Mix](https://elixir-lang.org/getting-started/mix-otp/introduction-to-mix.html).
>
>
Phoenix tasks
--------------
```
$ mix help --search "phx"
mix local.phx # Updates the Phoenix project generator locally
mix phx # Prints Phoenix help information
mix phx.digest # Digests and compresses static files
mix phx.digest.clean # Removes old versions of static assets.
mix phx.gen.auth # Generates authentication logic for a resource
mix phx.gen.cert # Generates a self-signed certificate for HTTPS testing
mix phx.gen.channel # Generates a Phoenix channel
mix phx.gen.context # Generates a context with functions around an Ecto schema
mix phx.gen.embedded # Generates an embedded Ecto schema file
mix phx.gen.html # Generates controller, views, and context for an HTML resource
mix phx.gen.json # Generates controller, views, and context for a JSON resource
mix phx.gen.live # Generates LiveView, templates, and context for a resource
mix phx.gen.notifier # Generates a notifier that delivers emails by default
mix phx.gen.presence # Generates a Presence tracker
mix phx.gen.schema # Generates an Ecto schema and migration file
mix phx.gen.secret # Generates a secret
mix phx.gen.socket # Generates a Phoenix socket handler
mix phx.new # Creates a new Phoenix application
mix phx.new.ecto # Creates a new Ecto project within an umbrella project
mix phx.new.web # Creates a new Phoenix web project within an umbrella project
mix phx.routes # Prints all routes
mix phx.server # Starts applications and their servers
```
We have seen all of these at one point or another in the guides, but having all the information about them in one place seems like a good idea.
We will cover all Phoenix Mix tasks, except `phx.new`, `phx.new.ecto`, and `phx.new.web`, which are part of the Phoenix installer. You can learn more about them or any other task by calling `mix help TASK`.
### [`mix phx.gen.html`](mix.tasks.phx.gen.html)
Phoenix offers the ability to generate all the code to stand up a complete HTML resource — Ecto migration, Ecto context, controller with all the necessary actions, view, and templates. This can be a tremendous time saver. Let's take a look at how to make this happen.
The [`mix phx.gen.html`](mix.tasks.phx.gen.html) task takes the following arguments: the module name of the context, the module name of the schema, the resource name, and a list of column\_name:type attributes. The module name we pass in must conform to the Elixir rules of module naming, following proper capitalization.
```
$ mix phx.gen.html Blog Post posts body:string word_count:integer
* creating lib/hello_web/controllers/post_controller.ex
* creating lib/hello_web/templates/post/edit.html.heex
* creating lib/hello_web/templates/post/form.html.heex
* creating lib/hello_web/templates/post/index.html.heex
* creating lib/hello_web/templates/post/new.html.heex
* creating lib/hello_web/templates/post/show.html.heex
* creating lib/hello_web/views/post_view.ex
* creating test/hello_web/controllers/post_controller_test.exs
* creating lib/hello/blog/post.ex
* creating priv/repo/migrations/20211001233016_create_posts.exs
* creating lib/hello/blog.ex
* injecting lib/hello/blog.ex
* creating test/hello/blog_test.exs
* injecting test/hello/blog_test.exs
* creating test/support/fixtures/blog_fixtures.ex
* injecting test/support/fixtures/blog_fixtures.ex
```
When [`mix phx.gen.html`](mix.tasks.phx.gen.html) is done creating files, it helpfully tells us that we need to add a line to our router file as well as run our Ecto migrations.
```
Add the resource to your browser scope in lib/hello_web/router.ex:
resources "/posts", PostController
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
Important: If we don't do this, we will see the following warnings in our logs, and our application will error when trying to execute the function.
```
$ mix phx.server
Compiling 17 files (.ex)
warning: function HelloWeb.Router.Helpers.post_path/3 is undefined or private
lib/hello_web/controllers/post_controller.ex:22:
```
If we don't want to create a context or schema for our resource we can use the `--no-context` flag. Note that this still requires a context module name as a parameter.
```
$ mix phx.gen.html Blog Post posts body:string word_count:integer --no-context
* creating lib/hello_web/controllers/post_controller.ex
* creating lib/hello_web/templates/post/edit.html.heex
* creating lib/hello_web/templates/post/form.html.heex
* creating lib/hello_web/templates/post/index.html.heex
* creating lib/hello_web/templates/post/new.html.heex
* creating lib/hello_web/templates/post/show.html.heex
* creating lib/hello_web/views/post_view.ex
* creating test/hello_web/controllers/post_controller_test.exs
```
It will tell us we need to add a line to our router file, but since we skipped the context, it won't mention anything about `ecto.migrate`.
```
Add the resource to your browser scope in lib/hello_web/router.ex:
resources "/posts", PostController
```
Similarly, if we want a context created without a schema for our resource we can use the `--no-schema` flag.
```
$ mix phx.gen.html Blog Post posts body:string word_count:integer --no-schema
* creating lib/hello_web/controllers/post_controller.ex
* creating lib/hello_web/templates/post/edit.html.heex
* creating lib/hello_web/templates/post/form.html.heex
* creating lib/hello_web/templates/post/index.html.heex
* creating lib/hello_web/templates/post/new.html.heex
* creating lib/hello_web/templates/post/show.html.heex
* creating lib/hello_web/views/post_view.ex
* creating test/hello_web/controllers/post_controller_test.exs
* creating lib/hello/blog.ex
* injecting lib/hello/blog.ex
* creating test/hello/blog_test.exs
* injecting test/hello/blog_test.exs
* creating test/support/fixtures/blog_fixtures.ex
* injecting test/support/fixtures/blog_fixtures.ex
```
It will tell us we need to add a line to our router file, but since we skipped the schema, it won't mention anything about `ecto.migrate`.
### [`mix phx.gen.json`](mix.tasks.phx.gen.json)
Phoenix also offers the ability to generate all the code to stand up a complete JSON resource — Ecto migration, Ecto schema, controller with all the necessary actions and view. This command will not create any template for the app.
The [`mix phx.gen.json`](mix.tasks.phx.gen.json) task takes the following arguments: the module name of the context, the module name of the schema, the resource name, and a list of column\_name:type attributes. The module name we pass in must conform to the Elixir rules of module naming, following proper capitalization.
```
$ mix phx.gen.json Blog Post posts title:string content:string
* creating lib/hello_web/controllers/post_controller.ex
* creating lib/hello_web/views/post_view.ex
* creating test/hello_web/controllers/post_controller_test.exs
* creating lib/hello_web/views/changeset_view.ex
* creating lib/hello_web/controllers/fallback_controller.ex
* creating lib/hello/blog/post.ex
* creating priv/repo/migrations/20170906153323_create_posts.exs
* creating lib/hello/blog.ex
* injecting lib/hello/blog.ex
* creating test/hello/blog/blog_test.exs
* injecting test/hello/blog/blog_test.exs
* creating test/support/fixtures/blog_fixtures.ex
* injecting test/support/fixtures/blog_fixtures.ex
```
When [`mix phx.gen.json`](mix.tasks.phx.gen.json) is done creating files, it helpfully tells us that we need to add a line to our router file as well as run our Ecto migrations.
```
Add the resource to your :api scope in lib/hello_web/router.ex:
resources "/posts", PostController, except: [:new, :edit]
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
Important: If we don't do this, we'll get the following warning in our logs and the application will error when attempting to load the page:
```
$ mix phx.server
Compiling 19 files (.ex)
warning: function HelloWeb.Router.Helpers.post_path/3 is undefined or private
lib/hello_web/controllers/post_controller.ex:18
```
[`mix phx.gen.json`](mix.tasks.phx.gen.json) also supports `--no-context`, `--no-schema`, and others, as in [`mix phx.gen.html`](mix.tasks.phx.gen.html).
### [`mix phx.gen.context`](mix.tasks.phx.gen.context)
If we don't need a complete HTML/JSON resource and only need a context, we can use the [`mix phx.gen.context`](mix.tasks.phx.gen.context) task. It will generate a context, a schema, a migration and a test case.
The [`mix phx.gen.context`](mix.tasks.phx.gen.context) task takes the following arguments: the module name of the context, the module name of the schema, the resource name, and a list of column\_name:type attributes.
```
$ mix phx.gen.context Accounts User users name:string age:integer
* creating lib/hello/accounts/user.ex
* creating priv/repo/migrations/20170906161158_create_users.exs
* creating lib/hello/accounts.ex
* injecting lib/hello/accounts.ex
* creating test/hello/accounts/accounts_test.exs
* injecting test/hello/accounts/accounts_test.exs
* creating test/support/fixtures/accounts_fixtures.ex
* injecting test/support/fixtures/accounts_fixtures.ex
```
> Note: If we need to namespace our resource we can simply namespace the first argument of the generator.
>
>
```
$ mix phx.gen.context Admin.Accounts User users name:string age:integer
* creating lib/hello/admin/accounts/user.ex
* creating priv/repo/migrations/20170906161246_create_users.exs
* creating lib/hello/admin/accounts.ex
* injecting lib/hello/admin/accounts.ex
* creating test/hello/admin/accounts_test.exs
* injecting test/hello/admin/accounts_test.exs
* creating test/support/fixtures/admin/accounts_fixtures.ex
* injecting test/support/fixtures/admin/accounts_fixtures.ex
```
### [`mix phx.gen.schema`](mix.tasks.phx.gen.schema)
If we don't need a complete HTML/JSON resource and are not interested in generating or altering a context we can use the [`mix phx.gen.schema`](mix.tasks.phx.gen.schema) task. It will generate a schema, and a migration.
The [`mix phx.gen.schema`](mix.tasks.phx.gen.schema) task takes the following arguments: the module name of the schema (which may be namespaced), the resource name, and a list of column\_name:type attributes.
```
$ mix phx.gen.schema Accounts.Credential credentials email:string:unique user_id:references:users
* creating lib/hello/accounts/credential.ex
* creating priv/repo/migrations/20170906162013_create_credentials.exs
```
### [`mix phx.gen.auth`](mix.tasks.phx.gen.auth)
Phoenix also offers the ability to generate all of the code to stand up a complete authentication system — Ecto migration, phoenix context, controllers, templates, etc. This can be a huge time saver, allowing you to quickly add authentication to your system and shift your focus back to the primary problems your application is trying to solve.
The [`mix phx.gen.auth`](mix.tasks.phx.gen.auth) task takes the following arguments: the module name of the context, the module name of the schema, and a plural version of the schema name used to generate database tables and route helpers.
Here is an example version of the command:
```
$ mix phx.gen.auth Accounts User users
* creating priv/repo/migrations/20201205184926_create_users_auth_tables.exs
* creating lib/hello/accounts/user_notifier.ex
* creating lib/hello/accounts/user.ex
* creating lib/hello/accounts/user_token.ex
* creating lib/hello_web/controllers/user_auth.ex
* creating test/hello_web/controllers/user_auth_test.exs
* creating lib/hello_web/views/user_confirmation_view.ex
* creating lib/hello_web/templates/user_confirmation/new.html.heex
* creating lib/hello_web/templates/user_confirmation/edit.html.heex
* creating lib/hello_web/controllers/user_confirmation_controller.ex
* creating test/hello_web/controllers/user_confirmation_controller_test.exs
* creating lib/hello_web/templates/layout/_user_menu.html.heex
* creating lib/hello_web/templates/user_registration/new.html.heex
* creating lib/hello_web/controllers/user_registration_controller.ex
* creating test/hello_web/controllers/user_registration_controller_test.exs
* creating lib/hello_web/views/user_registration_view.ex
* creating lib/hello_web/views/user_reset_password_view.ex
* creating lib/hello_web/controllers/user_reset_password_controller.ex
* creating test/hello_web/controllers/user_reset_password_controller_test.exs
* creating lib/hello_web/templates/user_reset_password/edit.html.heex
* creating lib/hello_web/templates/user_reset_password/new.html.heex
* creating lib/hello_web/views/user_session_view.ex
* creating lib/hello_web/controllers/user_session_controller.ex
* creating test/hello_web/controllers/user_session_controller_test.exs
* creating lib/hello_web/templates/user_session/new.html.heex
* creating lib/hello_web/views/user_settings_view.ex
* creating lib/hello_web/templates/user_settings/edit.html.heex
* creating lib/hello_web/controllers/user_settings_controller.ex
* creating test/hello_web/controllers/user_settings_controller_test.exs
* creating lib/hello/accounts.ex
* injecting lib/hello/accounts.ex
* creating test/hello/accounts_test.exs
* injecting test/hello/accounts_test.exs
* creating test/support/fixtures/accounts_fixtures.ex
* injecting test/support/fixtures/accounts_fixtures.ex
* injecting test/support/conn_case.ex
* injecting config/test.exs
* injecting mix.exs
* injecting lib/hello_web/router.ex
* injecting lib/hello_web/router.ex - imports
* injecting lib/hello_web/router.ex - plug
* injecting lib/hello_web/templates/layout/root.html.heex
```
When [`mix phx.gen.auth`](mix.tasks.phx.gen.auth) is done creating files, it helpfully tells us that we need to re-fetch our dependencies as well as run our Ecto migrations.
```
Please re-fetch your dependencies with the following command:
mix deps.get
Remember to update your repository by running migrations:
$ mix ecto.migrate
Once you are ready, visit "/users/register"
to create your account and then access to "/dev/mailbox" to
see the account confirmation email.
```
A more complete walk-through of how to get started with this generator is available in the [`mix phx.gen.auth` authentication guide](mix_phx_gen_auth).
### [`mix phx.gen.channel`](mix.tasks.phx.gen.channel) and [`mix phx.gen.socket`](mix.tasks.phx.gen.socket)
This task will generate a basic Phoenix channel, the socket to power the channel (if you haven't created one yet), as well a test case for it. It takes the module name for the channel as the only argument:
```
$ mix phx.gen.channel Room
* creating lib/hello_web/channels/room_channel.ex
* creating test/hello_web/channels/room_channel_test.exs
```
If your application does not have a `UserSocket` yet, it will ask if you want to create one:
```
The default socket handler - HelloWeb.UserSocket - was not found
in its default location.
Do you want to create it? [Y/n]
```
By pressing confirming, a channel will be created, then you need to connect the socket in your endpoint:
```
Add the socket handler to your `lib/hello_web/endpoint.ex`, for example:
socket "/socket", HelloWeb.UserSocket,
websocket: true,
longpoll: false
For the front-end integration, you need to import the `user_socket.js`
in your `assets/js/app.js` file:
import "./user_socket.js"
```
In case a `UserSocket` already exists or you decide to not create one, the `channel` generator will tell you to add it to the Socket manually:
```
Add the channel to your `lib/hello_web/channels/user_socket.ex` handler, for example:
channel "rooms:lobby", HelloWeb.RoomChannel
```
You can also create a socket any time by invoking [`mix phx.gen.socket`](mix.tasks.phx.gen.socket).
### [`mix phx.gen.presence`](mix.tasks.phx.gen.presence)
This task will generate a presence tracker. The module name can be passed as an argument, `Presence` is used if no module name is passed.
```
$ mix phx.gen.presence Presence
* lib/hello_web/channels/presence.ex
Add your new module to your supervision tree,
in lib/hello/application.ex:
children = [
...
HelloWeb.Presence
]
```
### [`mix phx.routes`](mix.tasks.phx.routes)
This task has a single purpose, to show us all the routes defined for a given router. We saw it used extensively in the [routing guide](routing).
If we don't specify a router for this task, it will default to the router Phoenix generated for us.
```
$ mix phx.routes
page_path GET / TaskTester.PageController.index/2
```
We can also specify an individual router if we have more than one for our application.
```
$ mix phx.routes TaskTesterWeb.Router
page_path GET / TaskTesterWeb.PageController.index/2
```
### [`mix phx.server`](mix.tasks.phx.server)
This is the task we use to get our application running. It takes no arguments at all. If we pass any in, they will be silently ignored.
```
$ mix phx.server
[info] Running TaskTesterWeb.Endpoint with Cowboy on port 4000 (http)
```
It will silently ignore our `DoesNotExist` argument:
```
$ mix phx.server DoesNotExist
[info] Running TaskTesterWeb.Endpoint with Cowboy on port 4000 (http)
```
If we would like to start our application and also have an [`IEx`](https://hexdocs.pm/iex/IEx.html) session open to it, we can run the Mix task within `iex` like this, `iex -S mix phx.server`.
```
$ iex -S mix phx.server
Erlang/OTP 17 [erts-6.4] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
[info] Running TaskTesterWeb.Endpoint with Cowboy on port 4000 (http)
Interactive Elixir (1.0.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>
```
### [`mix phx.digest`](mix.tasks.phx.digest)
This task does two things, it creates a digest for our static assets and then compresses them.
"Digest" here refers to an MD5 digest of the contents of an asset which gets added to the filename of that asset. This creates a sort of fingerprint for it. If the digest doesn't change, browsers and CDNs will use a cached version. If it does change, they will re-fetch the new version.
Before we run this task let's inspect the contents of two directories in our hello application.
First `priv/static/` which should look similar to this:
```
├── images
│ └── phoenix.png
└── robots.txt
```
And then `assets/` which should look similar to this:
```
├── css
│ └── app.css
├── js
│ └── app.js
└── vendor
└── phoenix.js
```
All of these files are our static assets. Now let's run the [`mix phx.digest`](mix.tasks.phx.digest) task.
```
$ mix phx.digest
Check your digested files at 'priv/static'.
```
We can now do as the task suggests and inspect the contents of `priv/static/` directory. We'll see that all files from `assets/` have been copied over to `priv/static/` and also each file now has a couple of versions. Those versions are:
* the original file
* a compressed file with gzip
* a file containing the original file name and its digest
* a compressed file containing the file name and its digest
We can optionally determine which files should be gzipped by using the `:gzippable_exts` option in the config file:
```
config :phoenix, :gzippable_exts, ~w(.js .css)
```
> Note: We can specify a different output folder where [`mix phx.digest`](mix.tasks.phx.digest) will put processed files. The first argument is the path where the static files are located.
>
>
```
$ mix phx.digest priv/static/ -o www/public/
Check your digested files at 'www/public/'
```
> Note: You can use [`mix phx.digest.clean`](mix.tasks.phx.digest.clean) to prune stale versions of the assets. If you want to remove all produced files, run `mix phx.digest.clean --all`.
>
>
Ecto tasks
-----------
Newly generated Phoenix applications now include Ecto and Postgrex as dependencies by default (which is to say, unless we use [`mix phx.new`](mix.tasks.phx.new) with the `--no-ecto` flag). With those dependencies come Mix tasks to take care of common Ecto operations. Let's see which tasks we get out of the box.
```
$ mix help --search "ecto"
mix ecto # Prints Ecto help information
mix ecto.create # Creates the repository storage
mix ecto.drop # Drops the repository storage
mix ecto.dump # Dumps the repository database structure
mix ecto.gen.migration # Generates a new migration for the repo
mix ecto.gen.repo # Generates a new repository
mix ecto.load # Loads previously dumped database structure
mix ecto.migrate # Runs the repository migrations
mix ecto.migrations # Displays the repository migration status
mix ecto.reset # Alias defined in mix.exs
mix ecto.rollback # Rolls back the repository migrations
mix ecto.setup # Alias defined in mix.exs
```
Note: We can run any of the tasks above with the `--no-start` flag to execute the task without starting the application.
### [`mix ecto.create`](https://hexdocs.pm/ecto/3.8.2/Mix.Tasks.Ecto.Create.html)
This task will create the database specified in our repo. By default it will look for the repo named after our application (the one generated with our app unless we opted out of Ecto), but we can pass in another repo if we want.
Here's what it looks like in action.
```
$ mix ecto.create
The database for Hello.Repo has been created.
```
There are a few things that can go wrong with `ecto.create`. If our Postgres database doesn't have a "postgres" role (user), we'll get an error like this one.
```
$ mix ecto.create
** (Mix) The database for Hello.Repo couldn't be created, reason given: psql: FATAL: role "postgres" does not exist
```
We can fix this by creating the "postgres" role in the `psql` console with the permissions needed to log in and create a database.
```
=# CREATE ROLE postgres LOGIN CREATEDB;
CREATE ROLE
```
If the "postgres" role does not have permission to log in to the application, we'll get this error.
```
$ mix ecto.create
** (Mix) The database for Hello.Repo couldn't be created, reason given: psql: FATAL: role "postgres" is not permitted to log in
```
To fix this, we need to change the permissions on our "postgres" user to allow login.
```
=# ALTER ROLE postgres LOGIN;
ALTER ROLE
```
If the "postgres" role does not have permission to create a database, we'll get this error.
```
$ mix ecto.create
** (Mix) The database for Hello.Repo couldn't be created, reason given: ERROR: permission denied to create database
```
To fix this, we need to change the permissions on our "postgres" user in the `psql` console to allow database creation.
```
=# ALTER ROLE postgres CREATEDB;
ALTER ROLE
```
If the "postgres" role is using a password different from the default "postgres", we'll get this error.
```
$ mix ecto.create
** (Mix) The database for Hello.Repo couldn't be created, reason given: psql: FATAL: password authentication failed for user "postgres"
```
To fix this, we can change the password in the environment specific configuration file. For the development environment the password used can be found at the bottom of the `config/dev.exs` file.
Finally, if we happen to have another repo called `OurCustom.Repo` that we want to create the database for, we can run this.
```
$ mix ecto.create -r OurCustom.Repo
The database for OurCustom.Repo has been created.
```
### [`mix ecto.drop`](https://hexdocs.pm/ecto/3.8.2/Mix.Tasks.Ecto.Drop.html)
This task will drop the database specified in our repo. By default it will look for the repo named after our application (the one generated with our app unless we opted out of Ecto). It will not prompt us to check if we're sure we want to drop the database, so do exercise caution.
```
$ mix ecto.drop
The database for Hello.Repo has been dropped.
```
If we happen to have another repo that we want to drop the database for, we can specify it with the `-r` flag.
```
$ mix ecto.drop -r OurCustom.Repo
The database for OurCustom.Repo has been dropped.
```
### [`mix ecto.gen.repo`](https://hexdocs.pm/ecto/3.8.2/Mix.Tasks.Ecto.Gen.Repo.html)
Many applications require more than one data store. For each data store, we'll need a new repo, and we can generate them automatically with `ecto.gen.repo`.
If we name our repo `OurCustom.Repo`, this task will create it here `lib/our_custom/repo.ex`.
```
$ mix ecto.gen.repo -r OurCustom.Repo
* creating lib/our_custom
* creating lib/our_custom/repo.ex
* updating config/config.exs
Don't forget to add your new repo to your supervision tree
(typically in lib/hello/application.ex):
{OurCustom.Repo, []}
```
Notice that this task has updated `config/config.exs`. If we take a look, we'll see this extra configuration block for our new repo.
```
. . .
config :hello, OurCustom.Repo,
username: "user",
password: "pass",
hostname: "localhost",
database: "hello_repo",
. . .
```
Of course, we'll need to change the login credentials to match what our database expects. We'll also need to change the config for other environments.
We certainly should follow the instructions and add our new repo to our supervision tree. In our `Hello` application, we would open up `lib/hello/application.ex`, and add our repo as a worker to the `children` list.
```
. . .
children = [
# Start the Ecto repository
Hello.Repo,
# Our custom repo
OurCustom.Repo,
# Start the endpoint when the application starts
HelloWeb.Endpoint,
]
. . .
```
### [`mix ecto.gen.migration`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Gen.Migration.html)
Migrations are a programmatic, repeatable way to affect changes to a database schema. Migrations are also just modules, and we can create them with the [`ecto.gen.migration`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Gen.Migration.html) task. Let's walk through the steps to create a migration for a new comments table.
We simply need to invoke the task with a `snake_case` version of the module name that we want. Preferably, the name will describe what we want the migration to do.
```
$ mix ecto.gen.migration add_comments_table
* creating priv/repo/migrations
* creating priv/repo/migrations/20150318001628_add_comments_table.exs
```
Notice that the migration's filename begins with a string representation of the date and time the file was created.
Let's take a look at the file `ecto.gen.migration` has generated for us at `priv/repo/migrations/20150318001628_add_comments_table.exs`.
```
defmodule Hello.Repo.Migrations.AddCommentsTable do
use Ecto.Migration
def change do
end
end
```
Notice that there is a single function `change/0` which will handle both forward migrations and rollbacks. We'll define the schema changes that we want using Ecto's handy DSL, and Ecto will figure out what to do depending on whether we are rolling forward or rolling back. Very nice indeed.
What we want to do is create a `comments` table with a `body` column, a `word_count` column, and timestamp columns for `inserted_at` and `updated_at`.
```
. . .
def change do
create table(:comments) do
add :body, :string
add :word_count, :integer
timestamps()
end
end
. . .
```
Again, we can run this task with the `-r` flag and another repo if we need to.
```
$ mix ecto.gen.migration -r OurCustom.Repo add_users
* creating priv/repo/migrations
* creating priv/repo/migrations/20150318172927_add_users.exs
```
For more information on how to modify your database schema please refer to the [Ecto's migration DSL docs](https://hexdocs.pm/ecto_sql/Ecto.Migration.html). For example, to alter an existing schema see the documentation on Ecto’s [`alter/2`](https://hexdocs.pm/ecto_sql/3.8.1/Ecto.Migration.html#alter/2) function.
That's it! We're ready to run our migration.
### [`mix ecto.migrate`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Migrate.html)
Once we have our migration module ready, we can simply run [`mix ecto.migrate`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Migrate.html) to have our changes applied to the database.
```
$ mix ecto.migrate
[info] == Running Hello.Repo.Migrations.AddCommentsTable.change/0 forward
[info] create table comments
[info] == Migrated in 0.1s
```
When we first run `ecto.migrate`, it will create a table for us called `schema_migrations`. This will keep track of all the migrations which we run by storing the timestamp portion of the migration's filename.
Here's what the `schema_migrations` table looks like.
```
hello_dev=# select * from schema_migrations;
version | inserted_at
---------------+---------------------
20150317170448 | 2015-03-17 21:07:26
20150318001628 | 2015-03-18 01:45:00
(2 rows)
```
When we roll back a migration, [`ecto.rollback`](#mix-ecto-rollback) will remove the record representing this migration from `schema_migrations`.
By default, `ecto.migrate` will execute all pending migrations. We can exercise more control over which migrations we run by specifying some options when we run the task.
We can specify the number of pending migrations we would like to run with the `-n` or `--step` options.
```
$ mix ecto.migrate -n 2
[info] == Running Hello.Repo.Migrations.CreatePost.change/0 forward
[info] create table posts
[info] == Migrated in 0.0s
[info] == Running Hello.Repo.Migrations.AddCommentsTable.change/0 forward
[info] create table comments
[info] == Migrated in 0.0s
```
The `--step` option will behave the same way.
```
mix ecto.migrate --step 2
```
The `--to` option will run all migrations up to and including given version.
```
mix ecto.migrate --to 20150317170448
```
### [`mix ecto.rollback`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Rollback.html)
The [`ecto.rollback`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Rollback.html) task will reverse the last migration we have run, undoing the schema changes. [`ecto.migrate`](#mix-ecto-migrate) and `ecto.rollback` are mirror images of each other.
```
$ mix ecto.rollback
[info] == Running Hello.Repo.Migrations.AddCommentsTable.change/0 backward
[info] drop table comments
[info] == Migrated in 0.0s
```
`ecto.rollback` will handle the same options as `ecto.migrate`, so `-n`, `--step`, `-v`, and `--to` will behave as they do for `ecto.migrate`.
Creating our own Mix task
--------------------------
As we've seen throughout this guide, both Mix itself and the dependencies we bring in to our application provide a number of really useful tasks for free. Since neither of these could possibly anticipate all our individual application's needs, Mix allows us to create our own custom tasks. That's exactly what we are going to do now.
The first thing we need to do is create a `mix/tasks/` directory inside of `lib/`. This is where any of our application specific Mix tasks will go.
```
$ mkdir -p lib/mix/tasks/
```
Inside that directory, let's create a new file, `hello.greeting.ex`, that looks like this.
```
defmodule Mix.Tasks.Hello.Greeting do
use Mix.Task
@shortdoc "Sends a greeting to us from Hello Phoenix"
@moduledoc """
This is where we would put any long form documentation and doctests.
"""
@impl Mix.Task
def run(_args) do
Mix.shell().info("Greetings from the Hello Phoenix Application!")
end
# We can define other functions as needed here.
end
```
Let's take a quick look at the moving parts involved in a working Mix task.
The first thing we need to do is name our module. All tasks must be defined in the `Mix.Tasks` namespace. We'd like to invoke this as `mix hello.greeting`, so we complete the module name with `Hello.Greeting`.
The `use Mix.Task` line brings in functionality from Mix that makes this module [behave as a Mix task](https://hexdocs.pm/mix/Mix.Task.html).
The `@shortdoc` module attribute holds a string which will describe our task when users invoke [`mix help`](https://hexdocs.pm/mix/Mix.Tasks.Help.html).
`@moduledoc` serves the same function that it does in any module. It's where we can put long-form documentation and doctests, if we have any.
The [`run/1`](https://hexdocs.pm/mix/Mix.Task.html#c:run/1) function is the critical heart of any Mix task. It's the function that does all the work when users invoke our task. In ours, all we do is send a greeting from our app, but we can implement our `run/1` function to do whatever we need it to. Note that [`Mix.shell().info/1`](https://hexdocs.pm/mix/Mix.html#shell/0) is the preferred way to print text back out to the user.
Of course, our task is just a module, so we can define other private functions as needed to support our `run/1` function.
Now that we have our task module defined, our next step is to compile the application.
```
$ mix compile
Compiled lib/tasks/hello.greeting.ex
Generated hello.app
```
Now our new task should be visible to [`mix help`](https://hexdocs.pm/mix/Mix.Tasks.Help.html).
```
$ mix help --search hello
mix hello.greeting # Sends a greeting to us from Hello Phoenix
```
Notice that [`mix help`](https://hexdocs.pm/mix/Mix.Tasks.Help.html) displays the text we put into the `@shortdoc` along with the name of our task.
So far, so good, but does it work?
```
$ mix hello.greeting
Greetings from the Hello Phoenix Application!
```
Indeed it does.
If you want to make your new Mix task to use your application's infrastructure, you need to make sure the application is started and configure when Mix task is being executed. This is particularly useful if you need to access your database from within the Mix task. Thankfully, Mix makes it really easy for us via the `@requirements` module attribute:
```
@requirements ["app.config"]
@impl Mix.Task
def run(_args) do
Mix.shell().info("Now I have access to Repo and other goodies!")
Mix.shell().info("Greetings from the Hello Phoenix Application!")
end
```
[← Previous Page Contexts](contexts) [Next Page → Telemetry](telemetry)
| programming_docs |
phoenix mix phx.digest.clean mix phx.digest.clean
=====================
Removes old versions of compiled assets.
By default, it will keep the latest version and 2 previous versions as well as any digest created in the last hour.
```
$ mix phx.digest.clean
$ mix phx.digest.clean -o /www/public
$ mix phx.digest.clean --age 600 --keep 3
$ mix phx.digest.clean --all
```
Options
--------
* `-o, --output` - indicates the path to your compiled assets directory. Defaults to `priv/static`
* `--age` - specifies a maximum age (in seconds) for assets. Files older than age that are not in the last `--keep` versions will be removed. Defaults to 3600 (1 hour)
* `--keep` - specifies how many previous versions of assets to keep. Defaults to 2 previous versions
* `--all` - specifies that all compiled assets (including the manifest) will be removed. Note this overrides the age and keep switches.
phoenix mix compile.phoenix mix compile.phoenix
====================
Compiles Phoenix source files that support code reloading.
If you are using Elixir v1.11+ or later, there is no longer a need to use this module as this functionality is now provided by Elixir. Just remember to update `__phoenix_recompile__?` to `__mix_recompile__?` in any module that may define it.
phoenix Contexts Contexts
=========
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [Request life-cycle guide](request_lifecycle).
>
>
> **Requirement**: This guide expects that you have gone through the [Ecto guide](ecto).
>
>
So far, we've built pages, wired up controller actions through our routers, and learned how Ecto allows data to be validated and persisted. Now it's time to tie it all together by writing web-facing features that interact with our greater Elixir application.
When building a Phoenix project, we are first and foremost building an Elixir application. Phoenix's job is to provide a web interface into our Elixir application. Naturally, we compose our applications with modules and functions, but simply defining a module with a few functions isn't enough when designing an application. We need to consider the boundaries between modules and how to group functionality. In other words, it's vital to think about application design when writing code.
Thinking about design
----------------------
Contexts are dedicated modules that expose and group related functionality. For example, anytime you call Elixir's standard library, be it [`Logger.info/1`](https://hexdocs.pm/logger/Logger.html#info/1) or [`Stream.map/2`](https://hexdocs.pm/elixir/Stream.html#map/2), you are accessing different contexts. Internally, Elixir's logger is made of multiple modules, but we never interact with those modules directly. We call the [`Logger`](https://hexdocs.pm/logger/Logger.html) module the context, exactly because it exposes and groups all of the logging functionality.
By giving modules that expose and group related functionality the name **contexts**, we help developers identify these patterns and talk about them. At the end of the day, contexts are just modules, as are your controllers, views, etc.
In Phoenix, contexts often encapsulate data access and data validation. They often talk to a database or APIs. Overall, think of them as boundaries to decouple and isolate parts of your application. Let's use these ideas to build out our web application. Our goal is to build an ecommerce system where we can showcase products, allow users to add products to their cart, and complete their orders.
> How to read this guide: Using the context generators is a great way for beginners and intermediate Elixir programmers alike to get up and running quickly while thoughtfully designing their applications. This guide focuses on those readers.
>
>
### Adding a Catalog Context
An ecommerce platform has wide-reaching coupling across a codebase so it's important to think upfront about writing well-defined interfaces. With that in mind, our goal is to build a product catalog API that handles creating, updating, and deleting the products available in our system. We'll start off with the basic features of showcasing our products, and we will add shopping cart features later. We'll see how starting with a solid foundation with isolated boundaries allows us to grow our application naturally as we add functionality.
Phoenix includes the [`mix phx.gen.html`](mix.tasks.phx.gen.html), [`mix phx.gen.json`](mix.tasks.phx.gen.json), [`mix phx.gen.live`](mix.tasks.phx.gen.live), and [`mix phx.gen.context`](mix.tasks.phx.gen.context) generators that apply the ideas of isolating functionality in our applications into contexts. These generators are a great way to hit the ground running while Phoenix nudges you in the right direction to grow your application. Let's put these tools to use for our new product catalog context.
In order to run the context generators, we need to come up with a module name that groups the related functionality that we're building. In the [Ecto guide](ecto), we saw how we can use Changesets and Repos to validate and persist user schemas, but we didn't integrate this with our application at large. In fact, we didn't think about where a "user" in our application should live at all. Let's take a step back and think about the different parts of our system. We know that we'll have products to showcase on pages for sale, along with descriptions, pricing, etc. Along with selling products, we know we'll need to support carting, order checkout, and so on. While the products being purchased are related to the cart and checkout processes, showcasing a product and managing the *exhibition* of our products is distinctly different than tracking what a user has placed in their cart or how an order is placed. A `Catalog` context is a natural place for the management of our product details and the showcasing of those products we have for sale.
> Naming things is hard. If you're stuck when trying to come up with a context name when the grouped functionality in your system isn't yet clear, you can simply use the plural form of the resource you're creating. For example, a `Products` context for managing products. As you grow your application and the parts of your system become clear, you can simply rename the context to a more refined one.
>
>
To jump-start our catalog context, we'll use [`mix phx.gen.html`](mix.tasks.phx.gen.html) which creates a context module that wraps up Ecto access for creating, updating, and deleting products, along with web files like controllers and templates for the web interface into our context. Run the following command at your project root:
```
$ mix phx.gen.html Catalog Product products title:string \
description:string price:decimal views:integer
* creating lib/hello_web/controllers/product_controller.ex
* creating lib/hello_web/templates/product/edit.html.heex
* creating lib/hello_web/templates/product/form.html.heex
* creating lib/hello_web/templates/product/index.html.heex
* creating lib/hello_web/templates/product/new.html.heex
* creating lib/hello_web/templates/product/show.html.heex
* creating lib/hello_web/views/product_view.ex
* creating test/hello_web/controllers/product_controller_test.exs
* creating lib/hello/catalog/product.ex
* creating priv/repo/migrations/20210201185747_create_products.exs
* creating lib/hello/catalog.ex
* injecting lib/hello/catalog.ex
* creating test/hello/catalog_test.exs
* injecting test/hello/catalog_test.exs
* creating test/support/fixtures/catalog_fixtures.ex
* injecting test/support/fixtures/catalog_fixtures.ex
Add the resource to your browser scope in lib/hello_web/router.ex:
resources "/products", ProductController
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
> Note: we are starting with the basics for modeling an ecommerce system. In practice, modeling such systems yields more complex relationships such as product variants, optional pricing, multiple currencies, etc. We'll keep things simple in this guide, but the foundations will give you a solid starting point to building such a complete system.
>
>
Phoenix generated the web files as expected in `lib/hello_web/`. We can also see our context files were generated inside a `lib/hello/catalog.ex` file and our product schema in the directory of the same name. Note the difference between `lib/hello` and `lib/hello_web`. We have a `Catalog` module to serve as the public API for product catalog functionality, as well as an `Catalog.Product` struct, which is an Ecto schema for casting and validating product data. Phoenix also provided web and context tests for us, it also included test helpers for creating entities via the `Hello.Catalog` context, which we'll look at later. For now, let's follow the instructions and add the route according to the console instructions, in `lib/hello_web/router.ex`:
```
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
+ resources "/products", ProductController
end
```
With the new route in place, Phoenix reminds us to update our repo by running [`mix ecto.migrate`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Migrate.html), but first we need to make a few tweaks to the generated migration in `priv/repo/migrations/*_create_products.exs`:
```
def change do
create table(:products) do
add :title, :string
add :description, :string
- add :price, :decimal
+ add :price, :decimal, precision: 15, scale: 6, null: false
- add :views, :integer
+ add :views, :integer, default: 0, null: false
timestamps()
end
```
We modified our price column to a specific precision of 15, scale of 6, along with a not-null constraint. This ensures we store currency with proper precision for any mathematical operations we may perform. Next, we added a default value and not-null constraint to our views count. With our changes in place, we're ready to migrate up our database. Let's do that now:
```
$ mix ecto.migrate
14:09:02.260 [info] == Running 20210201185747 Hello.Repo.Migrations.CreateProducts.change/0 forward
14:09:02.262 [info] create table products
14:09:02.273 [info] == Migrated 20210201185747 in 0.0s
```
Before we jump into the generated code, let's start the server with [`mix phx.server`](mix.tasks.phx.server) and visit <http://localhost:4000/products>. Let's follow the "New Product" link and click the "Save" button without providing any input. We should be greeted with the following output:
```
Oops, something went wrong! Please check the errors below.
```
When we submit the form, we can see all the validation errors inline with the inputs. Nice! Out of the box, the context generator included the schema fields in our form template and we can see our default validations for required inputs are in effect. Let's enter some example product data and resubmit the form:
```
Product created successfully.
Title: Metaprogramming Elixir
Description: Write Less Code, Get More Done (and Have Fun!)
Price: 15.000000
Views: 0
```
If we follow the "Back" link, we get a list of all products, which should contain the one we just created. Likewise, we can update this record or delete it. Now that we've seen how it works in the browser, it's time to take a look at the generated code.
Starting With Generators
-------------------------
That little [`mix phx.gen.html`](mix.tasks.phx.gen.html) command packed a surprising punch. We got a lot of functionality out-of-the-box for creating, updating, and deleting products in our catalog. This is far from a full-featured app, but remember, generators are first and foremost learning tools and a starting point for you to begin building real features. Code generation can't solve all your problems, but it will teach you the ins and outs of Phoenix and nudge you towards the proper mindset when designing your application.
Let's first check out the `ProductController` that was generated in `lib/hello_web/controllers/product_controller.ex`:
```
defmodule HelloWeb.ProductController do
use HelloWeb, :controller
alias Hello.Catalog
alias Hello.Catalog.Product
def index(conn, _params) do
products = Catalog.list_products()
render(conn, "index.html", products: products)
end
def new(conn, _params) do
changeset = Catalog.change_product(%Product{})
render(conn, "new.html", changeset: changeset)
end
def create(conn, %{"product" => product_params}) do
case Catalog.create_product(product_params) do
{:ok, product} ->
conn
|> put_flash(:info, "Product created successfully.")
|> redirect(to: Routes.product_path(conn, :show, product))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
product = Catalog.get_product!(id)
render(conn, "show.html", product: product)
end
...
end
```
We've seen how controllers work in our [controller guide](controllers), so the code probably isn't too surprising. What is worth noticing is how our controller calls into the `Catalog` context. We can see that the `index` action fetches a list of products with `Catalog.list_products/0`, and how products are persisted in the `create` action with `Catalog.create_product/1`. We haven't yet looked at the catalog context, so we don't yet know how product fetching and creation is happening under the hood – *but that's the point*. Our Phoenix controller is the web interface into our greater application. It shouldn't be concerned with the details of how products are fetched from the database or persisted into storage. We only care about telling our application to perform some work for us. This is great because our business logic and storage details are decoupled from the web layer of our application. If we move to a full-text storage engine later for fetching products instead of a SQL query, our controller doesn't need to be changed. Likewise, we can reuse our context code from any other interface in our application, be it a channel, mix task, or long-running process importing CSV data.
In the case of our `create` action, when we successfully create a product, we use [`Phoenix.Controller.put_flash/3`](phoenix.controller#put_flash/3) to show a success message, and then we redirect to the router's `product_path` show page. Conversely, if `Catalog.create_product/1` fails, we render our `"new.html"` template and pass along the Ecto changeset for the template to lift error messages from.
Next, let's dig deeper and check out our `Catalog` context in `lib/hello/catalog.ex`:
```
defmodule Hello.Catalog do
@moduledoc """
The Catalog context.
"""
import Ecto.Query, warn: false
alias Hello.Repo
alias Hello.Catalog.Product
@doc """
Returns the list of products.
## Examples
iex> list_products()
[%Product{}, ...]
"""
def list_products do
Repo.all(Product)
end
...
end
```
This module will be the public API for all product catalog functionality in our system. For example, in addition to product detail management, we may also handle product category classification and product variants for things like optional sizing, trims, etc. If we look at the `list_products/0` function, we can see the private details of product fetching. And it's super simple. We have a call to `Repo.all(Product)`. We saw how Ecto repo queries worked in the [Ecto guide](ecto), so this call should look familiar. Our `list_products` function is a generalized function name specifying the *intent* of our code – namely to list products. The details of that intent where we use our Repo to fetch the products from our PostgreSQL database is hidden from our callers. This is a common theme we'll see re-iterated as we use the Phoenix generators. Phoenix will push us to think about where we have different responsibilities in our application, and then to wrap up those different areas behind well-named modules and functions that make the intent of our code clear, while encapsulating the details.
Now we know how data is fetched, but how are products persisted? Let's take a look at the `Catalog.create_product/1` function:
```
@doc """
Creates a product.
## Examples
iex> create_product(%{field: value})
{:ok, %Product{}}
iex> create_product(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_product(attrs \\ %{}) do
%Product{}
|> Product.changeset(attrs)
|> Repo.insert()
end
```
There's more documentation than code here, but a couple of things are important to highlight. First, we can see again that our Ecto Repo is used under the hood for database access. You probably also noticed the call to `Product.changeset/2`. We talked about changesets before, and now we see them in action in our context.
If we open up the `Product` schema in `lib/hello/catalog/product.ex`, it will look immediately familiar:
```
defmodule Hello.Catalog.Product do
use Ecto.Schema
import Ecto.Changeset
schema "products" do
field :description, :string
field :price, :decimal
field :title, :string
field :views, :integer
timestamps()
end
@doc false
def changeset(product, attrs) do
product
|> cast(attrs, [:title, :description, :price, :views])
|> validate_required([:title, :description, :price, :views])
end
end
```
This is just what we saw before when we ran [`mix phx.gen.schema`](mix.tasks.phx.gen.schema), except here we see a `@doc false` above our `changeset/2` function. This tells us that while this function is publicly callable, it's not part of the public context API. Callers that build changesets do so via the context API. For example, `Catalog.create_product/1` calls into our `Product.changeset/2` to build the changeset from user input. Callers, such as our controller actions, do not access `Product.changeset/2` directly. All interaction with our product changesets is done through the public `Catalog` context.
Adding Catalog functions
-------------------------
As we've seen, your context modules are dedicated modules that expose and group related functionality. Phoenix generates generic functions, such as `list_products` and `update_product`, but they only serve as a basis for you to grow your business logic and application from. Let's add one of the basic features of our catalog by tracking product page view count.
For any ecommerce system, the ability to track how many times a product page has been viewed is essential for marketing, suggestions, ranking, etc. While we could try to use the existing `Catalog.update_product` function, along the lines of `Catalog.update_product(product, %{views: product.views + 1})`, this would not only be prone to race conditions, but it would also require the caller to know too much about our Catalog system. To see why the race condition exists, let's walk through the possible execution of events:
Intuitively, you would assume the following events:
1. User 1 loads the product page with count of 13
2. User 1 saves the product page with count of 14
3. User 2 loads the product page with count of 14
4. User 2 saves the product page with count of 15
While in practice this would happen:
1. User 1 loads the product page with count of 13
2. User 2 loads the product page with count of 13
3. User 1 saves the product page with count of 14
4. User 2 saves the product page with count of 14
The race conditions would make this an unreliable way to update the existing table since multiple callers may be updating out of date view values. There's a better way.
Let's think of a function that describes what we want to accomplish. Here's how we would like to use it:
```
product = Catalog.inc_page_views(product)
```
That looks great. Our callers will have no confusion over what this function does, and we can wrap up the increment in an atomic operation to prevent race conditions.
Open up your catalog context (`lib/hello/catalog.ex`), and add this new function:
```
def inc_page_views(%Product{} = product) do
{1, [%Product{views: views}]} =
from(p in Product, where: p.id == ^product.id, select: [:views])
|> Repo.update_all(inc: [views: 1])
put_in(product.views, views)
end
```
We built a query for fetching the current product given its ID which we pass to `Repo.update_all`. Ecto's `Repo.update_all` allows us to perform batch updates against the database, and is perfect for atomically updating values, such as incrementing our views count. The result of the repo operation returns the number of updated records, along with the selected schema values specified by the `select` option. When we receive the new product views, we use `put_in(product.views, views)` to place the new view count within the product struct.
With our context function in place, let's make use of it in our product controller. Update your `show` action in `lib/hello_web/controllers/product_controller.ex` to call our new function:
```
def show(conn, %{"id" => id}) do
product =
id
|> Catalog.get_product!()
|> Catalog.inc_page_views()
render(conn, "show.html", product: product)
end
```
We modified our `show` action to pipe our fetched product into `Catalog.inc_page_views/1`, which will return the updated product. Then we rendered our template just as before. Let's try it out. Refresh one of your product pages a few times and watch the view count increase.
We can also see our atomic update in action in the ecto debug logs:
```
[debug] QUERY OK source="products" db=0.5ms idle=834.5ms
UPDATE "products" AS p0 SET "views" = p0."views" + $1 WHERE (p0."id" = $2) RETURNING p0."views" [1, 1]
```
Good work!
As we've seen, designing with contexts gives you a solid foundation to grow your application from. Using discrete, well-defined APIs that expose the intent of your system allows you to write more maintainable applications with reusable code. Now that we know how to start extending our context API, lets explore handling relationships within a context.
In-context Relationships
-------------------------
Our basic catalog features are nice, but let's take it up a notch by categorizing products. Many ecommerce solutions allow products to be categorized in different ways, such as a product being marked for fashion, power tools, and so on. Starting with a one-to-one relationship between product and categories will cause major code changes later if we need to start supporting multiple categories. Let's set up a category association that will allow us to start off tracking a single category per product, but easily support more later as we grow our features.
For now, categories will contain only textual information. Our first order of business is to decide where categories live in the application. We have our `Catalog` context, which manages the exhibition of our products. Product categorization is a natural fit here. Phoenix is also smart enough to generate code inside an existing context, which makes adding new resources to a context a breeze. Run the following command at your project root:
> Sometimes it may be tricky to determine if two resources belong to the same context or not. In those cases, prefer distinct contexts per resource and refactor later if necessary. Otherwise you can easily end-up with large contexts of loosely related entities. Also keep in mind that the fact two resources are related does not necessarily mean they belong to the same context, otherwise you would quickly end-up with one large context, as the majority of resources in an application are connected to each other. To sum it up: if you are unsure, you should prefer separate modules (contexts).
>
>
```
$ mix phx.gen.context Catalog Category categories \
title:string:unique
You are generating into an existing context.
...
Would you like to proceed? [Yn] y
* creating lib/hello/catalog/category.ex
* creating priv/repo/migrations/20210203192325_create_categories.exs
* injecting lib/hello/catalog.ex
* injecting test/hello/catalog_test.exs
* injecting test/support/fixtures/catalog_fixtures.ex
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
This time around, we used [`mix phx.gen.context`](mix.tasks.phx.gen.context), which is just like [`mix phx.gen.html`](mix.tasks.phx.gen.html), except it doesn't generate the web files for us. Since we already have controllers and templates for managing products, we can integrate the new category features into our existing web form and product show page. We can see we now have a new `Category` schema alongside our product schema at `lib/hello/catalog/category.ex`, and Phoenix told us it was *injecting* new functions in our existing Catalog context for the category functionality. The injected functions will look very familiar to our product functions, with new functions like `create_category`, `list_categories`, and so on. Before we migrate up, we need to do a second bit of code generation. Our category schema is great for representing an individual category in the system, but we need to support a many-to-many relationship between products and categories. Fortunately, ecto allows us to do this simply with a join table, so let's generate that now with the `ecto.gen.migration` command:
```
$ mix ecto.gen.migration create_product_categories
* creating priv/repo/migrations/20210203192958_create_product_categories.exs
```
Next, let's open up the new migration file and add the following code to the `change` function:
```
defmodule Hello.Repo.Migrations.CreateProductCategories do
use Ecto.Migration
def change do
create table(:product_categories, primary_key: false) do
add :product_id, references(:products, on_delete: :delete_all)
add :category_id, references(:categories, on_delete: :delete_all)
end
create index(:product_categories, [:product_id])
create index(:product_categories, [:category_id])
create unique_index(:product_categories, [:product_id, :category_id])
end
end
```
We created a `product_categories` table and used the `primary_key: false` option since our join table does not need a primary key. Next we defined our `:product_id` and `:category_id` foreign key fields, and passed `on_delete: :delete_all` to ensure the database prunes our join table records if a linked product or category is deleted. By using a database constraint, we enforce data integrity at the database level, rather than relying on ad-hoc and error-prone application logic.
Next, we created indexes for our foreign keys, and a unique index to ensure a product cannot have duplicate categories. With our migrations in place, we can migrate up.
```
$ mix ecto.migrate
18:20:36.489 [info] == Running 20210222231834 Hello.Repo.Migrations.CreateCategories.change/0 forward
18:20:36.493 [info] create table categories
18:20:36.508 [info] create index categories_title_index
18:20:36.512 [info] == Migrated 20210222231834 in 0.0s
18:20:36.547 [info] == Running 20210222231930 Hello.Repo.Migrations.CreateProductCategories.change/0 forward
18:20:36.547 [info] create table product_categories
18:20:36.557 [info] create index product_categories_product_id_index
18:20:36.558 [info] create index product_categories_category_id_index
18:20:36.560 [info] create index product_categories_product_id_category_id_index
18:20:36.562 [info] == Migrated 20210222231930 in 0.0s
```
Now that we have a `Catalog.Product` schema and a join table to associate products and categories, we're nearly ready to start wiring up our new features. Before we dive in, we first need real categories to select in our web UI. Let's quickly seed some new categories in the application. Add the following code to your seeds file in `priv/repo/seeds.exs`:
```
for title <- ["Home Improvement", "Power Tools", "Gardening", "Books"] do
{:ok, _} = Hello.Catalog.create_category(%{title: title})
end
```
We simply enumerate over a list of category titles and use the generated `create_category/1` function of our catalog context to persist the new records. We can run the seeds with [`mix run`](https://hexdocs.pm/mix/Mix.Tasks.Run.html):
```
$ mix run priv/repo/seeds.exs
[debug] QUERY OK db=3.1ms decode=1.1ms queue=0.7ms idle=2.2ms
INSERT INTO "categories" ("title","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["Home Improvement", ~N[2021-02-03 19:39:53], ~N[2021-02-03 19:39:53]]
[debug] QUERY OK db=1.2ms queue=1.3ms idle=12.3ms
INSERT INTO "categories" ("title","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["Power Tools", ~N[2021-02-03 19:39:53], ~N[2021-02-03 19:39:53]]
[debug] QUERY OK db=1.1ms queue=1.1ms idle=15.1ms
INSERT INTO "categories" ("title","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["Gardening", ~N[2021-02-03 19:39:53], ~N[2021-02-03 19:39:53]]
[debug] QUERY OK db=2.4ms queue=1.0ms idle=17.6ms
INSERT INTO "categories" ("title","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["Books", ~N[2021-02-03 19:39:53], ~N[2021-02-03 19:39:53]]
```
Perfect. Before we integrate categories in the web layer, we need to let our context know how to associate products and categories. First, open up `lib/hello/catalog/product.ex` and add the following association:
```
+ alias Hello.Catalog.Category
schema "products" do
field :description, :string
field :price, :decimal
field :title, :string
field :views, :integer
+ many_to_many :categories, Category, join_through: "product_categories", on_replace: :delete
timestamps()
end
```
We used [`Ecto.Schema`](https://hexdocs.pm/ecto/3.8.2/Ecto.Schema.html)'s `many_to_many` macro to let Ecto know how to associate our product to multiple categories thru the `"product_categories"` join table. We also used the `on_replace: :delete` option to declare that any existing join records should be deleted when we are changing our categories.
With our schema associations set up, we can implement the selection of categories in our product form. To do so, we need to translate the user input of catalog IDs from the front-end to our many-to-many association. Fortunately Ecto makes this a breeze now that our schema is set up. Open up your catalog context and make the following changes:
```
- def get_product!(id), do: Repo.get!(Product, id)
+ def get_product!(id) do
+ Product |> Repo.get(id) |> Repo.preload(:categories)
+ end
def create_product(attrs \\ %{}) do
%Product{}
- |> Product.changeset(attrs)
+ |> change_product(attrs)
|> Repo.insert()
end
def update_product(%Product{} = product, attrs) do
product
- |> Product.changeset(attrs)
+ |> change_product(attrs)
|> Repo.update()
end
def change_product(%Product{} = product, attrs \\ %{}) do
- Product.changeset(product, attrs)
+ categories = list_categories_by_id(attrs["category_ids"])
+ product
+ |> Repo.preload(:categories)
+ |> Product.changeset(attrs)
+ |> Ecto.Changeset.put_assoc(:categories, categories)
end
+ def list_categories_by_id(nil), do: []
+ def list_categories_by_id(category_ids) do
+ Repo.all(from c in Category, where: c.id in ^category_ids)
+ end
```
First, we added `Repo.preload` to preload our categories when we fetch a product. This will allow us to reference `product.categories` in our controllers, templates, and anywhere else we want to make use of category information. Next, we modified our `create_product` and `update_product` functions to call into our existing `change_product` function to produce a changeset. Within `change_product` we added a lookup to find all categories if the `"category_ids"` attribute is present. Then we preloaded categories and called `Ecto.Changeset.put_assoc` to place the fetched categories into the changeset. Finally, we implemented the `list_categories_by_id/1` function to query the categories matching the category IDs, or return an empty list if no `"category_ids"` attribute is present. Now our `create_product` and `update_product` functions receive a changeset with the category associations all ready to go once we attempt an insert or update against our repo.
Next, let's expose our new feature to the web by adding the category input to our product form. To keep our form template tidy, let's write a new function to wrap up the details of rendering a category select input for our product. Open up your `ProductView` in `lib/hello_web/views/product_view.ex` and key this in:
```
defmodule HelloWeb.ProductView do
use HelloWeb, :view
def category_select(f, changeset) do
existing_ids = changeset |> Ecto.Changeset.get_change(:categories, []) |> Enum.map(& &1.data.id)
category_opts =
for cat <- Hello.Catalog.list_categories(),
do: [key: cat.title, value: cat.id, selected: cat.id in existing_ids]
multiple_select(f, :category_ids, category_opts)
end
end
```
We added a new `category_select/2` function which uses [`Phoenix.HTML`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.html)'s `multiple_select/3` to generate a multiple select tag. We calculated the existing category IDs from our changeset, then used those values when we generate the select options for the input tag. We did this by enumerating over all of our categories and returning the appropriate `key`, `value`, and `selected` values. We marked an option as selected if the category ID was found in those category IDs in our changeset.
With our `category_select` function in place, we can open up `lib/hello_web/templates/product/form.html.heex` and add:
```
...
<%= label f, :views %>
<%= number_input f, :views %>
<%= error_tag f, :views %>
+ <%= category_select f, @changeset %>
<div>
<%= submit "Save" %>
</div>
```
We added a `category_select` above our save button. Now let's try it out. Next, let's show the product's categories in the product show template. Add the following code to `lib/hello_web/templates/product/show.html.heex`:
```
...
+ <li>
+ <strong>Categories:</strong>
+ <%= for cat <- @product.categories do %>
+ <%= cat.title %>
+ <br>
+ <% end %>
+ </li>
</ul>
```
Now if we start the server with [`mix phx.server`](mix.tasks.phx.server) and visit <http://localhost:4000/products/new>, we'll see the new category multiple select input. Enter some valid product details, select a category or two, and click save.
```
Title: Elixir Flashcards
Description: Flash card set for the Elixir programming language
Price: 5.000000
Views: 0
Categories:
Education
Books
```
It's not much to look at yet, but it works! We added relationships within our context complete with data integrity enforced by the database. Not bad. Let's keep building!
Cross-context dependencies
---------------------------
Now that we have the beginnings of our product catalog features, let's begin to work on the other main features of our application – carting products from the catalog. In order to properly track products that have been added to a user's cart, we'll need a new place to persist this information, along with point-in-time product information like the price at time of carting. This is necessary so we can detect product price changes in the future. We know what we need to build, but now we need to decide where the cart functionality lives in our application.
If we take a step back and think about the isolation of our application, the exhibition of products in our catalog distinctly differs from the responsibilities of managing a user's cart. A product catalog shouldn't care about the rules of a our shopping cart system, and vice-versa. There's a clear need here for a separate context to handle the new cart responsibilities. Let's call it `ShoppingCart`.
Let's create a `ShoppingCart` context to handle basic cart duties. Before we write code, let's imagine we have the following feature requirements:
1. Add products to a user's cart from the product show page
2. Store point-in-time product price information at time of carting
3. Store and update quantities in cart
4. Calculate and display sum of cart prices
From the description, it's clear we need a `Cart` resource for storing the user's cart, along with a `CartItem` to track products in the cart. With our plan set, let's get to work. Run the following command to generate our new context:
```
$ mix phx.gen.context ShoppingCart Cart carts user_uuid:uuid:unique
* creating lib/hello/shopping_cart/cart.ex
* creating priv/repo/migrations/20210205203128_create_carts.exs
* creating lib/hello/shopping_cart.ex
* injecting lib/hello/shopping_cart.ex
* creating test/hello/shopping_cart_test.exs
* injecting test/hello/shopping_cart_test.exs
* creating test/support/fixtures/shopping_cart_fixtures.ex
* injecting test/support/fixtures/shopping_cart_fixtures.ex
Some of the generated database columns are unique. Please provide
unique implementations for the following fixture function(s) in
test/support/fixtures/shopping_cart_fixtures.ex:
def unique_cart_user_uuid do
raise "implement the logic to generate a unique cart user_uuid"
end
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
We generated our new context `ShoppingCart`, with a new `ShoppingCart.Cart` schema to tie a user to their cart which holds cart items. We don't have real users yet, so for now our cart will be tracked by an anonymous user UUID that we'll add to our plug session in a moment. With our cart in place, let's generate our cart items:
```
$ mix phx.gen.context ShoppingCart CartItem cart_items \
cart_id:references:carts product_id:references:products \
price_when_carted:decimal quantity:integer
You are generating into an existing context.
...
Would you like to proceed? [Yn] y
* creating lib/hello/shopping_cart/cart_item.ex
* creating priv/repo/migrations/20210205213410_create_cart_items.exs
* injecting lib/hello/shopping_cart.ex
* injecting test/hello/shopping_cart_test.exs
* injecting test/support/fixtures/shopping_cart_fixtures.ex
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
We generated a new resource inside our `ShoppingCart` named `CartItem`. This schema and table will hold references to a cart and product, along with the price at the time we added the item to our cart, and the quantity the user wishes to purchase. Let's touch up the generated migration file in `priv/repo/migrations/*_create_cart_items.ex`:
```
create table(:cart_items) do
- add :price_when_carted, :decimal
+ add :price_when_carted, :decimal, precision: 15, scale: 6, null: false
add :quantity, :integer
- add :cart_id, references(:carts, on_delete: :nothing)
+ add :cart_id, references(:carts, on_delete: :delete_all)
- add :product_id, references(:products, on_delete: :nothing)
+ add :product_id, references(:products, on_delete: :delete_all)
timestamps()
end
create index(:cart_items, [:cart_id])
create index(:cart_items, [:product_id])
+ create unique_index(:cart_items, [:cart_id, :product_id])
```
We used the `:delete_all` strategy again to enforce data integrity. This way, when a cart or product is deleted from the application, we don't have to rely on application code in our `ShoppingCart` or `Catalog` contexts to worry about cleaning up the records. This keeps our application code decoupled and the data integrity enforcement where it belongs – in the database. We also added a unique constraint to ensure a duplicate product is not allowed to be added to a cart. With our database tables in place, we can now migrate up:
```
$ mix ecto.migrate
16:59:51.941 [info] == Running 20210205203342 Hello.Repo.Migrations.CreateCarts.change/0 forward
16:59:51.945 [info] create table carts
16:59:51.949 [info] create index carts_user_uuid_index
16:59:51.952 [info] == Migrated 20210205203342 in 0.0s
16:59:51.988 [info] == Running 20210205213410 Hello.Repo.Migrations.CreateCartItems.change/0 forward
16:59:51.988 [info] create table cart_items
16:59:51.998 [info] create index cart_items_cart_id_index
16:59:52.000 [info] create index cart_items_product_id_index
16:59:52.001 [info] create index cart_items_cart_id_product_id_index
16:59:52.002 [info] == Migrated 20210205213410 in 0.0s
```
Our database is ready to go with new `carts` and `cart_items` tables, but now we need to map that back into application code. You may be wondering how we can mix database foreign keys across different tables and how that relates to the context pattern of isolated, grouped functionality. Let's jump in and discuss the approaches and their tradeoffs.
### Cross-context data
So far, we've done a great job isolating the two main contexts of our application from each other, but now we have a necessary dependency to handle.
Our `Catalog.Product` resource serves to keep the responsibilities of representing a product inside the catalog, but ultimately for an item to exist in the cart, a product from the catalog must be present. Given this, our `ShoppingCart` context will have a data dependency on the `Catalog` context. With that in mind, we have two options. One is to expose APIs on the `Catalog` context that allows us to efficiently fetch product data for use in the `ShoppingCart` system, which we would manually stitch together. Or we can use database joins to fetch the dependent data. Both are valid options given your tradeoffs and application size, but joining data from the database when you have a hard data dependency is just fine for a large class of applications and is the approach we will take here.
Now that we know where our data dependencies exist, let's add our schema associations so we can tie shopping cart items to products. First, let's make a quick change to our cart schema in `lib/hello/shopping_cart/cart.ex` to associate a cart to its items:
```
schema "carts" do
field :user_uuid, Ecto.UUID
+ has_many :items, Hello.ShoppingCart.CartItem
timestamps()
end
```
Now that our cart is associated to the items we place in it, let's set up the cart item associations inside `lib/hello/shopping_cart/cart_item.ex`:
```
schema "cart_items" do
- field :cart_id, :id
- field :product_id, :id
field :price_when_carted, :decimal
field :quantity, :integer
+ belongs_to :cart, Hello.ShoppingCart.Cart
+ belongs_to :product, Hello.Catalog.Product
timestamps()
end
@doc false
def changeset(cart_item, attrs) do
cart_item
|> cast(attrs, [:price_when_carted, :quantity])
|> validate_required([:price_when_carted, :quantity])
+ |> validate_number(:quantity, greater_than_or_equal_to: 0, less_than: 100)
end
```
First, we replaced the `cart_id` field with a standard `belongs_to` pointing at our `ShoppingCart.Cart` schema. Next, we replaced our `product_id` field by adding our first cross-context data dependency with a `belongs_to` for the `Catalog.Product` schema. Here, we intentionally coupled the data boundaries because it provides exactly what we need. An isolated context API with the bare minimum knowledge necessary to reference a product in our system. Next, we added a new validation to our changeset. With `validate_number/3`, we ensure any quantity provided by user input is between 0 and 100.
With our schemas in place, we can start integrating the new data structures and `ShoppingCart` context APIs into our web-facing features.
### Adding Shopping Cart functions
As we mentioned before, the context generators are only a starting point for our application. We can and should write well-named, purpose built functions to accomplish the goals of our context. We have a few new features to implement. First, we need to ensure every user of our application is granted a cart if one does not yet exist. From there, we can then allow users to add items to their cart, update item quantities, and calculate cart totals. Let's get started!
We won't focus on a real user authentication system at this point, but by the time we're done, you'll be able to naturally integrate one with what we've written here. To simulate a current user session, open up your `lib/hello_web/router.ex` and key this in:
```
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
+ plug :fetch_current_user
+ plug :fetch_current_cart
end
+ defp fetch_current_user(conn, _) do
+ if user_uuid = get_session(conn, :current_uuid) do
+ assign(conn, :current_uuid, user_uuid)
+ else
+ new_uuid = Ecto.UUID.generate()
+
+ conn
+ |> assign(:current_uuid, new_uuid)
+ |> put_session(:current_uuid, new_uuid)
+ end
+ end
+ alias Hello.ShoppingCart
+
+ def fetch_current_cart(conn, _opts) do
+ if cart = ShoppingCart.get_cart_by_user_uuid(conn.assigns.current_uuid) do
+ assign(conn, :cart, cart)
+ else
+ {:ok, new_cart} = ShoppingCart.create_cart(conn.assigns.current_uuid)
+ assign(conn, :cart, new_cart)
+ end
+ end
```
We added a new `:fetch_current_user` and `:fetch_current_cart` plug to our browser pipeline to run on all browser-based requests. Next, we implemented the `fetch_current_user` plug which simply checks the session for a user UUID that was previously added. If we find one, we add a `current_uuid` assign to the connection and we're done. In the case we haven't yet identified this visitor, we generate a unique UUID with `Ecto.UUID.generate()`, then we place that value in the `current_uuid` assign, along with a new session value to identify this visitor on future requests. A random, unique ID isn't much to represent a user, but it's enough for us to track and identify a visitor across requests, which is all we need for now. Later as our application becomes more complete, you'll be ready to migrate to a complete user authentication solution. With a guaranteed current user, we then implemented the `fetch_current_cart` plug which either finds a cart for the user UUID or creates a cart for the current user and assigns the result in the connection assigns. We'll need to implement our `ShoppingCart.get_cart_by_user_uuid/1` and modify the create cart function to accept a UUID, but let's add our routes first.
We'll need to implement a cart controller for handling cart operations like viewing a cart, updating quantities, and initiating the checkout process, as well as a cart items controller for adding and removing individual items to and from the cart. Add the following routes to your router in `lib/hello_web/router.ex`:
```
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
resources "/products", ProductController
+ resources "/cart_items", CartItemController, only: [:create, :delete]
+ get "/cart", CartController, :show
+ put "/cart", CartController, :update
end
```
We added a `resources` declaration for a `CartItemController`, which will wire up the routes for a create and delete action for adding and remove individual cart items. Next, we added two new routes pointing at a `CartController`. The first route, a GET request, will map to our show action, to show the cart contents. The second route, a PUT request, will handle the submission of a form for updating our cart quantities.
With our routes in place, let's add the ability to add an item to our cart from the product show page. Create a new file at `lib/hello_web/controllers/cart_item_controller.ex` and key this in:
```
defmodule HelloWeb.CartItemController do
use HelloWeb, :controller
alias Hello.{ShoppingCart, Catalog}
def create(conn, %{"product_id" => product_id}) do
product = Catalog.get_product!(product_id)
case ShoppingCart.add_item_to_cart(conn.assigns.cart, product) do
{:ok, _item} ->
conn
|> put_flash(:info, "Item added to your cart")
|> redirect(to: Routes.cart_path(conn, :show))
{:error, _changeset} ->
conn
|> put_flash(:error, "There was an error adding the item to your cart")
|> redirect(to: Routes.cart_path(conn, :show))
end
end
def delete(conn, %{"id" => product_id}) do
{:ok, _cart} = ShoppingCart.remove_item_from_cart(conn.assigns.cart, product_id)
redirect(conn, to: Routes.cart_path(conn, :show))
end
end
```
We defined a new `CartItemController` with the create and delete actions that we declared in our router. For `create`, we first lookup the product in the catalog with `Catalog.get_product!/1`, then we call a `ShoppingCart.add_item_to_cart/2` function which we'll implement in a moment. If successful, we show a flash successful message and redirect to the cart show page; else, we show a flash error message and redirect to the cart show page. For `delete`, we'll call a `remove_item_from_cart` function which we'll implement on our `ShoppingCart` context and then redirect back to the cart show page. We haven't implemented these two shopping cart functions yet, but notice how their names scream their intent: `add_item_to_cart` and `remove_item_from_cart` make it obvious what we are accomplishing here. It also allows us to spec out our web layer and context APIs without thinking about all the implementation details at once.
Let's implement the new interface for the `ShoppingCart` context API in `lib/hello/shopping_cart.ex`:
```
alias Hello.Catalog
alias Hello.ShoppingCart.{Cart, CartItem}
def get_cart_by_user_uuid(user_uuid) do
Repo.one(
from(c in Cart,
where: c.user_uuid == ^user_uuid,
left_join: i in assoc(c, :items),
left_join: p in assoc(i, :product),
order_by: [asc: i.inserted_at],
preload: [items: {i, product: p}]
)
)
end
- def create_cart(attrs \\ %{}) do
- %Cart{}
- |> Cart.changeset(attrs)
+ def create_cart(user_uuid) do
+ %Cart{user_uuid: user_uuid}
+ |> Cart.changeset(%{})
|> Repo.insert()
+ |> case do
+ {:ok, cart} -> {:ok, reload_cart(cart)}
+ {:error, changeset} -> {:error, changeset}
+ end
end
defp reload_cart(%Cart{} = cart), do: get_cart_by_user_uuid(cart.user_uuid)
def add_item_to_cart(%Cart{} = cart, %Catalog.Product{} = product) do
%CartItem{quantity: 1, price_when_carted: product.price}
|> CartItem.changeset(%{})
|> Ecto.Changeset.put_assoc(:cart, cart)
|> Ecto.Changeset.put_assoc(:product, product)
|> Repo.insert(
on_conflict: [inc: [quantity: 1]],
conflict_target: [:cart_id, :product_id]
)
end
def remove_item_from_cart(%Cart{} = cart, product_id) do
{1, _} =
Repo.delete_all(
from(i in CartItem,
where: i.cart_id == ^cart.id,
where: i.product_id == ^product_id
)
)
{:ok, reload_cart(cart)}
end
```
We started by implementing `get_cart_by_user_uuid/1` which fetches our cart and joins the cart items, and their products so that we have the full cart populated with all preloaded data. Next, we modified our `create_cart` function to accept a user UUID instead of attributes, which we used to populate the `user_uuid` field. If the insert is successful, we reload the cart contents by calling a private `reload_cart/1` function, which simply calls `get_cart_by_user_uuid/1` to refetch data. Next, we wrote our new `add_item_to_cart/2` function which accepts a cart struct and a product struct from the catalog. We used an upsert operation against our repo to either insert a new cart item into the database, or increase the quantity by one if it already exists in the cart. This is accomplished via the `on_conflict` and `conflict_target` options, which tells our repo how to handle an insert conflict. Next, we implemented `remove_item_from_cart/2` where we simply issue a `Repo.delete_all` call with a query to delete the cart item in our cart that matches the product ID. Finally, we reload the cart contents by calling `reload_cart/1`.
With our new cart functions in place, we can now expose the "Add to cart" button on the product catalog show page. Open up your template in `lib/hello_web/templates/product/show.html.heex` and make the following changes:
```
<h1>Show Product</h1>
+<%= link "Add to cart",
+ to: Routes.cart_item_path(@conn, :create, product_id: @product.id),
+ method: :post %>
...
```
The `link` functions from [`Phoenix.HTML`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.html) accepts a `:method` option to issue an HTTP verb when clicked, instead of the default GET request. With this link in place, the "Add to cart" link will issue a POST request, which will be matched by the route we defined in router which dispatches to the `CartItemController.create/2` function.
Let's try it out. Start your server with [`mix phx.server`](mix.tasks.phx.server) and visit a product page. If we try clicking the add to cart link, we'll be greeted by an error page with the following logs in the console:
```
[info] POST /cart_items
[debug] Processing with HelloWeb.CartItemController.create/2
Parameters: %{"_method" => "post", "product_id" => "1", ...}
Pipelines: [:browser]
INSERT INTO "cart_items" ...
[info] Sent 302 in 24ms
[info] GET /cart
[debug] Processing with HelloWeb.CartController.show/2
Parameters: %{}
Pipelines: [:browser]
[debug] QUERY OK source="carts" db=1.9ms idle=1798.5ms
[error] #PID<0.856.0> running HelloWeb.Endpoint (connection #PID<0.841.0>, stream id 5) terminated
Server: localhost:4000 (http)
Request: GET /cart
** (exit) an exception was raised:
** (UndefinedFunctionError) function HelloWeb.CartController.init/1 is undefined
(module HelloWeb.CartController is not available)
...
```
It's working! Kind of. If we follow the logs, we see our POST to the `/cart_items` path. Next, we can see our `ShoppingCart.add_item_to_cart` function successfully inserted a row into the `cart_items` table, and then we issued a redirect to `/cart`. Before our error, we also see a query to the `carts` table, which means we're fetching the current user's cart. So far so good. We know our `CartItem` controller and new `ShoppingCart` context functions are doing their jobs, but we've hit our next unimplemented feature when the router attempts to dispatch to a non-existent cart controller. Let's create the cart controller, view, and template to display and manage user carts.
Create a new file at `lib/hello_web/controllers/cart_controller.ex` and key this in:
```
defmodule HelloWeb.CartController do
use HelloWeb, :controller
alias Hello.ShoppingCart
def show(conn, _params) do
render(conn, "show.html", changeset: ShoppingCart.change_cart(conn.assigns.cart))
end
end
```
We defined a new cart controller to handle the `get "/cart"` route. For showing a cart, we render a `"show.html"` template which we'll create in moment. We know we need to allow the cart items to be changed by quantity updates, so right away we know we'll need a cart changeset. Fortunately, the context generator included a `ShoppingChart.change_cart/1` function, which we'll use. We pass it our cart struct which is already in the connection assigns thanks to the `fetch_current_cart` plug we defined in the router.
Next, we can implement the view and template. Create a new view file at `lib/hello_web/views/cart_view.ex` with the following content:
```
defmodule HelloWeb.CartView do
use HelloWeb, :view
alias Hello.ShoppingCart
def currency_to_str(%Decimal{} = val), do: "$#{Decimal.round(val, 2)}"
end
```
We created a view to render our `show.html` template and aliased our `ShoppingCart` context so it will be in scope for our template. We'll need to display the cart prices like product item price, cart total, etc, so we defined a `currency_to_str/1` which takes our decimal struct, rounds it properly for display, and prepends a USD dollar sign.
Next we can create the template at `lib/hello_web/templates/cart/show.html.heex`:
```
<h1>My Cart</h1>
<%= if @cart.items == [] do %>
Your cart is empty
<% else %>
<%= form_for @changeset, Routes.cart_path(@conn, :update), fn f -> %>
<ul>
<%= for item_form <- inputs_for(f, :items), item = item_form.data do %>
<li>
<%= hidden_inputs_for(item_form) %>
<%= item.product.title %>
<%= number_input item_form, :quantity %>
<%= currency_to_str(ShoppingCart.total_item_price(item)) %>
</li>
<% end %>
</ul>
<%= submit "update cart" %>
<% end %>
<b>Total</b>: <%= currency_to_str(ShoppingCart.total_cart_price(@cart)) %>
<% end %>
```
We started by showing the empty cart message if our preloaded `cart.items` is empty. If we have items, we use [`form_for`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Form.html#form_for/4) to take our cart changeset that we assigned in the `CartController.show/2` action and create a form which maps to our cart controller `update/2` action. Within the form, we use [`Phoenix.HTML.Form.inputs_for/2`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Form.html#inputs_for/2) to render inputs for the nested cart items. For each item form input, we use [`hidden_inputs_for/1`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Form.html#hidden_inputs_for/1) which will render out the item ID as a hidden input tag. This will allow us to map item inputs back together when the form is submitted. Next, we display the product title for the item in the cart, followed by a number input for the item quantity. We finish the item form by converting the item price to string. We haven't written the `ShoppingCart.total_item_price/1` function yet, but again we employed the idea of clear, descriptive public interfaces for our contexts. After rendering inputs for all the cart items, we show an "update cart" submit button, along with the total price of the entire cart. This is accomplished with another new `ShoppingCart.total_cart_price/1` function which we'll implement in a moment.
We're almost ready to try out our cart page, but first we need to implement our new currency calculation functions. Open up your shopping cart context at `lib/hello/shopping_cart.ex` and add these new functions:
```
def total_item_price(%CartItem{} = item) do
Decimal.mult(item.product.price, item.quantity)
end
def total_cart_price(%Cart{} = cart) do
Enum.reduce(cart.items, 0, fn item, acc ->
item
|> total_item_price()
|> Decimal.add(acc)
end)
end
```
We implemented `total_item_price/1` which accepts a `%CartItem{}` struct. To calculate the total price, we simply take the preloaded product's price and multiply it by the item's quantity. We used [`Decimal.mult/2`](https://hexdocs.pm/decimal/2.0.0/Decimal.html#mult/2) to take our decimal currency struct and multiply it with proper precision. Similarly for calculating the total cart price, we implemented a `total_cart_price/1` function which accepts the cart and sums the preloaded product prices for items in the cart. We again make use of the [`Decimal`](https://hexdocs.pm/decimal/2.0.0/Decimal.html) functions to add our decimal structs together.
Now that we can calculate price totals, let's try it out! Visit [`http://localhost:4000/cart`](http://localhost:4000/cart) and you should already see your first item in the cart. Going back to the same product and clicking "add to cart" will show our upsert in action. Your quantity should now be two. Nice work!
Our cart page is almost complete, but submitting the form will yield yet another error.
```
Request: POST /cart
** (exit) an exception was raised:
** (UndefinedFunctionError) function HelloWeb.CartController.update/2 is undefined or private
```
Let's head back to our `CartController` at `lib/hello_web/controllers/cart_controller.ex` and implement the update action:
```
def update(conn, %{"cart" => cart_params}) do
case ShoppingCart.update_cart(conn.assigns.cart, cart_params) do
{:ok, cart} ->
redirect(conn, to: Routes.cart_path(conn, :show))
{:error, _changeset} ->
conn
|> put_flash(:error, "There was an error updating your cart")
|> redirect(to: Routes.cart_path(conn, :show))
end
end
```
We started by plucking out the cart params from the form submit. Next, we call our existing `ShoppingCart.update_cart/2` function which was added by the context generator. We'll need to make some changes to this function, but the interface is good as is. If the update is successful, we redirect back to the cart page, otherwise we show a flash error message and send the user back to the cart page to fix any mistakes. Out-of-the-box, our `ShoppingCart.update_cart/2` function only concerned itself with casting the cart params into a changeset and updates it against our repo. For our purposes, we now need it to handled nested cart item associations, and most importantly, business logic for how to handle quantity updates like zero-quantity items being removed from the cart.
Head back over to your shopping cart context in `lib/hello/shopping_cart.ex` and replace your `update_cart/2` function with the following implementation:
```
def update_cart(%Cart{} = cart, attrs) do
changeset =
cart
|> Cart.changeset(attrs)
|> Ecto.Changeset.cast_assoc(:items, with: &CartItem.changeset/2)
Ecto.Multi.new()
|> Ecto.Multi.update(:cart, changeset)
|> Ecto.Multi.delete_all(:discarded_items, fn %{cart: cart} ->
from(i in CartItem, where: i.cart_id == ^cart.id and i.quantity == 0)
end)
|> Repo.transaction()
|> case do
{:ok, %{cart: cart}} -> {:ok, cart}
{:error, :cart, changeset, _changes_so_far} -> {:error, changeset}
end
end
```
We started much like how our out-of-the-box code started – we take the cart struct and cast the user input to a cart changeset, except this time we use [`Ecto.Changeset.cast_assoc/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#cast_assoc/3) to cast the nested item data into `CartItem` changesets. Remember the [`hidden_inputs_for/1`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Form.html#hidden_inputs_for/1) call in our cart form template? That hidden ID data is what allows Ecto's `cast_assoc` to map item data back to existing item associations in the cart. Next we use [`Ecto.Multi.new/0`](https://hexdocs.pm/ecto/3.8.2/Ecto.Multi.html#new/0), which you may not have seen before. Ecto's `Multi` is a feature that allows lazily defining a chain of named operations to eventually execute inside a database transaction. Each operation in the multi chain receives the values from the previous steps and executes until a failed step is encountered. When an operation fails, the transaction is rolled back and an error is returned, otherwise the transaction is committed.
For our multi operations, we start by issuing an update of our cart, which we named `:cart`. After the cart update is issued, we perform a multi `delete_all` operation, which takes the updated cart and applies our zero-quantity logic. We prune any items in the cart with zero quantity by returning an ecto query that finds all cart items for this cart with an empty quantity. Calling `Repo.transaction/1` with our multi will execute the operations in a new transaction and we return the success or failure result to the caller just like the original function.
Let's head back to the browser and try it out. Add a few products to your cart, update the quantities, and watch the values changes along with the price calculations. Setting any quantity to 0 will also remove the item. Pretty neat!
Adding an Orders context
-------------------------
With our `Catalog` and `ShoppingCart` contexts, we're seeing first-hand how our well-considered modules and function names are yielding clear and maintainable code. Our last order of business is to allow the user to initiate the checkout process. We won't go as far as integrating payment processing or order fulfillment, but we'll get you started in that direction. Like before, we need to decide where code for completing an order should live. Is it part of the catalog? Clearly not, but what about the shopping cart? Shopping carts are related to orders – after all the user has to add items in order to purchase any products, but should the order checkout process be grouped here?
If we stop and consider the order process, we'll see that orders involve related, but distinctly different data from the cart contents. Also, business rules around the checkout process are much different than carting. For example, we may allow a user to add a back-ordered item to their cart, but we could not allow an order with no inventory to be completed. Additionally, we need to capture point-in-time product information when an order is completed, such as the price of the items *at payment transaction time*. This is essential because a product price may change in the future, but the line items in our order must always record and display what we charged at time of purchase. For these reasons, we can start to see ordering can reasonably stand on its own with its own data concerns and business rules.
Naming wise, `Orders` clearly defines the scope of our context, so let's get started by again taking advantage of the context generators. Run the following command in your console:
```
$ mix phx.gen.html Orders Order orders user_uuid:uuid total_price:decimal
* creating lib/hello_web/controllers/order_controller.ex
* creating lib/hello_web/templates/order/edit.html.heex
* creating lib/hello_web/templates/order/form.html.heex
* creating lib/hello_web/templates/order/index.html.heex
* creating lib/hello_web/templates/order/new.html.heex
* creating lib/hello_web/templates/order/show.html.heex
* creating lib/hello_web/views/order_view.ex
* creating test/hello_web/controllers/order_controller_test.exs
* creating lib/hello/orders/order.ex
* creating priv/repo/migrations/20210209214612_create_orders.exs
* creating lib/hello/orders.ex
* injecting lib/hello/orders.ex
* creating test/hello/orders_test.exs
* injecting test/hello/orders_test.exs
* creating test/support/fixtures/orders_fixtures.ex
* injecting test/support/fixtures/orders_fixtures.ex
Add the resource to your browser scope in lib/hello_web/router.ex:
resources "/orders", OrderController
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
We generated a `Orders` context along with HTML controllers, views, etc. We added a `user_uuid` field to associate our placeholder current user to an order, along with a `total_price` column. With our starting point in place, let's open up the newly created migration in `priv/repo/migrations/*_create_orders.exs` and make the following changes:
```
def change do
create table(:orders) do
add :user_uuid, :uuid
- add :total_price, :decimal
+ add :total_price, :decimal, precision: 15, scale: 6, null: false
timestamps()
end
end
```
Like we did previously, we gave appropriate precision and scale options for our decimal column which will allow us to store currency without precision loss. We also added a not-null constraint to enforce all orders to have a price.
The orders table alone doesn't hold much information, but we know we'll need to store point-in-time product price information of all the items in the order. For that, we'll add an additional struct for this context named `LineItem`. Line items will capture the price of the product *at payment transaction time*. Please run the following command:
```
$ mix phx.gen.context Orders LineItem order_line_items \
price:decimal quantity:integer \
order_id:references:orders product_id:references:products
You are generating into an existing context.
Would you like to proceed? [Yn] y
* creating lib/hello/orders/line_item.ex
* creating priv/repo/migrations/20210209215050_create_order_line_items.exs
* injecting lib/hello/orders.ex
* injecting test/hello/orders_test.exs
* injecting test/support/fixtures/orders_fixtures.ex
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
We used the `phx.gen.context` command to generate the `LineItem` Ecto schema and inject supporting functions into our orders context. Like before, let's modify the migration in `priv/repo/migrations/*_create_order_line_items.exs` and make the following decimal field changes:
```
def change do
create table(:order_line_items) do
- add :price, :decimal
+ add :price, :decimal, precision: 15, scale: 6, null: false
add :quantity, :integer
add :order_id, references(:orders, on_delete: :nothing)
add :product_id, references(:products, on_delete: :nothing)
timestamps()
end
create index(:order_line_items, [:order_id])
create index(:order_line_items, [:product_id])
end
```
With our migration in place, let's wire up our orders and line items associations in `lib/hello/orders/order.ex`:
```
schema "orders" do
field :total_price, :decimal
field :user_uuid, Ecto.UUID
+ has_many :line_items, Hello.Orders.LineItem
+ has_many :products, through: [:line_items, :product]
timestamps()
end
```
We used `has_many :line_items` to associate orders and line items, just like we've seen before. Next, we used the `:through` feature of `has_many`, which allows us to instruct ecto how to associate resources across another relationship. In this case, we can associate products of an order by finding all products through associated line items. Next, let's wire up the association in the other direction in `lib/hello/orders/line_item.ex`:
```
schema "order_line_items" do
field :price, :decimal
field :quantity, :integer
- field :order_id, :id
- field :product_id, :id
+ belongs_to :order, Hello.Orders.Order
+ belongs_to :product, Hello.Catalog.Product
timestamps()
end
```
We used `belongs_to` to associate line items to orders and products. With our associations in place, we can start integrating the web interface into our order process. Open up your router `lib/hello_web/router.ex` and add the following line:
```
scope "/", HelloWeb do
pipe_through :browser
...
+ resources "/orders", OrderController, only: [:create, :show]
end
```
We wired up `create` and `show` routes for our generated `OrderController`, since these are the only actions we need at the moment. With our routes in place, we can now migrate up:
```
$ mix ecto.migrate
17:14:37.715 [info] == Running 20210209214612 Hello.Repo.Migrations.CreateOrders.change/0 forward
17:14:37.720 [info] create table orders
17:14:37.755 [info] == Migrated 20210209214612 in 0.0s
17:14:37.784 [info] == Running 20210209215050 Hello.Repo.Migrations.CreateOrderLineItems.change/0 forward
17:14:37.785 [info] create table order_line_items
17:14:37.795 [info] create index order_line_items_order_id_index
17:14:37.796 [info] create index order_line_items_product_id_index
17:14:37.798 [info] == Migrated 20210209215050 in 0.0s
```
Before we render information about our orders, we need to ensure our order data is fully populated and can be looked up by a current user. Open up your orders context in `lib/hello/orders.ex` and replace your `get_order!/1` function by a new `get_order!/2` definition:
```
def get_order!(user_uuid, id) do
Order
|> Repo.get_by!(id: id, user_uuid: user_uuid)
|> Repo.preload([line_items: [:product]])
end
```
We rewrote the function to accept a user UUID and query our repo for an order matching the user's ID for a given order ID. Then we populated the order by preloading our line item and product associations.
To complete an order, our cart page can issue a POST to the `OrderController.create` action, but we need to implement the operations and logic to actually complete an order. Like before, we'll start at the web interface by rewriting the create function in `lib/hello_web/controllers/order_controller.ex`:
```
def create(conn, _) do
case Orders.complete_order(conn.assigns.cart) do
{:ok, order} ->
conn
|> put_flash(:info, "Order created successfully.")
|> redirect(to: Routes.order_path(conn, :show, order))
{:error, _reason} ->
conn
|> put_flash(:error, "There was an error processing your order")
|> redirect(to: Routes.cart_path(conn, :show))
end
end
```
We rewrote the `create` action to call an as-yet-implemented `Orders.complete_order/1` function. The code that phoenix generated had a generic `Orders.create_order/1` call. Our code is technically "creating" an order, but it's important to step back and consider the naming of your interfaces. The act of *completing* an order is extremely important in our system. Money changes hands in a transaction, physical goods could be automatically shipped, etc. Such an operation deserves a better, more obvious function name, such as `complete_order`. If the order is completed successfully we redirect to the show page, otherwise a flash error is shown as we redirect back to the cart page.
Now we can implement our `Orders.complete_order/1` function. To complete an order, our job will require a few operations:
1. A new order record must be persisted with the total price of the order
2. All items in the cart must be transformed into new order line items records with quantity and point-in-time product price information
3. After successful order insert (and eventual payment), items must be pruned from the cart
From our requirements alone, we can start to see why a generic `create_order` function doesn't cut it. Let's implement this new function in `lib/hello/orders.ex`:
```
alias Hello.ShoppingCart
alias Hello.Orders.LineItem
def complete_order(%ShoppingCart.Cart{} = cart) do
line_items =
Enum.map(cart.items, fn item ->
%{product_id: item.product_id, price: item.product.price, quantity: item.quantity}
end)
order =
Ecto.Changeset.change(%Order{},
user_uuid: cart.user_uuid,
total_price: ShoppingCart.total_cart_price(cart),
line_items: line_items
)
Ecto.Multi.new()
|> Ecto.Multi.insert(:order, order)
|> Ecto.Multi.run(:prune_cart, fn _repo, _changes ->
ShoppingCart.prune_cart_items(cart)
end)
|> Repo.transaction()
|> case do
{:ok, %{order: order}} -> {:ok, order}
{:error, name, value, _changes_so_far} -> {:error, {name, value}}
end
end
```
We started by mapping the `%ShoppingCart.CartItem{}`'s in our shopping cart into a map of order line items structs. The job of the order line item record is to capture the price of the product *at payment transaction time*, so we reference the product's price here. Next, we create a bare order changeset with [`Ecto.Changeset.change/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#change/2) and associate our user UUID, set our total price calculation, and place our order line items in the changeset. With a fresh order changeset ready to be inserted, we can again make use of [`Ecto.Multi`](https://hexdocs.pm/ecto/3.8.2/Ecto.Multi.html) to execute our operations in a database transaction. We start by inserting the order, followed by a `run` operation. The [`Ecto.Multi.run/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Multi.html#run/3) function allows us to run any code in the function which must either succeed with `{:ok, result}` or error, which halts and rolls back the transaction. Here, we simply can call into our shopping cart context and ask it to prune all items in a cart. Running the transaction will execute the multi as before and we return the result to the caller.
To close out our order completion, we need to implement the `ShoppingCart.prune_cart_items/1` function in `lib/hello/shopping_cart.ex`:
```
def prune_cart_items(%Cart{} = cart) do
{_, _} = Repo.delete_all(from(i in CartItem, where: i.cart_id == ^cart.id))
{:ok, reload_cart(cart)}
end
```
Our new function accepts the cart struct and issues a `Repo.delete_all` which accepts a query of all items for the provided cart. We return a success result by simply reloading the pruned cart to the caller. With our context complete, we now need to show the user their completed order. Head back to your order controller and modify the `show/2` action:
```
def show(conn, %{"id" => id}) do
- order = Orders.get_order!(id)
+ order = Orders.get_order!(conn.assigns.current_uuid, id)
render(conn, "show.html", order: order)
end
```
We tweaked the show action to pass our `conn.assigns.current_uuid` to `get_order!` which authorizes orders to be viewable only by the owner of the order. Next, we can replace the order show template in `lib/hello_web/templates/order/show.html.heex`:
```
<h1>Thank you for your order!</h1>
<ul>
<li>
<strong>User uuid:</strong>
<%= @order.user_uuid %>
</li>
<%= for item <- @order.line_items do %>
<li>
<%= item.product.title %>
(<%= item.quantity %>) - <%= HelloWeb.CartView.currency_to_str(item.price) %>
</li>
<% end %>
<li>
<strong>Total price:</strong>
<%= HelloWeb.CartView.currency_to_str(@order.total_price) %>
</li>
</ul>
<span><%= link "Back", to: Routes.cart_path(@conn, :show) %></span>
```
To show our completed order, we displayed the order's user, followed by the line item listing with product title, quantity, and the price we "transacted" when completing the order, along with the total price.
Our last addition will be to add the "complete order" button to our cart page to allow completing an order. Add the following button to the bottom of the cart show template in `lib/hello_web/templates/cart/show.html.heex`:
```
<b>Total</b>: <%= currency_to_str(ShoppingCart.total_cart_price(@cart)) %>
+ <%= link "complete order", to: Routes.order_path(@conn, :create), method: :post %>
<% end %>
```
We added a link with `method: :post` to send a POST request to our `OrderController.create` action. If we head back to our cart page at [`http://localhost:4000/cart`](http://localhost:4000/cart) and complete an order, we'll be greeted by our rendered template:
```
Thank you for your order!
User uuid: 08964c7c-908c-4a55-bcd3-9811ad8b0b9d
Metaprogramming Elixir (2) - $15.00
Total price: $30.00
```
Nice work! We haven't added payments, but we can already see how our `ShoppingCart` and `Orders` context splitting is driving us towards a maintainable solution. With our cart items separated from our order line items, we are well equipped in the future to add payment transactions, cart price detection, and more.
Great work!
FAQ
----
### Returning Ecto structures from context APIs
As we explored the context API, you might have wondered:
> If one of the goals of our context is to encapsulate Ecto Repo access, why does `create_user/1` return an [`Ecto.Changeset`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html) struct when we fail to create a user?
>
>
Although Changesets are part of Ecto, they are not tied to the database, and they can be used to map data from and to any source, which makes it a general and useful data structure for tracking field changes, perform validations, and generate error messages.
For those reasons, `%Ecto.Changeset{}` is a good choice to model the data changes between your contexts and your web layer. Regardless if you are talking to an API or the database.
Finally, note that your controllers and views are not hardcoded to work exclusively with Ecto either. Instead, Phoenix defines protocols such as [`Phoenix.Param`](phoenix.param) and [`Phoenix.HTML.FormData`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.FormData.html), which allow any library to extend how Phoenix generates URL parameters or renders forms. Conveniently for us, the `phoenix_ecto` project implements those protocols, but you could as well bring your own data structures and implement them yourself.
[← Previous Page Ecto](ecto) [Next Page → Mix tasks](mix_tasks)
| programming_docs |
phoenix Up and Running Up and Running
===============
Let's get a Phoenix application up and running as quickly as possible.
Before we begin, please take a minute to read the [Installation Guide](installation). By installing any necessary dependencies beforehand, we'll be able to get our application up and running smoothly.
We can run [`mix phx.new`](mix.tasks.phx.new) from any directory in order to bootstrap our Phoenix application. Phoenix will accept either an absolute or relative path for the directory of our new project. Assuming that the name of our application is `hello`, let's run the following command:
```
$ mix phx.new hello
```
> A note about [Ecto](ecto): Ecto allows our Phoenix application to communicate with a data store, such as PostgreSQL, MySQL, and others. If our application will not require this component we can skip this dependency by passing the `--no-ecto` flag to [`mix phx.new`](mix.tasks.phx.new).
>
>
> To learn more about [`mix phx.new`](mix.tasks.phx.new) you can read the [Mix Tasks Guide](mix_tasks#phoenix-specific-mix-tasks).
>
>
```
mix phx.new hello
* creating hello/config/config.exs
* creating hello/config/dev.exs
* creating hello/config/prod.exs
...
Fetch and install dependencies? [Yn]
```
Phoenix generates the directory structure and all the files we will need for our application.
> Phoenix promotes the usage of git as version control software: among the generated files we find a `.gitignore`. We can `git init` our repository, and immediately add and commit all that hasn't been marked ignored.
>
>
When it's done, it will ask us if we want it to install our dependencies for us. Let's say yes to that.
```
Fetch and install dependencies? [Yn] Y
* running mix deps.get
* running mix deps.compile
We are almost there! The following steps are missing:
$ cd hello
Then configure your database in config/dev.exs and run:
$ mix ecto.create
Start your Phoenix app with:
$ mix phx.server
You can also run your app inside IEx (Interactive Elixir) as:
$ iex -S mix phx.server
```
Once our dependencies are installed, the task will prompt us to change into our project directory and start our application.
Phoenix assumes that our PostgreSQL database will have a `postgres` user account with the correct permissions and a password of "postgres". If that isn't the case, please see the [Mix Tasks Guide](mix_tasks#ecto-specific-mix-tasks) to learn more about the [`mix ecto.create`](https://hexdocs.pm/ecto/3.8.2/Mix.Tasks.Ecto.Create.html) task.
Ok, let's give it a try. First, we'll `cd` into the `hello/` directory we've just created:
```
$ cd hello
```
Now we'll create our database:
```
$ mix ecto.create
Compiling 13 files (.ex)
Generated hello app
The database for Hello.Repo has been created
```
In case the database could not be created, see the guides for the [`mix ecto.create`](mix_tasks#mix-ecto-create) for general troubleshooting.
> Note: if this is the first time you are running this command, Phoenix may also ask to install Rebar. Go ahead with the installation as Rebar is used to build Erlang packages.
>
>
And finally, we'll start the Phoenix server:
```
$ mix phx.server
[info] Running HelloWeb.Endpoint with cowboy 2.9.0 at 127.0.0.1:4000 (http)
[info] Access HelloWeb.Endpoint at http://localhost:4000
[watch] build finished, watching for changes...
...
```
If we choose not to have Phoenix install our dependencies when we generate a new application, the [`mix phx.new`](mix.tasks.phx.new) task will prompt us to take the necessary steps when we do want to install them.
```
Fetch and install dependencies? [Yn] n
We are almost there! The following steps are missing:
$ cd hello
$ mix deps.get
Then configure your database in config/dev.exs and run:
$ mix ecto.create
Start your Phoenix app with:
$ mix phx.server
You can also run your app inside IEx (Interactive Elixir) as:
$ iex -S mix phx.server
```
By default, Phoenix accepts requests on port 4000. If we point our favorite web browser at <http://localhost:4000>, we should see the Phoenix Framework welcome page.
If your screen looks like the image above, congratulations! You now have a working Phoenix application. In case you can't see the page above, try accessing it via <http://127.0.0.1:4000> and later make sure your OS has defined "localhost" as "127.0.0.1".
To stop it, we hit `ctrl-c` twice.
Now you are ready to explore the world provided by Phoenix! See [our community page](community) for books, screencasts, courses, and more.
Alternatively, you can continue reading these guides to have a quick introduction into all the parts that make your Phoenix application. If that's the case, you can read the guides in any order or start with our guide that explains the [Phoenix directory structure](directory_structure).
[← Previous Page Installation](installation) [Next Page → Community](community)
phoenix Phoenix.ActionClauseError exception Phoenix.ActionClauseError exception
====================================
Summary
========
Functions
----------
[blame(exception, stacktrace)](#blame/2) Callback implementation for [`Exception.blame/2`](https://hexdocs.pm/elixir/Exception.html#c:blame/2).
[message(exception)](#message/1) Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
Functions
==========
### blame(exception, stacktrace)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/exceptions.ex#L55)
Callback implementation for [`Exception.blame/2`](https://hexdocs.pm/elixir/Exception.html#c:blame/2).
### message(exception)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/exceptions.ex#L49)
Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
phoenix Overview Overview
=========
Phoenix is a web development framework written in Elixir which implements the server-side Model View Controller (MVC) pattern. Many of its components and concepts will seem familiar to those of us with experience in other web frameworks like Ruby on Rails or Python's Django.
Phoenix provides the best of both worlds - high developer productivity *and* high application performance. It also has some interesting new twists like channels for implementing realtime features and pre-compiled templates for blazing speed.
If you are already familiar with Elixir, great! If not, there are a number of places to learn. The [Elixir guides](https://elixir-lang.org/getting-started/introduction.html) and the [Elixir learning resources page](https://elixir-lang.org/learning.html) are two great places to start.
The guides that you are currently looking at provide an overview of all parts that make Phoenix. Here is a rundown of what they provide:
* Introduction - the guides you are currently reading. They will cover how to get your first application up and running
* Guides - in-depth guides covering the main components in Phoenix and Phoenix applications
* Authentication - in-depth guide covering how to use [`mix phx.gen.auth`](mix.tasks.phx.gen.auth)
* Real-time components - in-depth guides covering Phoenix's built-in real-time components
* Testing - in-depth guides about testing
* Deployment - in-depth guides about deployment
* How-to's - a collection of articles on how to achieve certain things with Phoenix
If you would prefer to read these guides as an EPUB, [click here!](phoenix.epub)
Note, these guides are not a step-by-step introduction to Phoenix. If you want a more structured approach to learning the framework, we have a large community and many books, courses, and screencasts available. See [our community page](community) for a complete list.
[Let's get Phoenix installed](installation).
[← Previous Page Changelog for v1.6](changelog) [Next Page → Installation](installation)
phoenix mix phx.gen.notifier mix phx.gen.notifier
=====================
Generates a notifier that delivers emails by default.
```
$ mix phx.gen.notifier Accounts User welcome_user reset_password confirmation_instructions
```
This task expects a context module name, followed by a notifier name and one or more message names. Messages are the functions that will be created prefixed by "deliver", so the message name should be "snake\_case" without punctuation.
Additionally a context app can be specified with the flag `--context-app`, which is useful if the notifier is being generated in a different app under an umbrella.
```
$ mix phx.gen.notifier Accounts User welcome_user --context-app marketing
```
The app "marketing" must exist before the command is executed.
phoenix Phoenix.MissingParamError exception Phoenix.MissingParamError exception
====================================
Raised when a key is expected to be present in the request parameters, but is not.
This exception is raised by [`Phoenix.Controller.scrub_params/2`](phoenix.controller#scrub_params/2) which:
* Checks to see if the required\_key is present (can be empty)
* Changes all empty parameters to nils ("" -> nil)
If you are seeing this error, you should handle the error and surface it to the end user. It means that there is a parameter missing from the request.
phoenix Phoenix.ConnTest Phoenix.ConnTest
=================
Conveniences for testing Phoenix endpoints and connection related helpers.
You likely want to use this module or make it part of your [`ExUnit.CaseTemplate`](https://hexdocs.pm/ex_unit/ExUnit.CaseTemplate.html). Once used, this module automatically imports all functions defined here as well as the functions in [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html).
Endpoint testing
-----------------
[`Phoenix.ConnTest`](phoenix.conntest#content) typically works against endpoints. That's the preferred way to test anything that your router dispatches to:
```
@endpoint MyAppWeb.Endpoint
test "says welcome on the home page" do
conn = get(build_conn(), "/")
assert conn.resp_body =~ "Welcome!"
end
test "logs in" do
conn = post(build_conn(), "/login", [username: "john", password: "doe"])
assert conn.resp_body =~ "Logged in!"
end
```
The `@endpoint` module attribute contains the endpoint under testing, most commonly your application endpoint itself. If you are using the MyApp.ConnCase generated by Phoenix, it is automatically set for you.
As in your router and controllers, the connection is the main abstraction in testing. `build_conn()` returns a new connection and functions in this module can be used to manipulate the connection before dispatching to the endpoint.
For example, one could set the accepts header for json requests as follows:
```
build_conn()
|> put_req_header("accept", "application/json")
|> get("/")
```
You can also create your own helpers, such as `json_conn()` that uses [`build_conn/0`](#build_conn/0) and `put_req_header/3`, so you avoid repeating the connection setup throughout your tests.
Controller testing
-------------------
The functions in this module can also be used for controller testing. While endpoint testing is preferred over controller testing, especially since the controller in Phoenix plays an integration role between your domain and your views, unit testing controllers may be helpful in some situations.
For such cases, you need to set the `@endpoint` attribute to your controller and pass an atom representing the action to dispatch:
```
@endpoint MyAppWeb.HomeController
test "says welcome on the home page" do
conn = get(build_conn(), :index)
assert conn.resp_body =~ "Welcome!"
end
```
Keep in mind that, once the `@endpoint` variable is set, all tests after setting it will be affected.
Views testing
--------------
Under other circumstances, you may be testing a view or another layer that requires a connection for processing. For such cases, a connection can be created using the [`build_conn/3`](#build_conn/3) helper:
```
MyApp.UserView.render("hello.html", conn: build_conn(:get, "/"))
```
While [`build_conn/0`](#build_conn/0) returns a connection with no request information to it, [`build_conn/3`](#build_conn/3) returns a connection with the given request information already filled in.
Recycling
----------
Browsers implement a storage by using cookies. When a cookie is set in the response, the browser stores it and sends it in the next request.
To emulate this behaviour, this module provides the idea of recycling. The [`recycle/1`](#recycle/1) function receives a connection and returns a new connection, similar to the one returned by [`build_conn/0`](#build_conn/0) with all the response cookies from the previous connection defined as request headers. This is useful when testing multiple routes that require cookies or session to work.
Keep in mind Phoenix will automatically recycle the connection between dispatches. This usually works out well most times, but it may discard information if you are modifying the connection before the next dispatch:
```
# No recycling as the connection is fresh
conn = get(build_conn(), "/")
# The connection is recycled, creating a new one behind the scenes
conn = post(conn, "/login")
# We can also recycle manually in case we want custom headers
conn =
conn
|> recycle()
|> put_req_header("x-special", "nice")
# No recycling as we did it explicitly
conn = delete(conn, "/logout")
```
Recycling also recycles the "accept" and "authorization" headers, as well as peer data information.
Summary
========
Functions
----------
[assert\_error\_sent(status\_int\_or\_atom, func)](#assert_error_sent/2) Asserts an error was wrapped and sent with the given status.
[build\_conn()](#build_conn/0) Creates a connection to be used in upcoming requests.
[build\_conn(method, path, params\_or\_body \\ nil)](#build_conn/3) Creates a connection to be used in upcoming requests with a preset method, path and body.
[bypass\_through(conn)](#bypass_through/1) Calls the Endpoint and Router pipelines.
[bypass\_through(conn, router)](#bypass_through/2) Calls the Endpoint and Router pipelines for the current route.
[bypass\_through(conn, router, pipelines)](#bypass_through/3) Calls the Endpoint and the given Router pipelines.
[clear\_flash(conn)](#clear_flash/1) Clears up the flash storage.
[connect(conn, path\_or\_action, params\_or\_body \\ nil)](#connect/3) Dispatches to the current endpoint.
[delete(conn, path\_or\_action, params\_or\_body \\ nil)](#delete/3) Dispatches to the current endpoint.
[delete\_req\_cookie(conn, key)](#delete_req_cookie/2) Deletes a request cookie.
[dispatch(conn, endpoint, method, path\_or\_action, params\_or\_body \\ nil)](#dispatch/5) Dispatches the connection to the given endpoint.
[ensure\_recycled(conn)](#ensure_recycled/1) Ensures the connection is recycled if it wasn't already.
[fetch\_flash(conn)](#fetch_flash/1) Fetches the flash storage.
[get(conn, path\_or\_action, params\_or\_body \\ nil)](#get/3) Dispatches to the current endpoint.
[get\_flash(conn)](#get_flash/1) Gets the whole flash storage.
[get\_flash(conn, key)](#get_flash/2) Gets the given key from the flash storage.
[head(conn, path\_or\_action, params\_or\_body \\ nil)](#head/3) Dispatches to the current endpoint.
[html\_response(conn, status)](#html_response/2) Asserts the given status code, that we have an html response and returns the response body if one was set or sent.
[init\_test\_session(conn, session)](#init_test_session/2) Inits a session used exclusively for testing.
[json\_response(conn, status)](#json_response/2) Asserts the given status code, that we have a json response and returns the decoded JSON response if one was set or sent.
[options(conn, path\_or\_action, params\_or\_body \\ nil)](#options/3) Dispatches to the current endpoint.
[patch(conn, path\_or\_action, params\_or\_body \\ nil)](#patch/3) Dispatches to the current endpoint.
[path\_params(conn, to)](#path_params/2) Returns the matched params of the URL for the `%Plug.Conn{}`'s router.
[post(conn, path\_or\_action, params\_or\_body \\ nil)](#post/3) Dispatches to the current endpoint.
[put(conn, path\_or\_action, params\_or\_body \\ nil)](#put/3) Dispatches to the current endpoint.
[put\_flash(conn, key, value)](#put_flash/3) Puts the given value under key in the flash storage.
[put\_req\_cookie(conn, key, value)](#put_req_cookie/3) Puts a request cookie.
[recycle(conn, headers \\ ~w(accept accept-language authorization))](#recycle/2) Recycles the connection.
[redirected\_params(conn)](#redirected_params/1) Returns the matched params from the URL the connection was redirected to.
[redirected\_to(conn, status \\ 302)](#redirected_to/2) Returns the location header from the given redirect response.
[response(conn, given)](#response/2) Asserts the given status code and returns the response body if one was set or sent.
[response\_content\_type(conn, format)](#response_content_type/2) Returns the content type as long as it matches the given format.
[text\_response(conn, status)](#text_response/2) Asserts the given status code, that we have a text response and returns the response body if one was set or sent.
[trace(conn, path\_or\_action, params\_or\_body \\ nil)](#trace/3) Dispatches to the current endpoint.
Functions
==========
### assert\_error\_sent(status\_int\_or\_atom, func)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L645)
```
@spec assert_error_sent(integer() | atom(), function()) :: {integer(), list(), term()}
```
Asserts an error was wrapped and sent with the given status.
Useful for testing actions that you expect raise an error and have the response wrapped in an HTTP status, with content usually rendered by your MyApp.ErrorView.
The function accepts a status either as an integer HTTP status or atom, such as `404` or `:not_found`. The list of allowed atoms is available in [`Plug.Conn.Status`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.Status.html). If an error is raised, a 3-tuple of the wrapped response is returned matching the status, headers, and body of the response:
```
{404, [{"content-type", "text/html"} | _], "Page not found"}
```
#### Examples
```
assert_error_sent :not_found, fn ->
get(build_conn(), "/users/not-found")
end
response = assert_error_sent 404, fn ->
get(build_conn(), "/users/not-found")
end
assert {404, [_h | _t], "Page not found"} = response
```
### build\_conn()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L139)
```
@spec build_conn() :: Plug.Conn.t()
```
Creates a connection to be used in upcoming requests.
### build\_conn(method, path, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L151)
```
@spec build_conn(atom() | binary(), binary(), binary() | list() | map() | nil) ::
Plug.Conn.t()
```
Creates a connection to be used in upcoming requests with a preset method, path and body.
This is useful when a specific connection is required for testing a plug or a particular function.
### bypass\_through(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L547)
```
@spec bypass_through(Plug.Conn.t()) :: Plug.Conn.t()
```
Calls the Endpoint and Router pipelines.
Useful for unit testing Plugs where Endpoint and/or router pipeline plugs are required for proper setup.
Note the use of `get("/")` following `bypass_through` in the examples below. To execute the plug pipelines, you must issue a request against the router. Most often, you can simply send a GET request against the root path, but you may also specify a different method or path which your pipelines may operate against.
#### Examples
For example, imagine you are testing an authentication plug in isolation, but you need to invoke the Endpoint plugs and router pipelines to set up session and flash related dependencies. One option is to invoke an existing route that uses the proper pipelines. You can do so by passing the connection and the router name to `bypass_through`:
```
conn =
conn
|> bypass_through(MyAppWeb.Router)
|> get("/some_url")
|> MyApp.RequireAuthentication.call([])
assert conn.halted
```
You can also specify which pipelines you want to run:
```
conn =
conn
|> bypass_through(MyAppWeb.Router, [:browser])
|> get("/")
|> MyApp.RequireAuthentication.call([])
assert conn.halted
```
Alternatively, you could only invoke the Endpoint's plugs:
```
conn =
conn
|> bypass_through()
|> get("/")
|> MyApp.RequireAuthentication.call([])
assert conn.halted
```
### bypass\_through(conn, router)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L557)
```
@spec bypass_through(Plug.Conn.t(), module()) :: Plug.Conn.t()
```
Calls the Endpoint and Router pipelines for the current route.
See [`bypass_through/1`](#bypass_through/1).
### bypass\_through(conn, router, pipelines)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L567)
```
@spec bypass_through(Plug.Conn.t(), module(), atom() | list()) :: Plug.Conn.t()
```
Calls the Endpoint and the given Router pipelines.
See [`bypass_through/1`](#bypass_through/1).
### clear\_flash(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L295)
```
@spec clear_flash(Plug.Conn.t()) :: Plug.Conn.t()
```
Clears up the flash storage.
### connect(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### delete(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### delete\_req\_cookie(conn, key)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L265)
```
@spec delete_req_cookie(Plug.Conn.t(), binary()) :: Plug.Conn.t()
```
Deletes a request cookie.
### dispatch(conn, endpoint, method, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L212)
Dispatches the connection to the given endpoint.
When invoked via [`get/3`](#get/3), [`post/3`](#post/3) and friends, the endpoint is automatically retrieved from the `@endpoint` module attribute, otherwise it must be given as an argument.
The connection will be configured with the given `method`, `path_or_action` and `params_or_body`.
If `path_or_action` is a string, it is considered to be the request path and stored as so in the connection. If an atom, it is assumed to be an action and the connection is dispatched to the given action.
#### Parameters and body
This function, as well as [`get/3`](#get/3), [`post/3`](#post/3) and friends, accepts the request body or parameters as last argument:
```
get(build_conn(), "/", some: "param")
get(build_conn(), "/", "some=param&url=encoded")
```
The allowed values are:
* `nil` - meaning there is no body
* a binary - containing a request body. For such cases, `:headers` must be given as option with a content-type
* a map or list - containing the parameters which will automatically set the content-type to multipart. The map or list may contain other lists or maps and all entries will be normalized to string keys
* a struct - unlike other maps, a struct will be passed through as-is without normalizing its entries
### ensure\_recycled(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L491)
```
@spec ensure_recycled(Plug.Conn.t()) :: Plug.Conn.t()
```
Ensures the connection is recycled if it wasn't already.
See [`recycle/1`](#recycle/1) for more information.
### fetch\_flash(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L271)
```
@spec fetch_flash(Plug.Conn.t()) :: Plug.Conn.t()
```
Fetches the flash storage.
### get(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### get\_flash(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L277)
```
@spec get_flash(Plug.Conn.t()) :: map()
```
Gets the whole flash storage.
### get\_flash(conn, key)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L283)
```
@spec get_flash(Plug.Conn.t(), term()) :: term()
```
Gets the given key from the flash storage.
### head(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### html\_response(conn, status)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L382)
```
@spec html_response(Plug.Conn.t(), status :: integer() | atom()) ::
String.t() | no_return()
```
Asserts the given status code, that we have an html response and returns the response body if one was set or sent.
#### Examples
```
assert html_response(conn, 200) =~ "<html>"
```
### init\_test\_session(conn, session)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L253)
```
@spec init_test_session(Plug.Conn.t(), map() | keyword()) :: Plug.Conn.t()
```
Inits a session used exclusively for testing.
### json\_response(conn, status)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L414)
```
@spec json_response(Plug.Conn.t(), status :: integer() | atom()) ::
map() | no_return()
```
Asserts the given status code, that we have a json response and returns the decoded JSON response if one was set or sent.
#### Examples
```
body = json_response(conn, 200)
assert "can't be blank" in body["errors"]
```
### options(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### patch(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### path\_params(conn, to)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L607)
```
@spec path_params(Plug.Conn.t(), String.t()) :: map()
```
Returns the matched params of the URL for the `%Plug.Conn{}`'s router.
Useful for extracting path params out of returned URLs, such as those returned by `Phoenix.LiveViewTest`'s redirected results.
#### Examples
```
assert {:error, {:redirect, %{to: "/posts/123" = to}}} = live(conn, "/path")
assert %{id: "123"} = path_params(conn, to)
```
### post(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### put(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
### put\_flash(conn, key, value)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L289)
```
@spec put_flash(Plug.Conn.t(), term(), term()) :: Plug.Conn.t()
```
Puts the given value under key in the flash storage.
### put\_req\_cookie(conn, key, value)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L259)
```
@spec put_req_cookie(Plug.Conn.t(), binary(), binary()) :: Plug.Conn.t()
```
Puts a request cookie.
### recycle(conn, headers \\ ~w(accept accept-language authorization))[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L472)
```
@spec recycle(Plug.Conn.t(), [String.t()]) :: Plug.Conn.t()
```
Recycles the connection.
Recycling receives a connection and returns a new connection, containing cookies and relevant information from the given one.
This emulates behaviour performed by browsers where cookies returned in the response are available in following requests.
By default, only the headers "accept", "accept-language", and "authorization" are recycled. However, a custom set of headers can be specified by passing a list of strings representing its names as the second argument of the function.
Note [`recycle/1`](#recycle/1) is automatically invoked when dispatching to the endpoint, unless the connection has already been recycled.
### redirected\_params(conn)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L583)
```
@spec redirected_params(Plug.Conn.t()) :: map()
```
Returns the matched params from the URL the connection was redirected to.
Uses the provided `%Plug.Conn{}`s router matched in the previous request. Raises if the response's location header is not set.
#### Examples
```
assert redirected_to(conn) =~ "/posts/123"
assert %{id: "123"} = redirected_params(conn)
```
### redirected\_to(conn, status \\ 302)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L434)
```
@spec redirected_to(Plug.Conn.t(), status :: non_neg_integer()) :: String.t()
```
Returns the location header from the given redirect response.
Raises if the response does not match the redirect status code (defaults to 302).
#### Examples
```
assert redirected_to(conn) =~ "/foo/bar"
assert redirected_to(conn, 301) =~ "/foo/bar"
assert redirected_to(conn, :moved_permanently) =~ "/foo/bar"
```
### response(conn, given)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L353)
```
@spec response(Plug.Conn.t(), status :: integer() | atom()) :: binary() | no_return()
```
Asserts the given status code and returns the response body if one was set or sent.
#### Examples
```
conn = get(build_conn(), "/")
assert response(conn, 200) =~ "hello world"
```
### response\_content\_type(conn, format)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L307)
```
@spec response_content_type(Plug.Conn.t(), atom()) :: String.t() | no_return()
```
Returns the content type as long as it matches the given format.
#### Examples
```
# Assert we have an html response with utf-8 charset
assert response_content_type(conn, :html) =~ "charset=utf-8"
```
### text\_response(conn, status)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L397)
```
@spec text_response(Plug.Conn.t(), status :: integer() | atom()) ::
String.t() | no_return()
```
Asserts the given status code, that we have a text response and returns the response body if one was set or sent.
#### Examples
```
assert text_response(conn, 200) =~ "hello"
```
### trace(conn, path\_or\_action, params\_or\_body \\ nil)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/conn_test.ex#L165)
Dispatches to the current endpoint.
See [`dispatch/5`](#dispatch/5) for more information.
| programming_docs |
phoenix Phoenix.Endpoint behaviour Phoenix.Endpoint behaviour
===========================
Defines a Phoenix endpoint.
The endpoint is the boundary where all requests to your web application start. It is also the interface your application provides to the underlying web servers.
Overall, an endpoint has three responsibilities:
* to provide a wrapper for starting and stopping the endpoint as part of a supervision tree
* to define an initial plug pipeline for requests to pass through
* to host web specific configuration for your application
Endpoints
----------
An endpoint is simply a module defined with the help of [`Phoenix.Endpoint`](phoenix.endpoint#content). If you have used the [`mix phx.new`](mix.tasks.phx.new) generator, an endpoint was automatically generated as part of your application:
```
defmodule YourAppWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :your_app
# plug ...
# plug ...
plug YourApp.Router
end
```
Endpoints must be explicitly started as part of your application supervision tree. Endpoints are added by default to the supervision tree in generated applications. Endpoints can be added to the supervision tree as follows:
```
children = [
YourAppWeb.Endpoint
]
```
Endpoint configuration
-----------------------
All endpoints are configured in your application environment. For example:
```
config :your_app, YourAppWeb.Endpoint,
secret_key_base: "kjoy3o1zeidquwy1398juxzldjlksahdk3"
```
Endpoint configuration is split into two categories. Compile-time configuration means the configuration is read during compilation and changing it at runtime has no effect. The compile-time configuration is mostly related to error handling.
Runtime configuration, instead, is accessed during or after your application is started and can be read through the [`config/2`](#c:config/2) function:
```
YourAppWeb.Endpoint.config(:port)
YourAppWeb.Endpoint.config(:some_config, :default_value)
```
### Dynamic configuration
For dynamically configuring the endpoint, such as loading data from environment variables or configuration files, Phoenix invokes the [`init/2`](#c:init/2) callback on the endpoint, passing the atom `:supervisor` as the first argument and the endpoint configuration as second.
All of Phoenix configuration, except the Compile-time configuration below can be set dynamically from the [`init/2`](#c:init/2) callback.
### Compile-time configuration
* `:code_reloader` - when `true`, enables code reloading functionality. For the list of code reloader configuration options see [`Phoenix.CodeReloader.reload/1`](phoenix.codereloader#reload/1). Keep in mind code reloading is based on the file-system, therefore it is not possible to run two instances of the same app at the same time with code reloading in development, as they will race each other and only one will effectively recompile the files. In such cases, tweak your config files so code reloading is enabled in only one of the apps or set the MIX\_BUILD environment variable to give them distinct build directories
* `:debug_errors` - when `true`, uses [`Plug.Debugger`](https://hexdocs.pm/plug/1.13.6/Plug.Debugger.html) functionality for debugging failures in the application. Recommended to be set to `true` only in development as it allows listing of the application source code during debugging. Defaults to `false`
* `:force_ssl` - ensures no data is ever sent via HTTP, always redirecting to HTTPS. It expects a list of options which are forwarded to [`Plug.SSL`](https://hexdocs.pm/plug/1.13.6/Plug.SSL.html). By default it sets the "strict-transport-security" header in HTTPS requests, forcing browsers to always use HTTPS. If an unsafe request (HTTP) is sent, it redirects to the HTTPS version using the `:host` specified in the `:url` configuration. To dynamically redirect to the `host` of the current request, set `:host` in the `:force_ssl` configuration to `nil`
### Runtime configuration
* `:adapter` - which webserver adapter to use for serving web requests. See the "Adapter configuration" section below
* `:cache_static_manifest` - a path to a json manifest file that contains static files and their digested version. This is typically set to "priv/static/cache\_manifest.json" which is the file automatically generated by [`mix phx.digest`](mix.tasks.phx.digest). It can be either: a string containing a file system path or a tuple containing the application name and the path within that application.
* `:cache_static_manifest_latest` - a map of the static files pointing to their digest version. This is automatically loaded from `cache_static_manifest` on boot. However, if you have your own static handling mechanism, you may want to set this value explicitly. This is used by projects such as `LiveView` to detect if the client is running on the latest version of all assets.
* `:cache_manifest_skip_vsn` - when true, skips the appended query string "?vsn=d" when generatic paths to static assets. This query string is used by [`Plug.Static`](https://hexdocs.pm/plug/1.13.6/Plug.Static.html) to set long expiry dates, therefore, you should set this option to true only if you are not using [`Plug.Static`](https://hexdocs.pm/plug/1.13.6/Plug.Static.html) to serve assets, for example, if you are using a CDN. If you are setting this option, you should also consider passing `--no-vsn` to [`mix phx.digest`](mix.tasks.phx.digest). Defaults to `false`.
* `:check_origin` - configure the default `:check_origin` setting for transports. See [`socket/3`](#socket/3) for options. Defaults to `true`.
* `:secret_key_base` - a secret key used as a base to generate secrets for encrypting and signing data. For example, cookies and tokens are signed by default, but they may also be encrypted if desired. Defaults to `nil` as it must be set per application
* `:server` - when `true`, starts the web server when the endpoint supervision tree starts. Defaults to `false`. The [`mix phx.server`](mix.tasks.phx.server) task automatically sets this to `true`
* `:url` - configuration for generating URLs throughout the app. Accepts the `:host`, `:scheme`, `:path` and `:port` options. All keys except `:path` can be changed at runtime. Defaults to:
```
[host: "localhost", path: "/"]
```
The `:port` option requires either an integer or string. The `:host` option requires a string.
The `:scheme` option accepts `"http"` and `"https"` values. Default value is inferred from top level `:http` or `:https` option. It is useful when hosting Phoenix behind a load balancer or reverse proxy and terminating SSL there.
The `:path` option can be used to override root path. Useful when hosting Phoenix behind a reverse proxy with URL rewrite rules
* `:static_url` - configuration for generating URLs for static files. It will fallback to `url` if no option is provided. Accepts the same options as `url`
* `:watchers` - a set of watchers to run alongside your server. It expects a list of tuples containing the executable and its arguments. Watchers are guaranteed to run in the application directory, but only when the server is enabled (unless `:force_watchers` configuration is set to `true`). For example, the watcher below will run the "watch" mode of the webpack build tool when the server starts. You can configure it to whatever build tool or command you want:
```
[
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch",
"--watch-options-stdin"
]
]
```
The `:cd` and `:env` options can be given at the end of the list to customize the watcher:
```
[node: [..., cd: "assets", env: [{"TAILWIND_MODE", "watch"}]]]
```
A watcher can also be a module-function-args tuple that will be invoked accordingly:
```
[another: {Mod, :fun, [arg1, arg2]}]
```
* `:force_watchers` - when `true`, forces your watchers to start even when the `:server` option is set to `false`.
* `:live_reload` - configuration for the live reload option. Configuration requires a `:patterns` option which should be a list of file patterns to watch. When these files change, it will trigger a reload. If you are using a tool like [pow](http://pow.cx) in development, you may need to set the `:url` option appropriately.
```
live_reload: [
url: "ws://localhost:4000",
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif)$},
~r{web/views/.*(ex)$},
~r{web/templates/.*(eex)$}
]
]
```
* `:pubsub_server` - the name of the pubsub server to use in channels and via the Endpoint broadcast functions. The PubSub server is typically started in your supervision tree.
* `:render_errors` - responsible for rendering templates whenever there is a failure in the application. For example, if the application crashes with a 500 error during a HTML request, `render("500.html", assigns)` will be called in the view given to `:render_errors`. Defaults to:
```
[view: MyApp.ErrorView, accepts: ~w(html), layout: false, log: :debug]
```
The default format is used when none is set in the connection
### Adapter configuration
Phoenix allows you to choose which webserver adapter to use. The default is [`Phoenix.Endpoint.Cowboy2Adapter`](phoenix.endpoint.cowboy2adapter) which can be configured via the following top-level options.
* `:http` - the configuration for the HTTP server. It accepts all options as defined by [`Plug.Cowboy`](https://hexdocs.pm/plug_cowboy/). Defaults to `false`
* `:https` - the configuration for the HTTPS server. It accepts all options as defined by [`Plug.Cowboy`](https://hexdocs.pm/plug_cowboy/). Defaults to `false`
* `:drainer` - a drainer process that triggers when your application is shutting down to wait for any on-going request to finish. It accepts all options as defined by [`Plug.Cowboy.Drainer`](https://hexdocs.pm/plug_cowboy/Plug.Cowboy.Drainer.html). Defaults to `[]`, which will start a drainer process for each configured endpoint, but can be disabled by setting it to `false`.
Endpoint API
-------------
In the previous section, we have used the [`config/2`](#c:config/2) function that is automatically generated in your endpoint. Here's a list of all the functions that are automatically defined in your endpoint:
* for handling paths and URLs: [`struct_url/0`](#c:struct_url/0), [`url/0`](#c:url/0), [`path/1`](#c:path/1), [`static_url/0`](#c:static_url/0),[`static_path/1`](#c:static_path/1), and [`static_integrity/1`](#c:static_integrity/1)
* for broadcasting to channels: [`broadcast/3`](#c:broadcast/3), [`broadcast!/3`](#c:broadcast!/3), [`broadcast_from/4`](#c:broadcast_from/4), [`broadcast_from!/4`](#c:broadcast_from!/4), [`local_broadcast/3`](#c:local_broadcast/3), and [`local_broadcast_from/4`](#c:local_broadcast_from/4)
* for configuration: [`start_link/1`](#c:start_link/1), [`config/2`](#c:config/2), and [`config_change/2`](#c:config_change/2)
* as required by the [`Plug`](https://hexdocs.pm/plug/1.13.6/Plug.html) behaviour: [`Plug.init/1`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:init/1) and [`Plug.call/2`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:call/2)
Summary
========
Types
------
[event()](#t:event/0) [msg()](#t:msg/0) [topic()](#t:topic/0) Callbacks
----------
[broadcast!(topic, event, msg)](#c:broadcast!/3) Broadcasts a `msg` as `event` in the given `topic` to all nodes.
[broadcast(topic, event, msg)](#c:broadcast/3) Broadcasts a `msg` as `event` in the given `topic` to all nodes.
[broadcast\_from!(from, topic, event, msg)](#c:broadcast_from!/4) Broadcasts a `msg` from the given `from` as `event` in the given `topic` to all nodes.
[broadcast\_from(from, topic, event, msg)](#c:broadcast_from/4) Broadcasts a `msg` from the given `from` as `event` in the given `topic` to all nodes.
[config key, default](#c:config/2) Access the endpoint configuration given by key.
[config\_change(changed, removed)](#c:config_change/2) Reload the endpoint configuration on application upgrades.
[host()](#c:host/0) Returns the host from the :url configuration.
[init(atom, config)](#c:init/2) Initialize the endpoint configuration.
[local\_broadcast(topic, event, msg)](#c:local_broadcast/3) Broadcasts a `msg` as `event` in the given `topic` within the current node.
[local\_broadcast\_from(from, topic, event, msg)](#c:local_broadcast_from/4) Broadcasts a `msg` from the given `from` as `event` in the given `topic` within the current node.
[path(path)](#c:path/1) Generates the path information when routing to this endpoint.
[script\_name()](#c:script_name/0) Returns the script name from the :url configuration.
[start\_link(keyword)](#c:start_link/1) Starts the endpoint supervision tree.
[static\_integrity(path)](#c:static_integrity/1) Generates an integrity hash to a static file in `priv/static`.
[static\_lookup(path)](#c:static_lookup/1) Generates a two item tuple containing the `static_path` and `static_integrity`.
[static\_path(path)](#c:static_path/1) Generates a route to a static file in `priv/static`.
[static\_url()](#c:static_url/0) Generates the static URL without any path information.
[struct\_url()](#c:struct_url/0) Generates the endpoint base URL, but as a [`URI`](https://hexdocs.pm/elixir/URI.html) struct.
[subscribe(topic, opts)](#c:subscribe/2) Subscribes the caller to the given topic.
[unsubscribe(topic)](#c:unsubscribe/1) Unsubscribes the caller from the given topic.
[url()](#c:url/0) Generates the endpoint base URL without any path information.
Functions
----------
[server?(otp\_app, endpoint)](#server?/2) Checks if Endpoint's web server has been configured to start.
[socket(path, module, opts \\ [])](#socket/3) Defines a websocket/longpoll mount-point for a socket.
Types
======
### event()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L256)
```
@type event() :: String.t()
```
### msg()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L257)
```
@type msg() :: map() | {:binary, binary()}
```
### topic()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L255)
```
@type topic() :: String.t()
```
Callbacks
==========
### broadcast!(topic, event, msg)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L360)
```
@callback broadcast!(topic(), event(), msg()) :: :ok | no_return()
```
Broadcasts a `msg` as `event` in the given `topic` to all nodes.
Raises in case of failures.
### broadcast(topic, event, msg)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L353)
```
@callback broadcast(topic(), event(), msg()) :: :ok | {:error, term()}
```
Broadcasts a `msg` as `event` in the given `topic` to all nodes.
### broadcast\_from!(from, topic, event, msg)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L372)
```
@callback broadcast_from!(from :: pid(), topic(), event(), msg()) :: :ok | no_return()
```
Broadcasts a `msg` from the given `from` as `event` in the given `topic` to all nodes.
Raises in case of failures.
### broadcast\_from(from, topic, event, msg)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L365)
```
@callback broadcast_from(from :: pid(), topic(), event(), msg()) :: :ok | {:error, term()}
```
Broadcasts a `msg` from the given `from` as `event` in the given `topic` to all nodes.
### config key, default[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L274)
```
@callback config(key :: atom(), default :: term()) :: term()
```
Access the endpoint configuration given by key.
### config\_change(changed, removed)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L279)
```
@callback config_change(changed :: term(), removed :: term()) :: term()
```
Reload the endpoint configuration on application upgrades.
### host()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L334)
```
@callback host() :: String.t()
```
Returns the host from the :url configuration.
### init(atom, config)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L287)
```
@callback init(:supervisor, config :: Keyword.t()) :: {:ok, Keyword.t()}
```
Initialize the endpoint configuration.
Invoked when the endpoint supervisor starts, allows dynamically configuring the endpoint from system environment or other runtime sources.
### local\_broadcast(topic, event, msg)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L377)
```
@callback local_broadcast(topic(), event(), msg()) :: :ok
```
Broadcasts a `msg` as `event` in the given `topic` within the current node.
### local\_broadcast\_from(from, topic, event, msg)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L382)
```
@callback local_broadcast_from(from :: pid(), topic(), event(), msg()) :: :ok
```
Broadcasts a `msg` from the given `from` as `event` in the given `topic` within the current node.
### path(path)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L304)
```
@callback path(path :: String.t()) :: String.t()
```
Generates the path information when routing to this endpoint.
### script\_name()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L329)
```
@callback script_name() :: [String.t()]
```
Returns the script name from the :url configuration.
### start\_link(keyword)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L269)
```
@callback start_link(keyword()) :: Supervisor.on_start()
```
Starts the endpoint supervision tree.
Starts endpoint's configuration cache and possibly the servers for handling requests.
### static\_integrity(path)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L319)
```
@callback static_integrity(path :: String.t()) :: String.t() | nil
```
Generates an integrity hash to a static file in `priv/static`.
### static\_lookup(path)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L324)
```
@callback static_lookup(path :: String.t()) ::
{String.t(), String.t()} | {String.t(), nil}
```
Generates a two item tuple containing the `static_path` and `static_integrity`.
### static\_path(path)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L314)
```
@callback static_path(path :: String.t()) :: String.t()
```
Generates a route to a static file in `priv/static`.
### static\_url()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L309)
```
@callback static_url() :: String.t()
```
Generates the static URL without any path information.
### struct\_url()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L294)
```
@callback struct_url() :: URI.t()
```
Generates the endpoint base URL, but as a [`URI`](https://hexdocs.pm/elixir/URI.html) struct.
### subscribe(topic, opts)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L343)
```
@callback subscribe(topic(), opts :: Keyword.t()) :: :ok | {:error, term()}
```
Subscribes the caller to the given topic.
See [`Phoenix.PubSub.subscribe/3`](https://hexdocs.pm/phoenix_pubsub/2.1.1/Phoenix.PubSub.html#subscribe/3) for options.
### unsubscribe(topic)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L348)
```
@callback unsubscribe(topic()) :: :ok | {:error, term()}
```
Unsubscribes the caller from the given topic.
### url()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L299)
```
@callback url() :: String.t()
```
Generates the endpoint base URL without any path information.
Functions
==========
### server?(otp\_app, endpoint)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L933)
Checks if Endpoint's web server has been configured to start.
* `otp_app` - The OTP app running the endpoint, for example `:my_app`
* `endpoint` - The endpoint module, for example `MyAppWeb.Endpoint`
#### Examples
```
iex> Phoenix.Endpoint.server?(:my_app, MyAppWeb.Endpoint)
true
```
### socket(path, module, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/endpoint.ex#L907)
Defines a websocket/longpoll mount-point for a socket.
#### Options
* `:websocket` - controls the websocket configuration. Defaults to `true`. May be false or a keyword list of options. See "Common configuration" and "WebSocket configuration" for the whole list
* `:longpoll` - controls the longpoll configuration. Defaults to `false`. May be true or a keyword list of options. See "Common configuration" and "Longpoll configuration" for the whole list
If your socket is implemented using [`Phoenix.Socket`](phoenix.socket), you can also pass to each transport above all options accepted on `use Phoenix.Socket`. An option given here will override the value in `use Phoenix.Socket`.
#### Examples
```
socket "/ws", MyApp.UserSocket
socket "/ws/admin", MyApp.AdminUserSocket,
longpoll: true,
websocket: [compress: true]
```
#### Path params
It is possible to include variables in the path, these will be available in the `params` that are passed to the socket.
```
socket "/ws/:user_id", MyApp.UserSocket,
websocket: [path: "/project/:project_id"]
```
#### Common configuration
The configuration below can be given to both `:websocket` and `:longpoll` keys:
* `:path` - the path to use for the transport. Will default to the transport name ("/websocket" or "/longpoll")
* `:serializer` - a list of serializers for messages. See [`Phoenix.Socket`](phoenix.socket) for more information
* `:transport_log` - if the transport layer itself should log and, if so, the level
* `:check_origin` - if the transport should check the origin of requests when the `origin` header is present. May be `true`, `false`, a list of hosts that are allowed, or a function provided as MFA tuple. Defaults to `:check_origin` setting at endpoint configuration.
If `true`, the header is checked against `:host` in `YourAppWeb.Endpoint.config(:url)[:host]`.
If `false`, your app is vulnerable to Cross-Site WebSocket Hijacking (CSWSH) attacks. Only use in development, when the host is truly unknown or when serving clients that do not send the `origin` header, such as mobile apps.
You can also specify a list of explicitly allowed origins. Wildcards are supported.
```
check_origin: [
"https://example.com",
"//another.com:888",
"//*.other.com"
]
```
Or to accept any origin matching the request connection's host, port, and scheme:
```
check_origin: :conn
```
Or a custom MFA function:
```
check_origin: {MyAppWeb.Auth, :my_check_origin?, []}
```
The MFA is invoked with the request `%URI{}` as the first argument, followed by arguments in the MFA list, and must return a boolean.
* `:code_reloader` - enable or disable the code reloader. Defaults to your endpoint configuration
* `:connect_info` - a list of keys that represent data to be copied from the transport to be made available in the user socket `connect/3` callback
The valid keys are:
+ `:peer_data` - the result of [`Plug.Conn.get_peer_data/1`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#get_peer_data/1)
+ `:trace_context_headers` - a list of all trace context headers. Supported headers are defined by the [W3C Trace Context Specification](https://www.w3.org/TR/trace-context-1/). These headers are necessary for libraries such as [OpenTelemetry](https://opentelemetry.io/) to extract trace propagation information to know this request is part of a larger trace in progress.
+ `:x_headers` - all request headers that have an "x-" prefix
+ `:uri` - a `%URI{}` with information from the conn
+ `:user_agent` - the value of the "user-agent" request header
+ `{:session, session_config}` - the session information from [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html). The `session_config` is an exact copy of the arguments given to [`Plug.Session`](https://hexdocs.pm/plug/1.13.6/Plug.Session.html). This requires the "\_csrf\_token" to be given as request parameter with the value of `URI.encode_www_form(Plug.CSRFProtection.get_csrf_token())` when connecting to the socket. It can also be a MFA to allow loading config in runtime `{MyAppWeb.Auth, :get_session_config, []}`. Otherwise the session will be `nil`.Arbitrary keywords may also appear following the above valid keys, which is useful for passing custom connection information to the socket.
For example:
```
socket "/socket", AppWeb.UserSocket,
websocket: [
connect_info: [:peer_data, :trace_context_headers, :x_headers, :uri, session: [store: :cookie]]
]
```
With arbitrary keywords:
```
socket "/socket", AppWeb.UserSocket,
websocket: [
connect_info: [:uri, custom_value: "abcdef"]
]
```
#### Websocket configuration
The following configuration applies only to `:websocket`.
* `:timeout` - the timeout for keeping websocket connections open after it last received data, defaults to 60\_000ms
* `:max_frame_size` - the maximum allowed frame size in bytes, defaults to "infinity"
* `:fullsweep_after` - the maximum number of garbage collections before forcing a fullsweep for the socket process. You can set it to `0` to force more frequent cleanups of your websocket transport processes. Setting this option requires Erlang/OTP 24
* `:compress` - whether to enable per message compression on all data frames, defaults to false
* `:subprotocols` - a list of supported websocket subprotocols. Used for handshake `Sec-WebSocket-Protocol` response header, defaults to nil.
For example:
```
subprotocols: ["sip", "mqtt"]
```
* `:error_handler` - custom error handler for connection errors. If [`Phoenix.Socket.connect/3`](phoenix.socket#c:connect/3) returns an `{:error, reason}` tuple, the error handler will be called with the error reason. For WebSockets, the error handler must be a MFA tuple that receives a [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html), the error reason, and returns a [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) with a response. For example:
```
error_handler: {MySocket, :handle_error, []}
```
and a `{:error, :rate_limit}` return may be handled on `MySocket` as:
```
def handle_error(conn, :rate_limit), do: Plug.Conn.send_resp(conn, 429, "Too many requests")
```
#### Longpoll configuration
The following configuration applies only to `:longpoll`:
* `:window_ms` - how long the client can wait for new messages in its poll request, defaults to 10\_000ms.
* `:pubsub_timeout_ms` - how long a request can wait for the pubsub layer to respond, defaults to 2000ms.
* `:crypto` - options for verifying and signing the token, accepted by [`Phoenix.Token`](phoenix.token). By default tokens are valid for 2 weeks
| programming_docs |
phoenix Phoenix.CodeReloader Phoenix.CodeReloader
=====================
A plug and module to handle automatic code reloading.
To avoid race conditions, all code reloads are funneled through a sequential call operation.
Summary
========
Functions
----------
[call(conn, opts)](#call/2) API used by Plug to invoke the code reloader on every request.
[init(opts)](#init/1) API used by Plug to start the code reloader.
[reload!(endpoint)](#reload!/1) Same as [`reload/1`](#reload/1) but it will raise if Mix is not available.
[reload(endpoint)](#reload/1) Reloads code for the current Mix project by invoking the `:reloadable_compilers` on the list of `:reloadable_apps`.
[sync()](#sync/0) Synchronizes with the code server if it is alive.
Functions
==========
### call(conn, opts)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/code_reloader.ex#L74)
API used by Plug to invoke the code reloader on every request.
### init(opts)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/code_reloader.ex#L69)
API used by Plug to start the code reloader.
### reload!(endpoint)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/code_reloader.ex#L43)
```
@spec reload!(module()) :: :ok | {:error, binary()}
```
Same as [`reload/1`](#reload/1) but it will raise if Mix is not available.
### reload(endpoint)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/code_reloader.ex#L35)
```
@spec reload(module()) :: :ok | {:error, binary()}
```
Reloads code for the current Mix project by invoking the `:reloadable_compilers` on the list of `:reloadable_apps`.
This is configured in your application environment like:
```
config :your_app, YourAppWeb.Endpoint,
reloadable_compilers: [:gettext, :elixir],
reloadable_apps: [:ui, :backend]
```
Keep in mind `:reloadable_compilers` must be a subset of the `:compilers` specified in `project/0` in your `mix.exs`.
The `:reloadable_apps` defaults to `nil`. In such case default behaviour is to reload the current project if it consists of a single app, or all applications within an umbrella project. You can set `:reloadable_apps` to a subset of default applications to reload only some of them, an empty list - to effectively disable the code reloader, or include external applications from library dependencies.
This function is a no-op and returns `:ok` if Mix is not available.
### sync()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/code_reloader.ex#L51)
```
@spec sync() :: :ok
```
Synchronizes with the code server if it is alive.
It returns `:ok`. If it is not running, it also returns `:ok`.
phoenix Custom Error Pages Custom Error Pages
===================
Phoenix has a view called `ErrorView` which lives in `lib/hello_web/views/error_view.ex`. The purpose of `ErrorView` is to handle errors in a general way, from one centralized location.
The ErrorView
--------------
For new applications, the `ErrorView` view looks like this:
```
defmodule HelloWeb.ErrorView do
use HelloWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
```
Before we dive into this, let's see what the rendered `404 Not Found` message looks like in a browser. In the development environment, Phoenix will debug errors by default, showing us a very informative debugging page. What we want here, however, is to see what page the application would serve in production. In order to do that, we need to set `debug_errors: false` in `config/dev.exs`.
```
import Config
config :hello, HelloWeb.Endpoint,
http: [port: 4000],
debug_errors: false,
code_reloader: true,
. . .
```
After modifying our config file, we need to restart our server in order for this change to take effect. After restarting the server, let's go to <http://localhost:4000/such/a/wrong/path> for a running local application and see what we get.
Ok, that's not very exciting. We get the bare string "Not Found", displayed without any markup or styling.
The first question is, where does that error string come from? The answer is right in `ErrorView`.
```
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
```
Great, so we have this `template_not_found/2` function that takes a template and an `assigns` map, which we ignore. The `template_not_found/2` is invoked whenever a [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) view attempts to render a template, but no template is found.
In other words, to provide custom error pages, we could simply define a proper `render/2` function clause in `HelloWeb.ErrorView`.
```
def render("404.html", _assigns) do
"Page Not Found"
end
```
But we can do even better.
Phoenix generates an `ErrorView` for us, but it doesn't give us a `lib/hello_web/templates/error` directory. Let's create one now. Inside our new directory, let's add a template named`404.html.heex` and give it some markup – a mixture of our application layout and a new `<div>` with our message to the user.
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Welcome to Phoenix!</title>
<link rel="stylesheet" href="/css/app.css"/>
<script defer type="text/javascript" src="/js/app.js"></script>
</head>
<body>
<header>
<section class="container">
<nav>
<ul>
<li><a href="https://hexdocs.pm/phoenix/overview.html">Get Started</a></li>
</ul>
</nav>
<a href="https://phoenixframework.org/" class="phx-logo">
<img src="/images/phoenix.png" alt="Phoenix Framework Logo"/>
</a>
</section>
</header>
<main class="container">
<section class="phx-hero">
<p>Sorry, the page you are looking for does not exist.</p>
</section>
</main>
</body>
</html>
```
After you define the template file, remember to remove the equivalent `render/2` clause for that template, as otherwise the function overrides the template. Let's do so for the 404.html clause we have previously introduced in `lib/hello_web/views/error_view.ex`:
```
- def render("404.html", _assigns) do
- "Page Not Found"
- end
```
Now, when we go back to <http://localhost:4000/such/a/wrong/path>, we should see a much nicer error page. It is worth noting that we did not render our `404.html.heex` template through our application layout, even though we want our error page to have the look and feel of the rest of our site. This is to avoid circular errors. For example, what happens if our application failed due to an error in the layout? Attempting to render the layout again will just trigger another error. So ideally we want to minimize the amount of dependencies and logic in our error templates, sharing only what is necessary.
Custom exceptions
------------------
Elixir provides a macro called [`defexception/1`](https://hexdocs.pm/elixir/Kernel.html#defexception/1) for defining custom exceptions. Exceptions are represented as structs, and structs need to be defined inside of modules.
In order to create a custom exception, we need to define a new module. Conventionally, this will have "Error" in the name. Inside that module, we need to define a new exception with [`defexception/1`](https://hexdocs.pm/elixir/Kernel.html#defexception/1), the file `lib/hello_web.ex` seems like a good place for it.
```
defmodule HelloWeb.SomethingNotFoundError do
defexception [:message]
end
```
You can raise your new exception like this:
```
raise HelloWeb.SomethingNotFoundError, "oops"
```
By default, Plug and Phoenix will treat all exceptions as 500 errors. However, Plug provides a protocol called [`Plug.Exception`](https://hexdocs.pm/plug/1.13.6/Plug.Exception.html) where we are able to customize the status and add actions that exception structs can return on the debug error page.
If we wanted to supply a status of 404 for an `HelloWeb.SomethingNotFoundError` error, we could do it by defining an implementation for the [`Plug.Exception`](https://hexdocs.pm/plug/1.13.6/Plug.Exception.html) protocol like this, in `lib/hello_web.ex`:
```
defimpl Plug.Exception, for: HelloWeb.SomethingNotFoundError do
def status(_exception), do: 404
def actions(_exception), do: []
end
```
Alternatively, you could define a `plug_status` field directly in the exception struct:
```
defmodule HelloWeb.SomethingNotFoundError do
defexception [:message, plug_status: 404]
end
```
However, implementing the [`Plug.Exception`](https://hexdocs.pm/plug/1.13.6/Plug.Exception.html) protocol by hand can be convenient in certain occasions, such as when providing actionable errors.
Actionable errors
------------------
Exception actions are functions that can be triggered by the error page, and they're basically a list of maps defining a `label` and a `handler` to be executed.
They are rendered in the error page as a collection of buttons and follow the format of:
```
[
%{
label: String.t(),
handler: {module(), function :: atom(), args :: []}
}
]
```
If we wanted to return some actions for an `HelloWeb.SomethingNotFoundError` we would implement [`Plug.Exception`](https://hexdocs.pm/plug/1.13.6/Plug.Exception.html) like this:
```
defimpl Plug.Exception, for: HelloWeb.SomethingNotFoundError do
def status(_exception), do: 404
def actions(_exception) do
[
%{
label: "Run seeds",
handler: {Code, :eval_file, "priv/repo/seeds.exs"}
}
]
end
end
```
[← Previous Page Deploying on Heroku](heroku) [Next Page → Using SSL](using_ssl)
phoenix Phoenix.ChannelTest Phoenix.ChannelTest
====================
Conveniences for testing Phoenix channels.
In channel tests, we interact with channels via process communication, sending and receiving messages. It is also common to subscribe to the same topic the channel subscribes to, allowing us to assert if a given message was broadcast or not.
Channel testing
----------------
To get started, define the module attribute `@endpoint` in your test case pointing to your application endpoint.
Then you can directly create a socket and [`subscribe_and_join/4`](#subscribe_and_join/4) topics and channels:
```
{:ok, _, socket} =
socket(UserSocket, "user:id", %{some_assigns: 1})
|> subscribe_and_join(RoomChannel, "room:lobby", %{"id" => 3})
```
You usually want to set the same ID and assigns your `UserSocket.connect/3` callback would set. Alternatively, you can use the [`connect/3`](#connect/3) helper to call your `UserSocket.connect/3` callback and initialize the socket with the socket id:
```
{:ok, socket} = connect(UserSocket, %{"some" => "params"}, %{})
{:ok, _, socket} = subscribe_and_join(socket, "room:lobby", %{"id" => 3})
```
Once called, [`subscribe_and_join/4`](#subscribe_and_join/4) will subscribe the current test process to the "room:lobby" topic and start a channel in another process. It returns `{:ok, reply, socket}` or `{:error, reply}`.
Now, in the same way the channel has a socket representing communication it will push to the client. Our test has a socket representing communication to be pushed to the server.
For example, we can use the [`push/3`](#push/3) function in the test to push messages to the channel (it will invoke `handle_in/3`):
```
push(socket, "my_event", %{"some" => "data"})
```
Similarly, we can broadcast messages from the test itself on the topic that both test and channel are subscribed to, triggering `handle_out/3` on the channel:
```
broadcast_from(socket, "my_event", %{"some" => "data"})
```
> Note only [`broadcast_from/3`](#broadcast_from/3) and [`broadcast_from!/3`](#broadcast_from!/3) are available in tests to avoid broadcast messages to be resent to the test process.
>
>
While the functions above are pushing data to the channel (server) we can use [`assert_push/3`](#assert_push/3) to verify the channel pushed a message to the client:
```
assert_push "my_event", %{"some" => "data"}
```
Or even assert something was broadcast into pubsub:
```
assert_broadcast "my_event", %{"some" => "data"}
```
Finally, every time a message is pushed to the channel, a reference is returned. We can use this reference to assert a particular reply was sent from the server:
```
ref = push(socket, "counter", %{})
assert_reply ref, :ok, %{"counter" => 1}
```
Checking side-effects
----------------------
Often one may want to do side-effects inside channels, like writing to the database, and verify those side-effects during their tests.
Imagine the following `handle_in/3` inside a channel:
```
def handle_in("publish", %{"id" => id}, socket) do
Repo.get!(Post, id) |> Post.publish() |> Repo.update!()
{:noreply, socket}
end
```
Because the whole communication is asynchronous, the following test would be very brittle:
```
push(socket, "publish", %{"id" => 3})
assert Repo.get_by(Post, id: 3, published: true)
```
The issue is that we have no guarantees the channel has done processing our message after calling [`push/3`](#push/3). The best solution is to assert the channel sent us a reply before doing any other assertion. First change the channel to send replies:
```
def handle_in("publish", %{"id" => id}, socket) do
Repo.get!(Post, id) |> Post.publish() |> Repo.update!()
{:reply, :ok, socket}
end
```
Then expect them in the test:
```
ref = push(socket, "publish", %{"id" => 3})
assert_reply ref, :ok
assert Repo.get_by(Post, id: 3, published: true)
```
Leave and close
----------------
This module also provides functions to simulate leaving and closing a channel. Once you leave or close a channel, because the channel is linked to the test process on join, it will crash the test process:
```
leave(socket)
** (EXIT from #PID<...>) {:shutdown, :leave}
```
You can avoid this by unlinking the channel process in the test:
```
Process.unlink(socket.channel_pid)
```
Notice [`leave/1`](#leave/1) is async, so it will also return a reference which you can use to check for a reply:
```
ref = leave(socket)
assert_reply ref, :ok
```
On the other hand, close is always sync and it will return only after the channel process is guaranteed to have been terminated:
```
:ok = close(socket)
```
This mimics the behaviour existing in clients.
To assert that your channel closes or errors asynchronously, you can monitor the channel process with the tools provided by Elixir, and wait for the `:DOWN` message. Imagine an implementation of the `handle_info/2` function that closes the channel when it receives `:some_message`:
```
def handle_info(:some_message, socket) do
{:stop, :normal, socket}
end
```
In your test, you can assert that the close happened by:
```
Process.monitor(socket.channel_pid)
send(socket.channel_pid, :some_message)
assert_receive {:DOWN, _, _, _, :normal}
```
Summary
========
Functions
----------
[assert\_broadcast(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :assert\_receive\_timeout))](#assert_broadcast/3) Asserts the channel has broadcast a message within `timeout`.
[assert\_push(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :assert\_receive\_timeout))](#assert_push/3) Asserts the channel has pushed a message back to the client with the given event and payload within `timeout`.
[assert\_reply(ref, status, payload \\ Macro.escape(%{}), timeout \\ Application.fetch\_env!(:ex\_unit, :assert\_receive\_timeout))](#assert_reply/4) Asserts the channel has replied to the given message within `timeout`.
[broadcast\_from!(socket, event, message)](#broadcast_from!/3) Same as [`broadcast_from/3`](#broadcast_from/3), but raises if broadcast fails.
[broadcast\_from(socket, event, message)](#broadcast_from/3) Broadcast event from pid to all subscribers of the socket topic.
[close(socket, timeout \\ 5000)](#close/2) Emulates the client closing the socket.
[connect(handler, params, connect\_info \\ quote do %{} end)](#connect/3) Initiates a transport connection for the socket handler.
[join(socket, topic)](#join/2) See [`join/4`](#join/4).
[join(socket, topic, payload)](#join/3) See [`join/4`](#join/4).
[join(socket, channel, topic, payload \\ %{})](#join/4) Joins the channel under the given topic and payload.
[leave(socket)](#leave/1) Emulates the client leaving the channel.
[push(socket, event, payload \\ %{})](#push/3) Pushes a message into the channel.
[refute\_broadcast(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :refute\_receive\_timeout))](#refute_broadcast/3) Asserts the channel has not broadcast a message within `timeout`.
[refute\_push(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :refute\_receive\_timeout))](#refute_push/3) Asserts the channel has not pushed a message to the client matching the given event and payload within `timeout`.
[refute\_reply(ref, status, payload \\ Macro.escape(%{}), timeout \\ Application.fetch\_env!(:ex\_unit, :refute\_receive\_timeout))](#refute_reply/4) Asserts the channel has not replied with a matching payload within `timeout`.
[socket(socket\_module)](#socket/1) Builds a socket for the given `socket_module`.
[socket(socket\_module, socket\_id, socket\_assigns)](#socket/3) Builds a socket for the given `socket_module` with given id and assigns.
[subscribe\_and\_join!(socket, topic)](#subscribe_and_join!/2) See [`subscribe_and_join!/4`](#subscribe_and_join!/4).
[subscribe\_and\_join!(socket, topic, payload)](#subscribe_and_join!/3) See [`subscribe_and_join!/4`](#subscribe_and_join!/4).
[subscribe\_and\_join!(socket, channel, topic, payload \\ %{})](#subscribe_and_join!/4) Same as [`subscribe_and_join/4`](#subscribe_and_join/4), but returns either the socket or throws an error.
[subscribe\_and\_join(socket, topic)](#subscribe_and_join/2) See [`subscribe_and_join/4`](#subscribe_and_join/4).
[subscribe\_and\_join(socket, topic, payload)](#subscribe_and_join/3) See [`subscribe_and_join/4`](#subscribe_and_join/4).
[subscribe\_and\_join(socket, channel, topic, payload \\ %{})](#subscribe_and_join/4) Subscribes to the given topic and joins the channel under the given topic and payload.
Functions
==========
### assert\_broadcast(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :assert\_receive\_timeout))[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L581)
Asserts the channel has broadcast a message within `timeout`.
Before asserting anything was broadcast, we must first subscribe to the topic of the channel in the test process:
```
@endpoint.subscribe("foo:ok")
```
Now we can match on event and payload as patterns:
```
assert_broadcast "some_event", %{"data" => _}
```
In the assertion above, we don't particularly care about the data being sent, as long as something was sent.
The timeout is in milliseconds and defaults to the `:assert_receive_timeout` set on the `:ex_unit` application (which defaults to 100ms).
### assert\_push(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :assert\_receive\_timeout))[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L488)
Asserts the channel has pushed a message back to the client with the given event and payload within `timeout`.
Notice event and payload are patterns. This means one can write:
```
assert_push "some_event", %{"data" => _}
```
In the assertion above, we don't particularly care about the data being sent, as long as something was sent.
The timeout is in milliseconds and defaults to the `:assert_receive_timeout` set on the `:ex_unit` application (which defaults to 100ms).
**NOTE:** Because event and payload are patterns, they will be matched. This means that if you wish to assert that the received payload is equivalent to an existing variable, you need to pin the variable in the assertion expression.
Good:
```
expected_payload = %{foo: "bar"}
assert_push "some_event", ^expected_payload
```
Bad:
```
expected_payload = %{foo: "bar"}
assert_push "some_event", expected_payload
# The code above does not assert the payload matches the described map.
```
### assert\_reply(ref, status, payload \\ Macro.escape(%{}), timeout \\ Application.fetch\_env!(:ex\_unit, :assert\_receive\_timeout))[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L531)
Asserts the channel has replied to the given message within `timeout`.
Notice status and payload are patterns. This means one can write:
```
ref = push(channel, "some_event")
assert_reply ref, :ok, %{"data" => _}
```
In the assertion above, we don't particularly care about the data being sent, as long as something was replied.
The timeout is in milliseconds and defaults to the `:assert_receive_timeout` set on the `:ex_unit` application (which defaults to 100ms).
### broadcast\_from!(socket, event, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L452)
Same as [`broadcast_from/3`](#broadcast_from/3), but raises if broadcast fails.
### broadcast\_from(socket, event, message)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L444)
Broadcast event from pid to all subscribers of the socket topic.
The test process will not receive the published message. This triggers the `handle_out/3` callback in the channel.
#### Examples
```
iex> broadcast_from(socket, "new_message", %{id: 1, content: "hello"})
:ok
```
### close(socket, timeout \\ 5000)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L428)
Emulates the client closing the socket.
Closing socket is synchronous and has a default timeout of 5000 milliseconds.
### connect(handler, params, connect\_info \\ quote do %{} end)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L268)
Initiates a transport connection for the socket handler.
Useful for testing UserSocket authentication. Returns the result of the handler's [`connect/3`](#connect/3) callback.
### join(socket, topic)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L353)
See [`join/4`](#join/4).
### join(socket, topic, payload)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L358)
See [`join/4`](#join/4).
### join(socket, channel, topic, payload \\ %{})[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L370)
Joins the channel under the given topic and payload.
The given channel is joined in a separate process which is linked to the test process.
It returns `{:ok, reply, socket}` or `{:error, reply}`.
### leave(socket)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L418)
```
@spec leave(Phoenix.Socket.t()) :: reference()
```
Emulates the client leaving the channel.
### push(socket, event, payload \\ %{})[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L407)
```
@spec push(Phoenix.Socket.t(), String.t(), map()) :: reference()
```
Pushes a message into the channel.
The triggers the `handle_in/3` callback in the channel.
#### Examples
```
iex> push(socket, "new_message", %{id: 1, content: "hello"})
reference
```
### refute\_broadcast(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :refute\_receive\_timeout))[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L599)
Asserts the channel has not broadcast a message within `timeout`.
Like `assert_broadcast`, the event and payload are patterns.
The timeout is in milliseconds and defaults to the `:refute_receive_timeout` set on the `:ex_unit` application (which defaults to 100ms). Keep in mind this macro will block the test by the timeout value, so use it only when necessary as overuse will certainly slow down your test suite.
### refute\_push(event, payload, timeout \\ Application.fetch\_env!(:ex\_unit, :refute\_receive\_timeout))[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L508)
Asserts the channel has not pushed a message to the client matching the given event and payload within `timeout`.
Like `assert_push`, the event and payload are patterns.
The timeout is in milliseconds and defaults to the `:refute_receive_timeout` set on the `:ex_unit` application (which defaults to 100ms). Keep in mind this macro will block the test by the timeout value, so use it only when necessary as overuse will certainly slow down your test suite.
### refute\_reply(ref, status, payload \\ Macro.escape(%{}), timeout \\ Application.fetch\_env!(:ex\_unit, :refute\_receive\_timeout))[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L553)
Asserts the channel has not replied with a matching payload within `timeout`.
Like `assert_reply`, the event and payload are patterns.
The timeout is in milliseconds and defaults to the `:refute_receive_timeout` set on the `:ex_unit` application (which defaults to 100ms). Keep in mind this macro will block the test by the timeout value, so use it only when necessary as overuse will certainly slow down your test suite.
### socket(socket\_module)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L208)
Builds a socket for the given `socket_module`.
The socket is then used to subscribe and join channels. Use this function when you want to create a blank socket to pass to functions like `UserSocket.connect/3`.
Otherwise, use [`socket/3`](#socket/3) if you want to build a socket with existing id and assigns.
#### Examples
```
socket(MyApp.UserSocket)
```
### socket(socket\_module, socket\_id, socket\_assigns)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L220)
Builds a socket for the given `socket_module` with given id and assigns.
#### Examples
```
socket(MyApp.UserSocket, "user_id", %{some: :assign})
```
### subscribe\_and\_join!(socket, topic)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L294)
See [`subscribe_and_join!/4`](#subscribe_and_join!/4).
### subscribe\_and\_join!(socket, topic, payload)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L299)
See [`subscribe_and_join!/4`](#subscribe_and_join!/4).
### subscribe\_and\_join!(socket, channel, topic, payload \\ %{})[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L311)
Same as [`subscribe_and_join/4`](#subscribe_and_join/4), but returns either the socket or throws an error.
This is helpful when you are not testing joining the channel and just need the socket.
### subscribe\_and\_join(socket, topic)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L320)
See [`subscribe_and_join/4`](#subscribe_and_join/4).
### subscribe\_and\_join(socket, topic, payload)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L325)
See [`subscribe_and_join/4`](#subscribe_and_join/4).
### subscribe\_and\_join(socket, channel, topic, payload \\ %{})[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/test/channel_test.ex#L346)
Subscribes to the given topic and joins the channel under the given topic and payload.
By subscribing to the topic, we can use [`assert_broadcast/3`](#assert_broadcast/3) to verify a message has been sent through the pubsub layer.
By joining the channel, we can interact with it directly. The given channel is joined in a separate process which is linked to the test process.
If no channel module is provided, the socket's handler is used to lookup the matching channel for the given topic.
It returns `{:ok, reply, socket}` or `{:error, reply}`.
| programming_docs |
phoenix Testing Controllers Testing Controllers
====================
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [Introduction to Testing guide](testing).
>
>
At the end of the Introduction to Testing guide, we generated an HTML resource for posts using the following command:
```
$ mix phx.gen.html Blog Post posts title body:text
```
This gave us a number of modules for free, including a PostController and the associated tests. We are going to explore those tests to learn more about testing controllers in general. At the end of the guide, we will generate a JSON resource, and explore how our API tests look like.
HTML controller tests
----------------------
If you open up `test/hello_web/controllers/post_controller_test.exs`, you will find the following:
```
defmodule HelloWeb.PostControllerTest do
use HelloWeb.ConnCase
alias Hello.Blog
@create_attrs %{body: "some body", title: "some title"}
@update_attrs %{body: "some updated body", title: "some updated title"}
@invalid_attrs %{body: nil, title: nil}
def fixture(:post) do
{:ok, post} = Blog.create_post(@create_attrs)
post
end
...
```
Similar to the `PageControllerTest` that ships with our application, this controller tests uses `use HelloWeb.ConnCase` to setup the testing structure. Then, as usual, it defines some aliases, some module attributes to use throughout testing, and then it starts a series of `describe` blocks, each of them to test a different controller action.
### The index action
The first describe block is for the `index` action. The action itself is implemented like this in `lib/hello_web/controllers/post_controller.ex`:
```
def index(conn, _params) do
posts = Blog.list_posts()
render(conn, "index.html", posts: posts)
end
```
It gets all posts and renders the "index.html" template. The template can be found in `lib/hello_web/templates/page/index.html.heex`.
The test looks like this:
```
describe "index" do
test "lists all posts", %{conn: conn} do
conn = get(conn, Routes.post_path(conn, :index))
assert html_response(conn, 200) =~ "Listing Posts"
end
end
```
The test for the `index` page is quite straight-forward. It uses the `get/2` helper to make a request to the "/posts" page, returned by `Routes.post_path(conn, :index)`, then we assert we got a successful HTML response and match on its contents.
### The create action
The next test we will look at is the one for the `create` action. The `create` action implementation is this:
```
def create(conn, %{"post" => post_params}) do
case Blog.create_post(post_params) do
{:ok, post} ->
conn
|> put_flash(:info, "Post created successfully.")
|> redirect(to: Routes.post_path(conn, :show, post))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
```
Since there are two possible outcomes for the `create`, we will have at least two tests:
```
describe "create post" do
test "redirects to show when data is valid", %{conn: conn} do
conn = post(conn, Routes.post_path(conn, :create), post: @create_attrs)
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == Routes.post_path(conn, :show, id)
conn = get(conn, Routes.post_path(conn, :show, id))
assert html_response(conn, 200) =~ "Show Post"
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post(conn, Routes.post_path(conn, :create), post: @invalid_attrs)
assert html_response(conn, 200) =~ "New Post"
end
end
```
The first test starts with a `post/2` request. That's because once the form in the `/posts/new` page is submitted, it becomes a POST request to the create action. Because we have supplied valid attributes, the post should have been successfully created and we should have redirected to the show action of the new post. This new page will have an address like `/posts/ID`, where ID is the identifier of the post in the database.
We then use `redirected_params(conn)` to get the ID of the post and then match that we indeed redirected to the show action. Finally, we do request a `get` request to the page we redirected to, allowing us to verify that the post was indeed created.
For the second test, we simply test the failure scenario. If any invalid attribute is given, it should re-render the "New Post" page.
One common question is: how many failure scenarios do you test at the controller level? For example, in the [Testing Contexts](testing_contexts) guide, we introduced a validation to the `title` field of the post:
```
def changeset(post, attrs) do
post
|> cast(attrs, [:title, :body])
|> validate_required([:title, :body])
|> validate_length(:title, min: 2)
end
```
In other words, creating a post can fail for the following reasons:
* the title is missing
* the body is missing
* the title is present but is less than 2 characters
Should we test all of these possible outcomes in our controller tests?
The answer is no. All of the different rules and outcomes should be verified in your context and schema tests. The controller works as the integration layer. In the controller tests we simply want to verify, in broad strokes, that we handle both success and failure scenarios.
The test for `update` follows a similar structure as `create`, so let's skip to the `delete` test.
### The delete action
The `delete` action looks like this:
```
def delete(conn, %{"id" => id}) do
post = Blog.get_post!(id)
{:ok, _post} = Blog.delete_post(post)
conn
|> put_flash(:info, "Post deleted successfully.")
|> redirect(to: Routes.post_path(conn, :index))
end
```
The test is written like this:
```
describe "delete post" do
setup [:create_post]
test "deletes chosen post", %{conn: conn, post: post} do
conn = delete(conn, Routes.post_path(conn, :delete, post))
assert redirected_to(conn) == Routes.post_path(conn, :index)
assert_error_sent 404, fn ->
get(conn, Routes.post_path(conn, :show, post))
end
end
end
defp create_post(_) do
post = fixture(:post)
%{post: post}
end
```
First of all, `setup` is used to declare that the `create_post` function should run before every test in this `describe` block. The `create_post` function simply creates a post and stores it in the test metadata. This allows us to, in the first line of the test, match on both the post and the connection:
```
test "deletes chosen post", %{conn: conn, post: post} do
```
The test uses `delete/2` to delete the post and then asserts that we redirected to the index page. Finally, we check that it is no longer possible to access the show page of the deleted post:
```
assert_error_sent 404, fn ->
get(conn, Routes.post_path(conn, :show, post))
end
```
`assert_error_sent` is a testing helper provided by [`Phoenix.ConnTest`](phoenix.conntest). In this case, it verifies that:
1. An exception was raised
2. The exception has a status code equivalent to 404 (which stands for Not Found)
This pretty much mimics how Phoenix handles exceptions. For example, when we access `/posts/12345` where `12345` is an ID that does not exist, we will invoke our `show` action:
```
def show(conn, %{"id" => id}) do
post = Blog.get_post!(id)
render(conn, "show.html", post: post)
end
```
When an unknown post ID is given to `Blog.get_post!/1`, it raises an `Ecto.NotFoundError`. If your application raises any exception during a web request, Phoenix translates those requests into proper HTTP response codes. In this case, 404.
We could, for example, have written this test as:
```
assert_raise Ecto.NotFoundError, fn ->
get(conn, Routes.post_path(conn, :show, post))
end
```
However, you may prefer the implementation Phoenix generates by default as it ignores the specific details of the failure, and instead verifies what the browser would actually receive.
The tests for `new`, `edit`, and `show` actions are simpler variations of the tests we have seen so far. You can check the action implementation and their respective tests yourself. Now we are ready to move to JSON controller tests.
JSON controller tests
----------------------
So far we have been working with a generated HTML resource. However, let's take a look at how our tests look like when we generate a JSON resource.
First of all, run this command:
```
$ mix phx.gen.json News Article articles title body
```
We chose a very similar concept to the Blog context <-> Post schema, except we are using a different name, so we can study these concepts in isolation.
After you run the command above, do not forget to follow the final steps output by the generator. Once all is done, we should run [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html) and now have 33 passing tests:
```
$ mix test
................
Finished in 0.6 seconds
33 tests, 0 failures
Randomized with seed 618478
```
You may have noticed that this time the scaffold controller has generated fewer tests. Previously it generated 16 (we went from 3 to 19) and now it generated 14 (we went from 19 to 33). That's because JSON APIs do not need to expose the `new` and `edit` actions. We can see this is the case in the resource we have added to the router at the end of the [`mix phx.gen.json`](mix.tasks.phx.gen.json) command:
```
resources "/articles", ArticleController, except: [:new, :edit]
```
`new` and `edit` are only necessary for HTML because they basically exist to assist users in creating and updating resources. Besides having less actions, we will notice the controller and view tests and implementations for JSON are drastically different from the HTML ones.
The only thing that is pretty much the same between HTML and JSON is the contexts and the schema, which, once you think about it, it makes total sense. After all, your business logic should remain the same, regardless if you are exposing it as HTML or JSON.
With the differences in hand, let's take a look at the controller tests.
### The index action
Open up `test/hello_web/controllers/article_controller_test.exs`. The initial structure is quite similar to `post_controller_test.exs`. So let's take a look at the tests for the `index` action. The `index` action itself is implemented in `lib/hello_web/controllers/article_controller.ex` like this:
```
def index(conn, _params) do
articles = News.list_articles()
render(conn, "index.json", articles: articles)
end
```
The action gets all articles and renders `index.json`. Since we are talking about JSON, we don't have a `index.json.eex` template. Instead, the code that converts `articles` into JSON can be found directly in the ArticleView module, defined at `lib/hello_web/views/article_view.ex` like this:
```
defmodule HelloWeb.ArticleView do
use HelloWeb, :view
alias HelloWeb.ArticleView
def render("index.json", %{articles: articles}) do
%{data: render_many(articles, ArticleView, "article.json")}
end
def render("show.json", %{article: article}) do
%{data: render_one(article, ArticleView, "article.json")}
end
def render("article.json", %{article: article}) do
%{id: article.id,
title: article.title,
body: article.body}
end
end
```
We talked about `render_many` in the [Views and templates guide](views). All we need to know for now is that all JSON replies have a "data" key with either a list of posts (for index) or a single post inside of it.
Let's take a look at the test for the `index` action then:
```
describe "index" do
test "lists all articles", %{conn: conn} do
conn = get(conn, Routes.article_path(conn, :index))
assert json_response(conn, 200)["data"] == []
end
end
```
It simply accesses the `index` path, asserts we got a JSON response with status 200 and that it contains a "data" key with an empty list, as we have no articles to return.
That was quite boring. Let's look at something more interesting.
### The `create` action
The `create` action is defined like this:
```
def create(conn, %{"article" => article_params}) do
with {:ok, %Article{} = article} <- News.create_article(article_params) do
conn
|> put_status(:created)
|> put_resp_header("location", Routes.article_path(conn, :show, article))
|> render("show.json", article: article)
end
end
```
As we can see, it checks if an article could be created. If so, it sets the status code to `:created` (which translates to 201), it sets a "location" header with the location of the article, and then renders "show.json" with the article.
This is precisely what the first test for the `create` action verifies:
```
describe "create" do
test "renders article when data is valid", %{conn: conn} do
conn = post(conn, Routes.article_path(conn, :create), article: @create_attrs)
assert %{"id" => id} = json_response(conn, 201)["data"]
conn = get(conn, Routes.article_path(conn, :show, id))
assert %{
"id" => id,
"body" => "some body",
"title" => "some title"
} = json_response(conn, 200)["data"]
end
```
The test uses `post/2` to create a new article and then we verify that the article returned a JSON response, with status 201, and that it had a "data" key in it. We pattern match the "data" on `%{"id" => id}`, which allows us to extract the ID of the new article. Then we perform a `get/2` request on the `show` route and verify that the article was successfully created.
Inside `describe "create"`, we will find another test, which handles the failure scenario. Can you spot the failure scenario in the `create` action? Let's recap it:
```
def create(conn, %{"article" => article_params}) do
with {:ok, %Article{} = article} <- News.create_article(article_params) do
```
The `with` special form that ships as part of Elixir allows us to check explicitly for the happy paths. In this case, we are interested only in the scenarios where `News.create_article(article_params)` returns `{:ok, article}`, if it returns anything else, the other value will simply be returned directly and none of the contents inside the `do/end` block will be executed. In other words, if `News.create_article/1` returns `{:error, changeset}`, we will simply return `{:error, changeset}` from the action.
However, this introduces an issue. Our actions do not know how to handle the `{:error, changeset}` result by default. Luckily, we can teach Phoenix Controllers to handle it with the Action Fallback controller. At the top of `ArticleController`, you will find:
```
action_fallback HelloWeb.FallbackController
```
This line says: if any action does not return a `%Plug.Conn{}`, we want to invoke `FallbackController` with the result. You will find `HelloWeb.FallbackController` at `lib/hello_web/controllers/fallback_controller.ex` and it looks like this:
```
defmodule HelloWeb.FallbackController do
use HelloWeb, :controller
def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
conn
|> put_status(:unprocessable_entity)
|> put_view(HelloWeb.ChangesetView)
|> render("error.json", changeset: changeset)
end
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(HelloWeb.ErrorView)
|> render(:"404")
end
end
```
You can see how the first clause of the `call/2` function handles the `{:error, changeset}` case, setting the status code to unprocessable entity (422), and then rendering "error.json" from the changeset view with the failed changeset.
With this in mind, let's look at our second test for `create`:
```
test "renders errors when data is invalid", %{conn: conn} do
conn = post(conn, Routes.article_path(conn, :create), article: @invalid_attrs)
assert json_response(conn, 422)["errors"] != %{}
end
```
It simply posts to the `create` path with invalid parameters. This makes it return a JSON response, with status code 422, and a response with a non-empty "errors" key.
The `action_fallback` can be extremely useful to reduce boilerplate when designing APIs. You can learn more about the "Action Fallback" in the [Controllers guide](controllers).
### The `delete` action
Finally, the last action we will study is the `delete` action for JSON. Its implementation looks like this:
```
def delete(conn, %{"id" => id}) do
article = News.get_article!(id)
with {:ok, %Article{}} <- News.delete_article(article) do
send_resp(conn, :no_content, "")
end
end
```
The new action simply attempts to delete the article and, if it succeeds, it returns an empty response with status code `:no_content` (204).
The test looks like this:
```
describe "delete article" do
setup [:create_article]
test "deletes chosen article", %{conn: conn, article: article} do
conn = delete(conn, Routes.article_path(conn, :delete, article))
assert response(conn, 204)
assert_error_sent 404, fn ->
get(conn, Routes.article_path(conn, :show, article))
end
end
end
defp create_article(_) do
article = fixture(:article)
%{article: article}
end
```
It setups a new article, then in the test it invokes the `delete` path to delete it, asserting on a 204 response, which is neither JSON nor HTML. Then it verifies that we can no longer access said article.
That's all!
Now that we understand how the scaffolded code and their tests work for both HTML and JSON APIs, we are prepared to move forward in building and maintaining our web applications!
[← Previous Page Testing Contexts](testing_contexts) [Next Page → Testing Channels](testing_channels)
phoenix Phoenix.Socket.InvalidMessageError exception Phoenix.Socket.InvalidMessageError exception
=============================================
Raised when the socket message is invalid.
phoenix mix phx.gen.auth mix phx.gen.auth
=================
Generates authentication logic for a resource.
```
$ mix phx.gen.auth Accounts User users
```
The first argument is the context module followed by the schema module and its plural name (used as the schema table name).
Additional information and security considerations are detailed in the [`mix phx.gen.auth` guide](mix_phx_gen_auth).
Password hashing
-----------------
The password hashing mechanism defaults to `bcrypt` for Unix systems and `pbkdf2` for Windows systems. Both systems use the [Comeonin interface](https://hexdocs.pm/comeonin/).
The password hashing mechanism can be overridden with the `--hashing-lib` option. The following values are supported:
* `bcrypt` - [bcrypt\_elixir](https://hex.pm/packages/bcrypt_elixir)
* `pbkdf2` - [pbkdf2\_elixir](https://hex.pm/packages/pbkdf2_elixir)
* `argon2` - [argon2\_elixir](https://hex.pm/packages/argon2_elixir)
We recommend developers to consider using `argon2`, which is the most robust of all 3. The downside is that `argon2` is quite CPU and memory intensive, and you will need more powerful instances to run your applications on.
For more information about choosing these libraries, see the [Comeonin project](https://github.com/riverrun/comeonin).
Web namespace
--------------
By default, the controllers and view will be namespaced by the schema name. You can customize the web module namespace by passing the `--web` flag with a module name, for example:
```
$ mix phx.gen.auth Accounts User users --web Warehouse
```
Which would generate the controllers, views, templates and associated tests nested in the `MyAppWeb.Warehouse` namespace:
* `lib/my_app_web/controllers/warehouse/user_auth.ex`
* `lib/my_app_web/controllers/warehouse/user_confirmation_controller.ex`
* `lib/my_app_web/views/warehouse/user_confirmation_view.ex`
* `lib/my_app_web/templates/warehouse/user_confirmation/new.html.heex`
* `test/my_app_web/controllers/warehouse/user_auth_test.exs`
* `test/my_app_web/controllers/warehouse/user_confirmation_controller_test.exs`
* and so on...
Binary ids
-----------
The `--binary-id` option causes the generated migration to use `binary_id` for its primary key and foreign keys.
Default options
----------------
This generator uses default options provided in the `:generators` configuration of your application. These are the defaults:
```
config :your_app, :generators,
binary_id: false,
sample_binary_id: "11111111-1111-1111-1111-111111111111"
```
You can override those options per invocation by providing corresponding switches, e.g. `--no-binary-id` to use normal ids despite the default configuration.
Custom table names
-------------------
By default, the table name for the migration and schema will be the plural name provided for the resource. To customize this value, a `--table` option may be provided. For example:
```
$ mix phx.gen.auth Accounts User users --table accounts_users
```
This will cause the generated tables to be named `"accounts_users"` and `"accounts_users_tokens"`.
| programming_docs |
phoenix Phoenix.Router Phoenix.Router
===============
Defines a Phoenix router.
The router provides a set of macros for generating routes that dispatch to specific controllers and actions. Those macros are named after HTTP verbs. For example:
```
defmodule MyAppWeb.Router do
use Phoenix.Router
get "/pages/:page", PageController, :show
end
```
The [`get/3`](#get/3) macro above accepts a request to `/pages/hello` and dispatches it to `PageController`'s `show` action with `%{"page" => "hello"}` in `params`.
Phoenix's router is extremely efficient, as it relies on Elixir pattern matching for matching routes and serving requests.
Routing
--------
[`get/3`](#get/3), [`post/3`](#post/3), [`put/3`](#put/3) and other macros named after HTTP verbs are used to create routes.
The route:
```
get "/pages", PageController, :index
```
matches a `GET` request to `/pages` and dispatches it to the `index` action in `PageController`.
```
get "/pages/:page", PageController, :show
```
matches `/pages/hello` and dispatches to the `show` action with `%{"page" => "hello"}` in `params`.
```
defmodule PageController do
def show(conn, params) do
# %{"page" => "hello"} == params
end
end
```
Partial and multiple segments can be matched. For example:
```
get "/api/v:version/pages/:id", PageController, :show
```
matches `/api/v1/pages/2` and puts `%{"version" => "1", "id" => "2"}` in `params`. Only the trailing part of a segment can be captured.
Routes are matched from top to bottom. The second route here:
```
get "/pages/:page", PageController, :show
get "/pages/hello", PageController, :hello
```
will never match `/pages/hello` because `/pages/:page` matches that first.
Routes can use glob-like patterns to match trailing segments.
```
get "/pages/*page", PageController, :show
```
matches `/pages/hello/world` and puts the globbed segments in `params["page"]`.
```
GET /pages/hello/world
%{"page" => ["hello", "world"]} = params
```
Globs cannot have prefixes nor suffixes, but can be mixed with variables:
```
get "/pages/he:page/*rest", PageController, :show
```
matches
```
GET /pages/hello
%{"page" => "llo", "rest" => []} = params
GET /pages/hey/there/world
%{"page" => "y", "rest" => ["there" "world"]} = params
```
Helpers
--------
Phoenix automatically generates a module `Helpers` inside your router which contains named helpers to help developers generate and keep their routes up to date.
Helpers are automatically generated based on the controller name. For example, the route:
```
get "/pages/:page", PageController, :show
```
will generate the following named helper:
```
MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
"/pages/hello"
MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
"/pages/hello?some=query"
MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
"http://example.com/pages/hello"
MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
"http://example.com/pages/hello?some=query"
```
If the route contains glob-like patterns, parameters for those have to be given as list:
```
MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, ["hello", "world"])
"/pages/hello/world"
```
The URL generated in the named URL helpers is based on the configuration for `:url`, `:http` and `:https`. However, if for some reason you need to manually control the URL generation, the url helpers also allow you to pass in a [`URI`](https://hexdocs.pm/elixir/URI.html) struct:
```
uri = %URI{scheme: "https", host: "other.example.com"}
MyAppWeb.Router.Helpers.page_url(uri, :show, "hello")
"https://other.example.com/pages/hello"
```
The named helper can also be customized with the `:as` option. Given the route:
```
get "/pages/:page", PageController, :show, as: :special_page
```
the named helper will be:
```
MyAppWeb.Router.Helpers.special_page_path(conn, :show, "hello")
"/pages/hello"
```
Scopes and Resources
---------------------
It is very common in Phoenix applications to namespace all of your routes under the application scope:
```
scope "/", MyAppWeb do
get "/pages/:id", PageController, :show
end
```
The route above will dispatch to `MyAppWeb.PageController`. This syntax is not only convenient for developers, since we don't have to repeat the `MyAppWeb.` prefix on all routes, but it also allows Phoenix to put less pressure on the Elixir compiler. If instead we had written:
```
get "/pages/:id", MyAppWeb.PageController, :show
```
The Elixir compiler would infer that the router depends directly on `MyAppWeb.PageController`, which is not true. By using scopes, Phoenix can properly hint to the Elixir compiler the controller is not an actual dependency of the router. This provides more efficient compilation times.
Scopes allow us to scope on any path or even on the helper name:
```
scope "/api/v1", MyAppWeb, as: :api_v1 do
get "/pages/:id", PageController, :show
end
```
For example, the route above will match on the path `"/api/v1/pages/:id"` and the named route will be `api_v1_page_path`, as expected from the values given to [`scope/2`](#scope/2) option.
Phoenix also provides a [`resources/4`](#resources/4) macro that allows developers to generate "RESTful" routes to a given resource:
```
defmodule MyAppWeb.Router do
use Phoenix.Router
resources "/pages", PageController, only: [:show]
resources "/users", UserController, except: [:delete]
end
```
Finally, Phoenix ships with a [`mix phx.routes`](mix.tasks.phx.routes) task that nicely formats all routes in a given router. We can use it to verify all routes included in the router above:
```
$ mix phx.routes
page_path GET /pages/:id PageController.show/2
user_path GET /users UserController.index/2
user_path GET /users/:id/edit UserController.edit/2
user_path GET /users/new UserController.new/2
user_path GET /users/:id UserController.show/2
user_path POST /users UserController.create/2
user_path PATCH /users/:id UserController.update/2
PUT /users/:id UserController.update/2
```
One can also pass a router explicitly as an argument to the task:
```
$ mix phx.routes MyAppWeb.Router
```
Check [`scope/2`](#scope/2) and [`resources/4`](#resources/4) for more information.
Pipelines and plugs
--------------------
Once a request arrives at the Phoenix router, it performs a series of transformations through pipelines until the request is dispatched to a desired end-point.
Such transformations are defined via plugs, as defined in the [Plug](https://github.com/elixir-lang/plug) specification. Once a pipeline is defined, it can be piped through per scope.
For example:
```
defmodule MyAppWeb.Router do
use Phoenix.Router
pipeline :browser do
plug :fetch_session
plug :accepts, ["html"]
end
scope "/" do
pipe_through :browser
# browser related routes and resources
end
end
```
[`Phoenix.Router`](phoenix.router#content) imports functions from both [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) and [`Phoenix.Controller`](phoenix.controller) to help define plugs. In the example above, `fetch_session/2` comes from [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) while `accepts/2` comes from [`Phoenix.Controller`](phoenix.controller).
Note that router pipelines are only invoked after a route is found. No plug is invoked in case no matches were found.
Summary
========
Functions
----------
[connect(path, plug, plug\_opts, options \\ [])](#connect/4) Generates a route to handle a connect request to the given path.
[delete(path, plug, plug\_opts, options \\ [])](#delete/4) Generates a route to handle a delete request to the given path.
[forward(path, plug, plug\_opts \\ [], router\_opts \\ [])](#forward/4) Forwards a request at the given path to a plug.
[get(path, plug, plug\_opts, options \\ [])](#get/4) Generates a route to handle a get request to the given path.
[head(path, plug, plug\_opts, options \\ [])](#head/4) Generates a route to handle a head request to the given path.
[match(verb, path, plug, plug\_opts, options \\ [])](#match/5) Generates a route match based on an arbitrary HTTP method.
[options(path, plug, plug\_opts, options \\ [])](#options/4) Generates a route to handle a options request to the given path.
[patch(path, plug, plug\_opts, options \\ [])](#patch/4) Generates a route to handle a patch request to the given path.
[pipe\_through(pipes)](#pipe_through/1) Defines a list of plugs (and pipelines) to send the connection through.
[pipeline(plug, list)](#pipeline/2) Defines a plug pipeline.
[plug(plug, opts \\ [])](#plug/2) Defines a plug inside a pipeline.
[post(path, plug, plug\_opts, options \\ [])](#post/4) Generates a route to handle a post request to the given path.
[put(path, plug, plug\_opts, options \\ [])](#put/4) Generates a route to handle a put request to the given path.
[resources(path, controller)](#resources/2) See [`resources/4`](#resources/4).
[resources(path, controller, opts)](#resources/3) See [`resources/4`](#resources/4).
[resources(path, controller, opts, list)](#resources/4) Defines "RESTful" routes for a resource.
[route\_info(router, method, path, host)](#route_info/4) Returns the compile-time route info and runtime path params for a request.
[routes(router)](#routes/1) Returns all routes information from the given router.
[scope(options, list)](#scope/2) Defines a scope in which routes can be nested.
[scope(path, options, list)](#scope/3) Define a scope with the given path.
[scope(path, alias, options, list)](#scope/4) Defines a scope with the given path and alias.
[scoped\_alias(router\_module, alias)](#scoped_alias/2) Returns the full alias with the current scope's aliased prefix.
[trace(path, plug, plug\_opts, options \\ [])](#trace/4) Generates a route to handle a trace request to the given path.
Functions
==========
### connect(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a connect request to the given path.
```
connect("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### delete(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a delete request to the given path.
```
delete("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### forward(path, plug, plug\_opts \\ [], router\_opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L1008)
Forwards a request at the given path to a plug.
All paths that match the forwarded prefix will be sent to the forwarded plug. This is useful for sharing a router between applications or even breaking a big router into smaller ones. The router pipelines will be invoked prior to forwarding the connection.
However, we don't advise forwarding to another endpoint. The reason is that plugs defined by your app and the forwarded endpoint would be invoked twice, which may lead to errors.
#### Examples
```
scope "/", MyApp do
pipe_through [:browser, :admin]
forward "/admin", SomeLib.AdminDashboard
forward "/api", ApiRouter
end
```
### get(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a get request to the given path.
```
get("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### head(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a head request to the given path.
```
head("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### match(verb, path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L573)
Generates a route match based on an arbitrary HTTP method.
Useful for defining routes not included in the builtin macros.
The catch-all verb, `:*`, may also be used to match all HTTP methods.
#### Options
* `:as` - configures the named helper exclusively. If false, does not generate a helper.
* `:alias` - configure if the scope alias should be applied to the route. Defaults to true, disables scoping if false.
* `:log` - the level to log the route dispatching under, may be set to false. Defaults to `:debug`
* `:host` - a string containing the host scope, or prefix host scope, ie `"foo.bar.com"`, `"foo."`
* `:private` - a map of private data to merge into the connection when a route matches
* `:assigns` - a map of data to merge into the connection when a route matches
* `:metadata` - a map of metadata used by the telemetry events and returned by [`route_info/4`](#route_info/4)
* `:trailing_slash` - a boolean to flag whether or not the helper functions append a trailing slash. Defaults to `false`.
#### Examples
```
match(:move, "/events/:id", EventController, :move)
match(:*, "/any", SomeController, :any)
```
### options(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a options request to the given path.
```
options("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### patch(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a patch request to the given path.
```
patch("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### pipe\_through(pipes)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L720)
Defines a list of plugs (and pipelines) to send the connection through.
See [`pipeline/2`](#pipeline/2) for more information.
### pipeline(plug, list)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L627)
Defines a plug pipeline.
Pipelines are defined at the router root and can be used from any scope.
#### Examples
```
pipeline :api do
plug :token_authentication
plug :dispatch
end
```
A scope may then use this pipeline as:
```
scope "/" do
pipe_through :api
end
```
Every time [`pipe_through/1`](#pipe_through/1) is called, the new pipelines are appended to the ones previously given.
### plug(plug, opts \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L678)
Defines a plug inside a pipeline.
See [`pipeline/2`](#pipeline/2) for more information.
### post(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a post request to the given path.
```
post("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### put(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a put request to the given path.
```
put("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
### resources(path, controller)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L831)
See [`resources/4`](#resources/4).
### resources(path, controller, opts)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L820)
See [`resources/4`](#resources/4).
### resources(path, controller, opts, list)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L813)
Defines "RESTful" routes for a resource.
The given definition:
```
resources "/users", UserController
```
will include routes to the following actions:
* `GET /users` => `:index`
* `GET /users/new` => `:new`
* `POST /users` => `:create`
* `GET /users/:id` => `:show`
* `GET /users/:id/edit` => `:edit`
* `PATCH /users/:id` => `:update`
* `PUT /users/:id` => `:update`
* `DELETE /users/:id` => `:delete`
#### Options
This macro accepts a set of options:
* `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
* `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
* `:param` - the name of the parameter for this resource, defaults to `"id"`
* `:name` - the prefix for this resource. This is used for the named helper and as the prefix for the parameter in nested resources. The default value is automatically derived from the controller name, i.e. `UserController` will have name `"user"`
* `:as` - configures the named helper exclusively
* `:singleton` - defines routes for a singleton resource that is looked up by the client without referencing an ID. Read below for more information
#### Singleton resources
When a resource needs to be looked up without referencing an ID, because it contains only a single entry in the given context, the `:singleton` option can be used to generate a set of routes that are specific to such single resource:
* `GET /user` => `:show`
* `GET /user/new` => `:new`
* `POST /user` => `:create`
* `GET /user/edit` => `:edit`
* `PATCH /user` => `:update`
* `PUT /user` => `:update`
* `DELETE /user` => `:delete`
Usage example:
```
resources "/account", AccountController, only: [:show], singleton: true
```
#### Nested Resources
This macro also supports passing a nested block of route definitions. This is helpful for nesting children resources within their parents to generate nested routes.
The given definition:
```
resources "/users", UserController do
resources "/posts", PostController
end
```
will include the following routes:
```
user_post_path GET /users/:user_id/posts PostController :index
user_post_path GET /users/:user_id/posts/:id/edit PostController :edit
user_post_path GET /users/:user_id/posts/new PostController :new
user_post_path GET /users/:user_id/posts/:id PostController :show
user_post_path POST /users/:user_id/posts PostController :create
user_post_path PATCH /users/:user_id/posts/:id PostController :update
PUT /users/:user_id/posts/:id PostController :update
user_post_path DELETE /users/:user_id/posts/:id PostController :delete
```
### route\_info(router, method, path, host)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L1054)
Returns the compile-time route info and runtime path params for a request.
The `path` can be either a string or the `path_info` segments.
A map of metadata is returned with the following keys:
* `:log` - the configured log level. For example `:debug`
* `:path_params` - the map of runtime path params
* `:pipe_through` - the list of pipelines for the route's scope, for example `[:browser]`
* `:plug` - the plug to dispatch the route to, for example `AppWeb.PostController`
* `:plug_opts` - the options to pass when calling the plug, for example: `:index`
* `:route` - the string route pattern, such as `"/posts/:id"`
#### Examples
```
iex> Phoenix.Router.route_info(AppWeb.Router, "GET", "/posts/123", "myhost")
%{
log: :debug,
path_params: %{"id" => "123"},
pipe_through: [:browser],
plug: AppWeb.PostController,
plug_opts: :show,
route: "/posts/:id",
}
iex> Phoenix.Router.route_info(MyRouter, "GET", "/not-exists", "myhost")
:error
```
### routes(router)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L1021)
Returns all routes information from the given router.
### scope(options, list)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L882)
Defines a scope in which routes can be nested.
#### Examples
```
scope path: "/api/v1", as: :api_v1, alias: API.V1 do
get "/pages/:id", PageController, :show
end
```
The generated route above will match on the path `"/api/v1/pages/:id"` and will dispatch to `:show` action in `API.V1.PageController`. A named helper `api_v1_page_path` will also be generated.
#### Options
The supported options are:
* `:path` - a string containing the path scope.
* `:as` - a string or atom containing the named helper scope. When set to false, it resets the nested helper scopes.
* `:alias` - an alias (atom) containing the controller scope. When set to false, it resets all nested aliases.
* `:host` - a string containing the host scope, or prefix host scope, ie `"foo.bar.com"`, `"foo."`
* `:private` - a map of private data to merge into the connection when a route matches
* `:assigns` - a map of data to merge into the connection when a route matches
* `:log` - the level to log the route dispatching under, may be set to false. Defaults to `:debug`
* `:trailing_slash` - whether or not the helper functions append a trailing slash. Defaults to `false`.
### scope(path, options, list)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L909)
Define a scope with the given path.
This function is a shortcut for:
```
scope path: path do
...
end
```
#### Examples
```
scope "/api/v1", as: :api_v1 do
get "/pages/:id", PageController, :show
end
```
### scope(path, alias, options, list)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L946)
Defines a scope with the given path and alias.
This function is a shortcut for:
```
scope path: path, alias: alias do
...
end
```
#### Examples
```
scope "/api/v1", API.V1, as: :api_v1 do
get "/pages/:id", PageController, :show
end
```
### scoped\_alias(router\_module, alias)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L981)
Returns the full alias with the current scope's aliased prefix.
Useful for applying the same short-hand alias handling to other values besides the second argument in route definitions.
#### Examples
```
scope "/", MyPrefix do
get "/", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)
end
```
### trace(path, plug, plug\_opts, options \\ [])[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/router.ex#L585)
Generates a route to handle a trace request to the given path.
```
trace("/events/:id", EventController, :action)
```
See [`match/5`](#match/5) for options.
| programming_docs |
phoenix Controllers Controllers
============
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [request life-cycle guide](request_lifecycle).
>
>
Phoenix controllers act as intermediary modules. Their functions — called actions — are invoked from the router in response to HTTP requests. The actions, in turn, gather all the necessary data and perform all the necessary steps before invoking the view layer to render a template or returning a JSON response.
Phoenix controllers also build on the Plug package, and are themselves plugs. Controllers provide the functions to do almost anything we need to in an action. If we do find ourselves looking for something that Phoenix controllers don't provide, we might find what we're looking for in Plug itself. Please see the [Plug guide](plug) or the [Plug documentation](https://hexdocs.pm/plug/1.13.6/Plug.html) for more information.
A newly generated Phoenix app will have a single controller named `PageController`, which can be found at `lib/hello_web/controllers/page_controller.ex` which looks like this:
```
defmodule HelloWeb.PageController do
use HelloWeb, :controller
def index(conn, _params) do
render(conn, "index.html")
end
end
```
The first line below the module definition invokes the `__using__/1` macro of the `HelloWeb` module, which imports some useful modules.
`PageController` gives us the `index` action to display the Phoenix [welcome page](http://localhost:4000/) associated with the default route Phoenix defines in the router.
Actions
--------
Controller actions are just functions. We can name them anything we like as long as they follow Elixir's naming rules. The only requirement we must fulfill is that the action name matches a route defined in the router.
For example, in `lib/hello_web/router.ex` we could change the action name in the default route that Phoenix gives us in a new app from `index`:
```
get "/", PageController, :index
```
to `home`:
```
get "/", PageController, :home
```
as long as we change the action name in `PageController` to `home` as well, the [welcome page](http://localhost:4000/) will load as before.
```
defmodule HelloWeb.PageController do
...
def home(conn, _params) do
render(conn, "index.html")
end
end
```
While we can name our actions whatever we like, there are conventions for action names which we should follow whenever possible. We went over these in the [routing guide](routing), but we'll take another quick look here.
* index - renders a list of all items of the given resource type
* show - renders an individual item by ID
* new - renders a form for creating a new item
* create - receives parameters for one new item and saves it in a data store
* edit - retrieves an individual item by ID and displays it in a form for editing
* update - receives parameters for one edited item and saves the item to a data store
* delete - receives an ID for an item to be deleted and deletes it from a data store
Each of these actions takes two parameters, which will be provided by Phoenix behind the scenes.
The first parameter is always `conn`, a struct which holds information about the request such as the host, path elements, port, query string, and much more. `conn` comes to Phoenix via Elixir's Plug middleware framework. More detailed information about `conn` can be found in the [Plug.Conn documentation](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html).
The second parameter is `params`. Not surprisingly, this is a map which holds any parameters passed along in the HTTP request. It is a good practice to pattern match against parameters in the function signature to provide data in a simple package we can pass on to rendering. We saw this in the [request life-cycle guide](request_lifecycle) when we added a messenger parameter to our `show` route in `lib/hello_web/controllers/hello_controller.ex`.
```
defmodule HelloWeb.HelloController do
...
def show(conn, %{"messenger" => messenger}) do
render(conn, "show.html", messenger: messenger)
end
end
```
In some cases — often in `index` actions, for instance — we don't care about parameters because our behavior doesn't depend on them. In those cases, we don't use the incoming parameters, and simply prefix the variable name with an underscore, calling it `_params`. This will keep the compiler from complaining about the unused variable while still keeping the correct arity.
Rendering
----------
Controllers can render content in several ways. The simplest is to render some plain text using the [`text/2`](phoenix.controller#text/2) function which Phoenix provides.
For example, let's rewrite the `show` action from `HelloController` to return text instead. For that, we could do the following.
```
def show(conn, %{"messenger" => messenger}) do
text(conn, "From messenger #{messenger}")
end
```
Now [`/hello/Frank`](http://localhost:4000/hello/Frank) in your browser should display `From messenger Frank` as plain text without any HTML.
A step beyond this is rendering pure JSON with the [`json/2`](phoenix.controller#json/2) function. We need to pass it something that the [Jason library](https://hexdocs.pm/jason/1.3.0/Jason.html) can decode into JSON, such as a map. (Jason is one of Phoenix's dependencies.)
```
def show(conn, %{"messenger" => messenger}) do
json(conn, %{id: messenger})
end
```
If we again visit [`/hello/Frank`](http://localhost:4000/hello/Frank) in the browser, we should see a block of JSON with the key `id` mapped to the string `"Frank"`.
```
{"id": "Frank"}
```
The [`json/2`](phoenix.controller#json/2) function is useful for writing APIs and there is also the [`html/2`](phoenix.controller#html/2) function for rendering HTML, but most of the times we use Phoenix views to build our responses. For this, Phoenix includes the [`render/3`](phoenix.controller#render/3) function. It is specially important for HTML responses, as Phoenix Views provide performance and security benefits.
Let's rollback our `show` action to what we originally wrote in the [request life-cycle guide](request_lifecycle):
```
defmodule HelloWeb.HelloController do
use HelloWeb, :controller
def show(conn, %{"messenger" => messenger}) do
render(conn, "show.html", messenger: messenger)
end
end
```
In order for the [`render/3`](phoenix.controller#render/3) function to work correctly, the controller and view must share the same root name (in this case `Hello`), and it also must have the same root name as the template directory (in this case `hello`) where the `show.html.heex` template lives. In other words, `HelloController` requires `HelloView`, and `HelloView` requires the existence of the `lib/hello_web/templates/hello` directory, which must contain the `show.html.heex` template.
[`render/3`](phoenix.controller#render/3) will also pass the value which the `show` action received for `messenger` from the parameters as an assign.
If we need to pass values into the template when using `render`, that's easy. We can pass a keyword like we've seen with `messenger: messenger`, or we can use [`Plug.Conn.assign/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#assign/3), which conveniently returns `conn`.
```
def show(conn, %{"messenger" => messenger}) do
conn
|> Plug.Conn.assign(:messenger, messenger)
|> render("show.html")
end
```
Note: Using [`Phoenix.Controller`](phoenix.controller) imports [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html), so shortening the call to [`assign/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#assign/3) works just fine.
Passing more than one value to our template is as simple as connecting [`assign/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#assign/3) functions together:
```
def show(conn, %{"messenger" => messenger}) do
conn
|> assign(:messenger, messenger)
|> assign(:receiver, "Dweezil")
|> render("show.html")
end
```
Generally speaking, once all assigns are configured, we invoke the view layer. The view layer then renders `show.html` alongside the layout and a response is sent back to the browser.
[Views and templates](views) have their own guide, so we won't spend much time on them here. What we will look at is how to assign a different layout, or none at all, from inside a controller action.
### Assigning layouts
Layouts are just a special subset of templates. They live in the `templates/layout` folder (`lib/hello_web/templates/layout`). Phoenix created three for us when we generated our app. The default *root layout* is called `root.html.heex`, and it is the layout into which all templates will be rendered by default.
Since layouts are really just templates, they need a view to render them. This one is `LayoutView` which is defined in `lib/hello_web/views/layout_view.ex`. Since Phoenix generated this view for us, we won't have to create a new one as long as we put the layouts we want to render inside the `lib/hello_web/templates/layout` directory.
Before we create a new layout, though, let's do the simplest possible thing and render a template with no layout at all.
The [`Phoenix.Controller`](phoenix.controller) module provides the [`put_root_layout/2`](phoenix.controller#put_root_layout/2) function for us to switch *root layouts*. This takes `conn` as its first argument and a string for the basename of the layout we want to render. It also accepts `false` to disable the layout altogether.
You can edit the `index` action of `PageController` in `lib/hello_web/controllers/page_controller.ex` to look like this.
```
def index(conn, _params) do
conn
|> put_root_layout(false)
|> render("index.html")
end
```
After reloading <http://localhost:4000/>, we should see a very different page, one with no title, logo image, or CSS styling at all.
Now let's actually create another layout and render the index template into it. As an example, let's say we had a different layout for the admin section of our application which didn't have the logo image. To do this, let's copy the existing `root.html.heex` to a new file `admin.html.heex` in the same directory `lib/hello_web/templates/layout`. Then let's replace the lines in `admin.html.heex` that displays the logo with the word "Administration".
Remove these lines:
```
<a href="https://phoenixframework.org/" class="phx-logo">
<img src={Routes.static_path(@conn, "/images/phoenix.png")} alt="Phoenix Framework Logo"/>
</a>
```
Replace them with:
```
<p>Administration</p>
```
Then, pass the basename of the new layout into [`put_root_layout/2`](phoenix.controller#put_root_layout/2) in our `index` action in `lib/hello_web/controllers/page_controller.ex`.
```
def index(conn, _params) do
conn
|> put_root_layout("admin.html")
|> render("index.html")
end
```
When we load the page, we should be rendering the admin layout without a logo and with the word "Administration".
### Overriding rendering formats
Rendering HTML through a template is fine, but what if we need to change the rendering format on the fly? Let's say that sometimes we need HTML, sometimes we need plain text, and sometimes we need JSON. Then what?
Phoenix allows us to change formats on the fly with the `_format` query string parameter. To make this happen, Phoenix requires an appropriately named view and an appropriately named template in the correct directory.
As an example, let's take `PageController`'s `index` action from a newly generated app. Out of the box, this has the right view `PageView`, the right templates directory (`lib/hello_web/templates/page`), and the right template for rendering HTML (`index.html.heex`.)
```
def index(conn, _params) do
render(conn, "index.html")
end
```
What it doesn't have is an alternative template for rendering text. Let's add one at `lib/hello_web/templates/page/index.text.eex`. Here is our example `index.text.eex` template.
```
OMG, this is actually some text.
```
There are just a few more things we need to do to make this work. We need to tell our router that it should accept the `text` format. We do that by adding `text` to the list of accepted formats in the `:browser` pipeline. Let's open up `lib/hello_web/router.ex` and change `plug :accepts` to include `text` as well as `html` like this.
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html", "text"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
...
```
We also need to tell the controller to render a template with the same format as the one returned by [`Phoenix.Controller.get_format/1`](phoenix.controller#get_format/1). We do that by substituting the name of the template "index.html" with the atom version `:index`.
```
def index(conn, _params) do
render(conn, :index)
end
```
If we go to [`http://localhost:4000/?_format=text`](http://localhost:4000/?_format=text), we will see "OMG, this is actually some text.".
### Sending responses directly
If none of the rendering options above quite fits our needs, we can compose our own using some of the functions that [`Plug`](https://hexdocs.pm/plug/1.13.6/Plug.html) gives us. Let's say we want to send a response with a status of "201" and no body whatsoever. We can do that with the [`Plug.Conn.send_resp/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#send_resp/3) function.
Edit the `index` action of `PageController` in `lib/hello_web/controllers/page_controller.ex` to look like this:
```
def index(conn, _params) do
send_resp(conn, 201, "")
end
```
Reloading <http://localhost:4000> should show us a completely blank page. The network tab of our browser's developer tools should show a response status of "201" (Created). Some browsers (Safari) will download the response, as the content type is not set.
To be specific about the content type, we can use [`put_resp_content_type/2`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#put_resp_content_type/2) in conjunction with [`send_resp/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#send_resp/3).
```
def index(conn, _params) do
conn
|> put_resp_content_type("text/plain")
|> send_resp(201, "")
end
```
Using [`Plug`](https://hexdocs.pm/plug/1.13.6/Plug.html) functions in this way, we can craft just the response we need.
### Setting the Content Type
Analogous to the `_format` query string param, we can render any sort of format we want by modifying the HTTP Content-Type Header and providing the appropriate template.
If we wanted to render an XML version of our `index` action, we might implement the action like this in `lib/hello_web/page_controller.ex`.
```
def index(conn, _params) do
conn
|> put_resp_content_type("text/xml")
|> render("index.xml", content: some_xml_content)
end
```
We would then need to provide an `index.xml.eex` template which created valid XML, and we would be done.
For a list of valid content mime-types, please see the [`MIME`](https://hexdocs.pm/mime/2.0.2/MIME.html) library.
### Setting the HTTP Status
We can also set the HTTP status code of a response similarly to the way we set the content type. The [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) module, imported into all controllers, has a `put_status/2` function to do this.
[`Plug.Conn.put_status/2`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#put_status/2) takes `conn` as the first parameter and as the second parameter either an integer or a "friendly name" used as an atom for the status code we want to set. The list of status code atom representations can be found in [`Plug.Conn.Status.code/1`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.Status.html#code/1) documentation.
Let's change the status in our `PageController` `index` action.
```
def index(conn, _params) do
conn
|> put_status(202)
|> render("index.html")
end
```
The status code we provide must be a valid number.
Redirection
------------
Often, we need to redirect to a new URL in the middle of a request. A successful `create` action, for instance, will usually redirect to the `show` action for the resource we just created. Alternately, it could redirect to the `index` action to show all the things of that same type. There are plenty of other cases where redirection is useful as well.
Whatever the circumstance, Phoenix controllers provide the handy [`redirect/2`](phoenix.controller#redirect/2) function to make redirection easy. Phoenix differentiates between redirecting to a path within the application and redirecting to a URL — either within our application or external to it.
In order to try out [`redirect/2`](phoenix.controller#redirect/2), let's create a new route in `lib/hello_web/router.ex`.
```
defmodule HelloWeb.Router do
...
scope "/", HelloWeb do
...
get "/", PageController, :index
get "/redirect_test", PageController, :redirect_test
...
end
end
```
Then we'll change `PageController`'s `index` action of our controller to do nothing but to redirect to our new route.
```
defmodule HelloWeb.PageController do
use HelloWeb, :controller
def index(conn, _params) do
redirect(conn, to: "/redirect_test")
end
end
```
Actually, we should make use of the path helpers, which are the preferred approach to link to any page within our application, as we learned about in the [routing guide](routing).
```
def index(conn, _params) do
redirect(conn, to: Routes.page_path(conn, :redirect_test))
end
```
Finally, let's define in the same file the action we redirect to, which simply renders the index, but now under a new address:
```
def redirect_test(conn, _params) do
render(conn, "index.html")
end
```
When we reload our [welcome page](http://localhost:4000/), we see that we've been redirected to `/redirect_test` which shows the original welcome page. It works!
If we care to, we can open up our developer tools, click on the network tab, and visit our root route again. We see two main requests for this page - a get to `/` with a status of `302`, and a get to `/redirect_test` with a status of `200`.
Notice that the redirect function takes `conn` as well as a string representing a relative path within our application. For security reasons, the `:to` helper can only redirect to paths within your application. If you want to redirect to a fully-qualified path or an external URL, you should use `:external` instead:
```
def index(conn, _params) do
redirect(conn, external: "https://elixir-lang.org/")
end
```
Flash messages
---------------
Sometimes we need to communicate with users during the course of an action. Maybe there was an error updating a schema, or maybe we just want to welcome them back to the application. For this, we have flash messages.
The [`Phoenix.Controller`](phoenix.controller) module provides the [`put_flash/3`](phoenix.controller#put_flash/3) and [`get_flash/2`](phoenix.controller#get_flash/2) functions to help us set and retrieve flash messages as a key-value pair. Let's set two flash messages in our `HelloWeb.PageController` to try this out.
To do this we modify the `index` action as follows:
```
defmodule HelloWeb.PageController do
...
def index(conn, _params) do
conn
|> put_flash(:info, "Welcome to Phoenix, from flash info!")
|> put_flash(:error, "Let's pretend we have an error.")
|> render("index.html")
end
end
```
In order to see our flash messages, we need to be able to retrieve them and display them in a template layout. One way to do the first part is with [`get_flash/2`](phoenix.controller#get_flash/2) which takes `conn` and the key we care about. It then returns the value for that key.
For our convenience, the application layout, `lib/hello_web/templates/layout/app.html.heex`, already has markup for displaying flash messages.
```
<p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
<p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p>
```
When we reload the [welcome page](http://localhost:4000/), our messages should appear just above "Welcome to Phoenix!"
The flash functionality is handy when mixed with redirects. Perhaps you want to redirect to a page with some extra information. If we reuse the redirect action from the previous section, we can do:
```
def index(conn, _params) do
conn
|> put_flash(:info, "Welcome to Phoenix, from flash info!")
|> put_flash(:error, "Let's pretend we have an error.")
|> redirect(to: Routes.page_path(conn, :redirect_test))
end
```
Now if you reload the [welcome page](http://localhost:4000/), you will be redirected and the flash messages will be shown once more.
Besides [`put_flash/3`](phoenix.controller#put_flash/3) and [`get_flash/2`](phoenix.controller#get_flash/2), the [`Phoenix.Controller`](phoenix.controller) module has another useful function worth knowing about. [`clear_flash/1`](phoenix.controller#clear_flash/1) takes only `conn` and removes any flash messages which might be stored in the session.
Phoenix does not enforce which keys are stored in the flash. As long as we are internally consistent, all will be well. `:info` and `:error`, however, are common and are handled by default in our templates.
Action fallback
----------------
Action fallback allows us to centralize error handling code in plugs, which are called when a controller action fails to return a [`%Plug.Conn{}`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#t:t/0) struct. These plugs receive both the `conn` which was originally passed to the controller action along with the return value of the action.
Let's say we have a `show` action which uses [`with`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1) to fetch a blog post and then authorize the current user to view that blog post. In this example we might expect `fetch_post/1` to return `{:error, :not_found}` if the post is not found and `authorize_user/3` might return `{:error, :unauthorized}` if the user is unauthorized. We could use `ErrorView` which is generated by Phoenix for every new application to handle these error paths accordingly:
```
defmodule HelloWeb.MyController do
use Phoenix.Controller
def show(conn, %{"id" => id}, current_user) do
with {:ok, post} <- fetch_post(id),
:ok <- authorize_user(current_user, :view, post) do
render(conn, "show.json", post: post)
else
{:error, :not_found} ->
conn
|> put_status(:not_found)
|> put_view(HelloWeb.ErrorView)
|> render(:"404")
{:error, :unauthorized} ->
conn
|> put_status(403)
|> put_view(HelloWeb.ErrorView)
|> render(:"403")
end
end
end
```
Now imagine you may need to implement similar logic for every controller and action handled by your API. This would result in a lot of repetition.
Instead we can define a module plug which knows how to handle these error cases specifically. Since controllers are module plugs, let's define our plug as a controller:
```
defmodule HelloWeb.MyFallbackController do
use Phoenix.Controller
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(HelloWeb.ErrorView)
|> render(:"404")
end
def call(conn, {:error, :unauthorized}) do
conn
|> put_status(403)
|> put_view(HelloWeb.ErrorView)
|> render(:"403")
end
end
```
Then we can reference our new controller as the `action_fallback` and simply remove the `else` block from our `with`:
```
defmodule HelloWeb.MyController do
use Phoenix.Controller
action_fallback HelloWeb.MyFallbackController
def show(conn, %{"id" => id}, current_user) do
with {:ok, post} <- fetch_post(id),
:ok <- authorize_user(current_user, :view, post) do
render(conn, "show.json", post: post)
end
end
end
```
Whenever the `with` conditions do not match, `HelloWeb.MyFallbackController` will receive the original `conn` as well as the result of the action and respond accordingly.
[← Previous Page Routing](routing) [Next Page → Views and templates](views)
| programming_docs |
phoenix mix phx.gen.schema mix phx.gen.schema
===================
Generates an Ecto schema and migration.
```
$ mix phx.gen.schema Blog.Post blog_posts title:string views:integer
```
The first argument is the schema module followed by its plural name (used as the table name).
The generated schema above will contain:
* a schema file in `lib/my_app/blog/post.ex`, with a `blog_posts` table
* a migration file for the repository
The generated migration can be skipped with `--no-migration`.
Contexts
---------
Your schemas can be generated and added to a separate OTP app. Make sure your configuration is properly setup or manually specify the context app with the `--context-app` option with the CLI.
Via config:
```
config :marketing_web, :generators, context_app: :marketing
```
Via CLI:
```
$ mix phx.gen.schema Blog.Post blog_posts title:string views:integer --context-app marketing
```
Attributes
-----------
The resource fields are given using `name:type` syntax where type are the types supported by Ecto. Omitting the type makes it default to `:string`:
```
$ mix phx.gen.schema Blog.Post blog_posts title views:integer
```
The following types are supported:
* `:integer`
* `:float`
* `:decimal`
* `:boolean`
* `:map`
* `:string`
* `:array`
* `:references`
* `:text`
* `:date`
* `:time`
* `:time_usec`
* `:naive_datetime`
* `:naive_datetime_usec`
* `:utc_datetime`
* `:utc_datetime_usec`
* `:uuid`
* `:binary`
* `:enum`
* `:datetime` - An alias for `:naive_datetime`
The generator also supports references, which we will properly associate the given column to the primary key column of the referenced table:
```
$ mix phx.gen.schema Blog.Post blog_posts title user_id:references:users
```
This will result in a migration with an `:integer` column of `:user_id` and create an index.
Furthermore an array type can also be given if it is supported by your database, although it requires the type of the underlying array element to be given too:
```
$ mix phx.gen.schema Blog.Post blog_posts tags:array:string
```
Unique columns can be automatically generated by using:
```
$ mix phx.gen.schema Blog.Post blog_posts title:unique unique_int:integer:unique
```
Redact columns can be automatically generated by using:
```
$ mix phx.gen.schema Accounts.Superhero superheroes secret_identity:redact password:string:redact
```
Ecto.Enum fields can be generated by using:
```
$ mix phx.gen.schema Blog.Post blog_posts title status:enum:unpublished:published:deleted
```
If no data type is given, it defaults to a string.
table
------
By default, the table name for the migration and schema will be the plural name provided for the resource. To customize this value, a `--table` option may be provided. For example:
```
$ mix phx.gen.schema Blog.Post posts --table cms_posts
```
binary\_id
-----------
Generated migration can use `binary_id` for schema's primary key and its references with option `--binary-id`.
Default options
----------------
This generator uses default options provided in the `:generators` configuration of your application. These are the defaults:
```
config :your_app, :generators,
migration: true,
binary_id: false,
sample_binary_id: "11111111-1111-1111-1111-111111111111"
```
You can override those options per invocation by providing corresponding switches, e.g. `--no-binary-id` to use normal ids despite the default configuration or `--migration` to force generation of the migration.
phoenix Phoenix.Socket.Reply Phoenix.Socket.Reply
=====================
Defines a reply sent from channels to transports.
The message format requires the following keys:
* `:topic` - The string topic or topic:subtopic pair namespace, for example "messages", "messages:123"
* `:status` - The reply status as an atom
* `:payload` - The reply payload
* `:ref` - The unique string ref
* `:join_ref` - The unique string ref when joining
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/message.ex#L54)
```
@type t() :: %Phoenix.Socket.Reply{
join_ref: term(),
payload: term(),
ref: term(),
status: term(),
topic: term()
}
```
phoenix Ecto Ecto
=====
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
Most web applications today need some form of data validation and persistence. In the Elixir ecosystem, we have [`Ecto`](https://hexdocs.pm/ecto/3.8.2/Ecto.html) to enable this. Before we jump into building database-backed web features, we're going to focus on the finer details of Ecto to give a solid base to build our web features on top of. Let's get started!
Phoenix uses Ecto to provide builtin support to the following databases:
* PostgreSQL (via [`postgrex`](https://github.com/elixir-ecto/postgrex))
* MySQL (via [`myxql`](https://github.com/elixir-ecto/myxql))
* MSSQL (via [`tds`](https://github.com/livehelpnow/tds))
* ETS (via [`etso`](https://github.com/evadne/etso))
* SQLite3 (via [`ecto_sqlite3`](https://github.com/elixir-sqlite/ecto_sqlite3))
Newly generated Phoenix projects include Ecto with the PostgreSQL adapter by default. You can pass the `--database` option to change or `--no-ecto` flag to exclude this.
Ecto also provides support for other databases and it has many learning resources available. Please check out [Ecto's README](https://github.com/elixir-ecto/ecto) for general information.
This guide assumes that we have generated our new application with Ecto integration and that we will be using PostgreSQL. The introductory guides cover how to get your first application up and running. For instructions on switching to MySQL, please see the [Using MySQL](#using-mysql) section.
Using the schema and migration generator
-----------------------------------------
Once we have Ecto and PostgreSQL installed and configured, the easiest way to use Ecto is to generate an Ecto *schema* through the `phx.gen.schema` task. Ecto schemas are a way for us to specify how Elixir data types map to and from external sources, such as database tables. Let's generate a `User` schema with `name`, `email`, `bio`, and `number_of_pets` fields.
```
$ mix phx.gen.schema User users name:string email:string \
bio:string number_of_pets:integer
* creating ./lib/hello/user.ex
* creating priv/repo/migrations/20170523151118_create_users.exs
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
A couple of files were generated with this task. First, we have a `user.ex` file, containing our Ecto schema with our schema definition of the fields we passed to the task. Next, a migration file was generated inside `priv/repo/migrations/` which will create our database table that our schema maps to.
With our files in place, let's follow the instructions and run our migration:
```
$ mix ecto.migrate
Compiling 1 file (.ex)
Generated hello app
[info] == Running Hello.Repo.Migrations.CreateUsers.change/0 forward
[info] create table users
[info] == Migrated in 0.0s
```
Mix assumes that we are in the development environment unless we tell it otherwise with `MIX_ENV=prod mix ecto.migrate`.
If we log in to our database server, and connect to our `hello_dev` database, we should see our `users` table. Ecto assumes that we want an integer column called `id` as our primary key, so we should see a sequence generated for that as well.
```
$ psql -U postgres
Type "help" for help.
postgres=# \connect hello_dev
You are now connected to database "hello_dev" as user "postgres".
hello_dev=# \d
List of relations
Schema | Name | Type | Owner
--------+-------------------+----------+----------
public | schema_migrations | table | postgres
public | users | table | postgres
public | users_id_seq | sequence | postgres
(3 rows)
hello_dev=# \q
```
If we take a look at the migration generated by `phx.gen.schema` in `priv/repo/migrations/`, we'll see that it will add the columns we specified. It will also add timestamp columns for `inserted_at` and `updated_at` which come from the [`timestamps/1`](https://hexdocs.pm/ecto_sql/3.8.1/Ecto.Migration.html#timestamps/1) function.
```
defmodule Hello.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string
add :email, :string
add :bio, :string
add :number_of_pets, :integer
timestamps()
end
end
end
```
And here's what that translates to in the actual `users` table.
```
$ psql
hello_dev=# \d users
Table "public.users"
Column | Type | Modifiers
---------------+-----------------------------+----------------------------------------------------
id | bigint | not null default nextval('users_id_seq'::regclass)
name | character varying(255) |
email | character varying(255) |
bio | character varying(255) |
number_of_pets | integer |
inserted_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
```
Notice that we do get an `id` column as our primary key by default, even though it isn't listed as a field in our migration.
Repo configuration
-------------------
Our `Hello.Repo` module is the foundation we need to work with databases in a Phoenix application. Phoenix generated it for us in `lib/hello/repo.ex`, and this is what it looks like.
```
defmodule Hello.Repo do
use Ecto.Repo,
otp_app: :hello,
adapter: Ecto.Adapters.Postgres
end
```
It begins by defining the repository module. Then it configures our `otp_app` name, and the `adapter` – `Postgres`, in our case.
Our repo has three main tasks - to bring in all the common query functions from [[`Ecto.Repo`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html)], to set the `otp_app` name equal to our application name, and to configure our database adapter. We'll talk more about how to use `Hello.Repo` in a bit.
When `phx.new` generated our application, it included some basic repository configuration as well. Let's look at `config/dev.exs`.
```
...
# Configure your database
config :hello, Hello.Repo,
username: "postgres",
password: "postgres",
hostname: "localhost",
database: "hello_dev",
show_sensitive_data_on_connection_error: true,
pool_size: 10
...
```
We also have similar configuration in `config/test.exs` and `config/runtime.exs` (formerly `config/prod.secret.exs`) which can also be changed to match your actual credentials.
The schema
-----------
Ecto schemas are responsible for mapping Elixir values to external data sources, as well as mapping external data back into Elixir data structures. We can also define relationships to other schemas in our applications. For example, our `User` schema might have many posts, and each post would belong to a user. Ecto also handles data validation and type casting with changesets, which we'll discuss in a moment.
Here's the `User` schema that Phoenix generated for us.
```
defmodule Hello.User do
use Ecto.Schema
import Ecto.Changeset
alias Hello.User
schema "users" do
field :bio, :string
field :email, :string
field :name, :string
field :number_of_pets, :integer
timestamps()
end
@doc false
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :bio, :number_of_pets])
|> validate_required([:name, :email, :bio, :number_of_pets])
end
end
```
Ecto schemas at their core are simply Elixir structs. Our `schema` block is what tells Ecto how to cast our `%User{}` struct fields to and from the external `users` table. Often, the ability to simply cast data to and from the database isn't enough and extra data validation is required. This is where Ecto changesets come in. Let's dive in!
Changesets and validations
---------------------------
Changesets define a pipeline of transformations our data needs to undergo before it will be ready for our application to use. These transformations might include type-casting, user input validation, and filtering out any extraneous parameters. Often we'll use changesets to validate user input before writing it to the database. Ecto repositories are also changeset-aware, which allows them not only to refuse invalid data, but also perform the minimal database updates possible by inspecting the changeset to know which fields have changed.
Let's take a closer look at our default changeset function.
```
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :bio, :number_of_pets])
|> validate_required([:name, :email, :bio, :number_of_pets])
end
```
Right now, we have two transformations in our pipeline. In the first call, we invoke [`Ecto.Changeset.cast/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#cast/3), passing in our external parameters and marking which fields are required for validation.
[`cast/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#cast/3) first takes a struct, then the parameters (the proposed updates), and then the final field is the list of columns to be updated. [`cast/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#cast/3) also will only take fields that exist in the schema.
Next, [`Ecto.Changeset.validate_required/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#validate_required/3) checks that this list of fields is present in the changeset that [`cast/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#cast/3) returns. By default with the generator, all fields are required.
We can verify this functionality in [`IEx`](https://hexdocs.pm/iex/IEx.html). Let's fire up our application inside IEx by running `iex -S mix`. In order to minimize typing and make this easier to read, let's alias our `Hello.User` struct.
```
$ iex -S mix
iex> alias Hello.User
Hello.User
```
Next, let's build a changeset from our schema with an empty `User` struct, and an empty map of parameters.
```
iex> changeset = User.changeset(%User{}, %{})
#Ecto.Changeset<
action: nil,
changes: %{},
errors: [
name: {"can't be blank", [validation: :required]},
email: {"can't be blank", [validation: :required]},
bio: {"can't be blank", [validation: :required]},
number_of_pets: {"can't be blank", [validation: :required]}
],
data: #Hello.User<>,
valid?: false
>
```
Once we have a changeset, we can check if it is valid.
```
iex> changeset.valid?
false
```
Since this one is not valid, we can ask it what the errors are.
```
iex> changeset.errors
[
name: {"can't be blank", [validation: :required]},
email: {"can't be blank", [validation: :required]},
bio: {"can't be blank", [validation: :required]},
number_of_pets: {"can't be blank", [validation: :required]}
]
```
Now, let's make `number_of_pets` optional. In order to do this, we simply remove it from the list in the `changeset/2` function, in `Hello.User`.
```
|> validate_required([:name, :email, :bio])
```
Now casting the changeset should tell us that only `name`, `email`, and `bio` can't be blank. We can test that by running `recompile()` inside IEx and then rebuilding our changeset.
```
iex> recompile()
Compiling 1 file (.ex)
:ok
iex> changeset = User.changeset(%User{}, %{})
#Ecto.Changeset<
action: nil,
changes: %{},
errors: [
name: {"can't be blank", [validation: :required]},
email: {"can't be blank", [validation: :required]},
bio: {"can't be blank", [validation: :required]}
],
data: #Hello.User<>,
valid?: false
>
iex> changeset.errors
[
name: {"can't be blank", [validation: :required]},
email: {"can't be blank", [validation: :required]},
bio: {"can't be blank", [validation: :required]}
]
```
What happens if we pass a key-value pair that is neither defined in the schema nor required?
Inside our existing IEx shell, let's create a `params` map with valid values plus an extra `random_key: "random value"`.
```
iex> params = %{name: "Joe Example", email: "[email protected]", bio: "An example to all", number_of_pets: 5, random_key: "random value"}
%{
bio: "An example to all",
email: "[email protected]",
name: "Joe Example",
number_of_pets: 5,
random_key: "random value"
}
```
Next, let's use our new `params` map to create another changeset.
```
iex> changeset = User.changeset(%User{}, params)
#Ecto.Changeset<
action: nil,
changes: %{
bio: "An example to all",
email: "[email protected]",
name: "Joe Example",
number_of_pets: 5
},
errors: [],
data: #Hello.User<>,
valid?: true
>
```
Our new changeset is valid.
```
iex> changeset.valid?
true
```
We can also check the changeset's changes - the map we get after all of the transformations are complete.
```
iex(9)> changeset.changes
%{bio: "An example to all", email: "[email protected]", name: "Joe Example",
number_of_pets: 5}
```
Notice that our `random_key` key and `"random_value"` value have been removed from the final changeset. Changesets allow us to cast external data, such as user input on a web form or data from a CSV file into valid data into our system. Invalid parameters will be stripped and bad data that is unable to be cast according to our schema will be highlighted in the changeset errors.
We can validate more than just whether a field is required or not. Let's take a look at some finer-grained validations.
What if we had a requirement that all biographies in our system must be at least two characters long? We can do this easily by adding another transformation to the pipeline in our changeset which validates the length of the `bio` field.
```
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :bio, :number_of_pets])
|> validate_required([:name, :email, :bio, :number_of_pets])
|> validate_length(:bio, min: 2)
end
```
Now, if we try to cast data containing a value of `"A"` for our user's `bio`, we should see the failed validation in the changeset's errors.
```
iex> recompile()
iex> changeset = User.changeset(%User{}, %{bio: "A"})
iex> changeset.errors[:bio]
{"should be at least %{count} character(s)",
[count: 2, validation: :length, kind: :min, type: :string]}
```
If we also have a requirement for the maximum length that a bio can have, we can simply add another validation.
```
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :bio, :number_of_pets])
|> validate_required([:name, :email, :bio, :number_of_pets])
|> validate_length(:bio, min: 2)
|> validate_length(:bio, max: 140)
end
```
Let's say we want to perform at least some rudimentary format validation on the `email` field. All we want to check for is the presence of the `@`. The [`Ecto.Changeset.validate_format/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Changeset.html#validate_format/3) function is just what we need.
```
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :bio, :number_of_pets])
|> validate_required([:name, :email, :bio, :number_of_pets])
|> validate_length(:bio, min: 2)
|> validate_length(:bio, max: 140)
|> validate_format(:email, ~r/@/)
end
```
If we try to cast a user with an email of `"example.com"`, we should see an error message like the following:
```
iex> recompile()
iex> changeset = User.changeset(%User{}, %{email: "example.com"})
iex> changeset.errors[:email]
{"has invalid format", [validation: :format]}
```
There are many more validations and transformations we can perform in a changeset. Please see the [Ecto Changeset documentation](../ecto/ecto.changeset) for more information.
Data persistence
-----------------
We've explored migrations and schemas, but we haven't yet persisted any of our schemas or changesets. We briefly looked at our repository module in `lib/hello/repo.ex` earlier, and now it's time to put it to use.
Ecto repositories are the interface into a storage system, be it a database like PostgreSQL or an external service like a RESTful API. The `Repo` module's purpose is to take care of the finer details of persistence and data querying for us. As the caller, we only care about fetching and persisting data. The `Repo` module takes care of the underlying database adapter communication, connection pooling, and error translation for database constraint violations.
Let's head back over to IEx with `iex -S mix`, and insert a couple of users into the database.
```
iex> alias Hello.{Repo, User}
[Hello.Repo, Hello.User]
iex> Repo.insert(%User{email: "[email protected]"})
[debug] QUERY OK db=6.5ms queue=0.5ms idle=1358.3ms
INSERT INTO "users" ("email","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["[email protected]", ~N[2021-02-25 01:58:55], ~N[2021-02-25 01:58:55]]
{:ok,
%Hello.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
bio: nil,
email: "[email protected]",
id: 1,
inserted_at: ~N[2021-02-25 01:58:55],
name: nil,
number_of_pets: nil,
updated_at: ~N[2021-02-25 01:58:55]
}}
iex> Repo.insert(%User{email: "[email protected]"})
[debug] QUERY OK db=1.3ms idle=1402.7ms
INSERT INTO "users" ("email","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["[email protected]", ~N[2021-02-25 02:03:28], ~N[2021-02-25 02:03:28]]
{:ok,
%Hello.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
bio: nil,
email: "[email protected]",
id: 2,
inserted_at: ~N[2021-02-25 02:03:28],
name: nil,
number_of_pets: nil,
updated_at: ~N[2021-02-25 02:03:28]
}}
```
We started by aliasing our `User` and `Repo` modules for easy access. Next, we called [`Repo.insert/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:insert/2) with a User struct. Since we are in the `dev` environment, we can see the debug logs for the query our repository performed when inserting the underlying `%User{}` data. We received a two-element tuple back with `{:ok, %User{}}`, which lets us know the insertion was successful.
We could also insert a user by passing a changeset to [`Repo.insert/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:insert/2). If the changeset is valid, the repository will use an optimized database query to insert the record, and return a two-element tuple back, as above. If the changeset is not valid, we receive a two-element tuple consisting of `:error` plus the invalid changeset.
With a couple of users inserted, let's fetch them back out of the repo.
```
iex> Repo.all(User)
[debug] QUERY OK source="users" db=5.8ms queue=1.4ms idle=1672.0ms
SELECT u0."id", u0."bio", u0."email", u0."name", u0."number_of_pets", u0."inserted_at", u0."updated_at" FROM "users" AS u0 []
[
%Hello.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
bio: nil,
email: "[email protected]",
id: 1,
inserted_at: ~N[2021-02-25 01:58:55],
name: nil,
number_of_pets: nil,
updated_at: ~N[2021-02-25 01:58:55]
},
%Hello.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
bio: nil,
email: "[email protected]",
id: 2,
inserted_at: ~N[2021-02-25 02:03:28],
name: nil,
number_of_pets: nil,
updated_at: ~N[2021-02-25 02:03:28]
}
]
```
That was easy! `Repo.all/1` takes a data source, our `User` schema in this case, and translates that to an underlying SQL query against our database. After it fetches the data, the Repo then uses our Ecto schema to map the database values back into Elixir data structures according to our `User` schema. We're not just limited to basic querying – Ecto includes a full-fledged query DSL for advanced SQL generation. In addition to a natural Elixir DSL, Ecto's query engine gives us multiple great features, such as SQL injection protection and compile-time optimization of queries. Let's try it out.
```
iex> import Ecto.Query
Ecto.Query
iex> Repo.all(from u in User, select: u.email)
[debug] QUERY OK source="users" db=0.8ms queue=0.9ms idle=1634.0ms
SELECT u0."email" FROM "users" AS u0 []
["[email protected]", "[email protected]"]
```
First, we imported [[`Ecto.Query`](https://hexdocs.pm/ecto/3.8.2/Ecto.Query.html)], which imports the [`from/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Query.html#from/2) macro of Ecto's Query DSL. Next, we built a query which selects all the email addresses in our users table. Let's try another example.
```
iex)> Repo.one(from u in User, where: ilike(u.email, "%1%"),
select: count(u.id))
[debug] QUERY OK source="users" db=1.6ms SELECT count(u0."id") FROM "users" AS u0 WHERE (u0."email" ILIKE '%1%') []
1
```
Now we're starting to get a taste of Ecto's rich querying capabilities. We used [`Repo.one/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:one/2) to fetch the count of all users with an email address containing `1`, and received the expected count in return. This just scratches the surface of Ecto's query interface, and much more is supported such as sub-querying, interval queries, and advanced select statements. For example, let's build a query to fetch a map of all user id's to their email addresses.
```
iex> Repo.all(from u in User, select: %{u.id => u.email})
[debug] QUERY OK source="users" db=0.9ms
SELECT u0."id", u0."email" FROM "users" AS u0 []
[
%{1 => "[email protected]"},
%{2 => "[email protected]"}
]
```
That little query packed a big punch. It both fetched all user emails from the database and efficiently built a map of the results in one go. You should browse the [Ecto.Query documentation](../ecto/ecto.query#content) to see the breadth of supported query features.
In addition to inserts, we can also perform updates and deletes with [`Repo.update/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:update/2) and [`Repo.delete/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:delete/2) to update or delete a single schema. Ecto also supports bulk persistence with the [`Repo.insert_all/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:insert_all/3), [`Repo.update_all/3`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:update_all/3), and [`Repo.delete_all/2`](https://hexdocs.pm/ecto/3.8.2/Ecto.Repo.html#c:delete_all/2) functions.
There is quite a bit more that Ecto can do and we've only barely scratched the surface. With a solid Ecto foundation in place, we're now ready to continue building our app and integrate the web-facing application with our backend persistence. Along the way, we'll expand our Ecto knowledge and learn how to properly isolate our web interface from the underlying details of our system. Please take a look at the [Ecto documentation](../ecto/index) for the rest of the story.
In our [contexts guide](contexts), we'll find out how to wrap up our Ecto access and business logic behind modules that group related functionality. We'll see how Phoenix helps us design maintainable applications, and we'll find out about other neat Ecto features along the way.
Using MySQL
------------
Phoenix applications are configured to use PostgreSQL by default, but what if we want to use MySQL instead? In this guide, we'll walk through changing that default whether we are about to create a new application, or whether we have an existing one configured for PostgreSQL.
If we are about to create a new application, configuring our application to use MySQL is easy. We can simply pass the `--database mysql` flag to `phx.new` and everything will be configured correctly.
```
$ mix phx.new hello_phoenix --database mysql
```
This will set up all the correct dependencies and configuration for us automatically. Once we install those dependencies with [`mix deps.get`](https://hexdocs.pm/mix/Mix.Tasks.Deps.Get.html), we'll be ready to begin working with Ecto in our application.
If we have an existing application, all we need to do is switch adapters and make some small configuration changes.
To switch adapters, we need to remove the Postgrex dependency and add a new one for Myxql instead.
Let's open up our `mix.exs` file and do that now.
```
defmodule HelloPhoenix.MixProject do
use Mix.Project
. . .
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.4.0"},
{:phoenix_ecto, "~> 4.4"},
{:ecto_sql, "~> 3.6"},
{:myxql, ">= 0.0.0"},
...
]
end
end
```
Next, we need to configure our adapter to use the default MySQL credentials by updating `config/dev.exs`:
```
config :hello_phoenix, HelloPhoenix.Repo,
username: "root",
password: "",
database: "hello_phoenix_dev"
```
If we have an existing configuration block for our `HelloPhoenix.Repo`, we can simply change the values to match our new ones. You also need to configure the correct values in the `config/test.exs` and `config/runtime.exs` (formerly `config/prod.secret.exs`) files as well.
The last change is to open up `lib/hello_phoenix/repo.ex` and make sure to set the `:adapter` to [`Ecto.Adapters.MyXQL`](https://hexdocs.pm/ecto_sql/3.8.1/Ecto.Adapters.MyXQL.html).
Now all we need to do is fetch our new dependency, and we'll be ready to go.
```
$ mix do deps.get, compile
```
With our new adapter installed and configured, we're ready to create our database.
```
$ mix ecto.create
```
The database for HelloPhoenix.Repo has been created. We're also ready to run any migrations, or do anything else with Ecto that we may choose.
```
$ mix ecto.migrate
[info] == Running HelloPhoenix.Repo.Migrations.CreateUser.change/0 forward
[info] create table users
[info] == Migrated in 0.2s
```
Other options
--------------
While Phoenix uses the [`Ecto`](https://hexdocs.pm/ecto/3.8.2/Ecto.html) project to interact with the data access layer, there are many other data access options, some even built into the Erlang standard library. [ETS](https://www.erlang.org/doc/man/ets.html) – available in Ecto via [`etso`](https://hexdocs.pm/etso/) – and [DETS](https://www.erlang.org/doc/man/dets.html) are key-value data stores built into [OTP](https://www.erlang.org/doc/). OTP also provides a relational database called [Mnesia](https://www.erlang.org/doc/man/mnesia.html) with its own query language called QLC. Both Elixir and Erlang also have a number of libraries for working with a wide range of popular data stores.
The data world is your oyster, but we won't be covering these options in these guides.
[← Previous Page Views and templates](views) [Next Page → Contexts](contexts)
| programming_docs |
phoenix Channels Channels
=========
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
Channels are an exciting part of Phoenix that enable soft real-time communication with and between millions of connected clients.
Some possible use cases include:
* Chat rooms and APIs for messaging apps
* Breaking news, like "a goal was scored" or "an earthquake is coming"
* Tracking trains, trucks, or race participants on a map
* Events in multiplayer games
* Monitoring sensors and controlling lights
* Notifying a browser that a page's CSS or JavaScript has changed (this is handy in development)
Conceptually, Channels are pretty simple.
First, clients connect to the server using some transport, like WebSocket. Once connected, they join one or more topics. For example, to interact with a public chat room clients may join a topic called `public_chat`, and to receive updates from a product with ID 7, they may need to join a topic called `product_updates:7`.
Clients can push messages to the topics they've joined, and can also receive messages from them. The other way around, Channel servers receive messages from their connected clients, and can push messages to them too.
Servers are able to broadcast messages to all clients subscribed to a certain topic. This is illustrated in the following diagram:
```
+----------------+
+--Topic X-->| Mobile Client |
| +----------------+
+-------------------+ |
+----------------+ | | | +----------------+
| Browser Client |--Topic X-->| Phoenix Server(s) |--+--Topic X-->| Desktop Client |
+----------------+ | | | +----------------+
+-------------------+ |
| +----------------+
+--Topic X-->| IoT Client |
+----------------+
```
Broadcasts work even if the application runs on several nodes/computers. That is, if two clients have their socket connected to different application nodes and are subscribed to the same topic `T`, both of them will receive messages broadcasted to `T`. That is possible thanks to an internal PubSub mechanism.
Channels can support any kind of client: a browser, native app, smart watch, embedded device, or anything else that can connect to a network. All the client needs is a suitable library; see the [Client Libraries](#client-libraries) section below. Each client library communicates using one of the "transports" that Channels understand. Currently, that's either Websockets or long polling, but other transports may be added in the future.
Unlike stateless HTTP connections, Channels support long-lived connections, each backed by a lightweight BEAM process, working in parallel and maintaining its own state.
This architecture scales well; Phoenix Channels [can support millions of subscribers with reasonable latency on a single box](https://phoenixframework.org/blog/the-road-to-2-million-websocket-connections), passing hundreds of thousands of messages per second. And that capacity can be multiplied by adding more nodes to the cluster.
The Moving Parts
-----------------
Although Channels are simple to use from a client perspective, there are a number of components involved in routing messages to clients across a cluster of servers. Let's take a look at them.
### Overview
To start communicating, a client connects to a node (a Phoenix server) using a transport (e.g., Websockets or long polling) and joins one or more channels using that single network connection. One channel server lightweight process is created per client, per topic. Each channel holds onto the `%Phoenix.Socket{}` and can maintain any state it needs within its `socket.assigns`.
Once the connection is established, each incoming message from a client is routed, based on its topic, to the correct channel server. If the channel server asks to broadcast a message, that message is sent to the local PubSub, which sends it out to any clients connected to the same server and subscribed to that topic.
If there are other nodes in the cluster, the local PubSub also forwards the message to their PubSubs, which send it out to their own subscribers. Because only one message has to be sent per additional node, the performance cost of adding nodes is negligible, while each new node supports many more subscribers.
The message flow looks something like this:
```
Channel +-------------------------+ +--------+
route | Sending Client, Topic 1 | | Local |
+----------->| Channel.Server |----->| PubSub |--+
+----------------+ | +-------------------------+ +--------+ |
| Sending Client |-Transport--+ | |
+----------------+ +-------------------------+ | |
| Sending Client, Topic 2 | | |
| Channel.Server | | |
+-------------------------+ | |
| |
+-------------------------+ | |
+----------------+ | Browser Client, Topic 1 | | |
| Browser Client |<-------Transport--------| Channel.Server |<----------+ |
+----------------+ +-------------------------+ |
|
|
|
+-------------------------+ |
+----------------+ | Phone Client, Topic 1 | |
| Phone Client |<-------Transport--------| Channel.Server |<-+ |
+----------------+ +-------------------------+ | +--------+ |
| | Remote | |
+-------------------------+ +---| PubSub |<-+
+----------------+ | Watch Client, Topic 1 | | +--------+ |
| Watch Client |<-------Transport--------| Channel.Server |<-+ |
+----------------+ +-------------------------+ |
|
|
+-------------------------+ +--------+ |
+----------------+ | IoT Client, Topic 1 | | Remote | |
| IoT Client |<-------Transport--------| Channel.Server |<-----| PubSub |<-+
+----------------+ +-------------------------+ +--------+
```
### Endpoint
In your Phoenix app's `Endpoint` module, a `socket` declaration specifies which socket handler will receive connections on a given URL.
```
socket "/socket", HelloWeb.UserSocket,
websocket: true,
longpoll: false
```
Phoenix comes with two default transports: websocket and longpoll. You can configure them directly via the `socket` declaration.
### Socket Handlers
On the client side, you will establish a socket connection to the route above:
```
let socket = new Socket("/socket", {params: {token: window.userToken}})
```
On the server, Phoenix will invoke `HelloWeb.UserSocket.connect/2`, passing your parameters and the initial socket state. Within the socket, you can authenticate and identify a socket connection and set default socket assigns. The socket is also where you define your channel routes.
### Channel Routes
Channel routes match on the topic string and dispatch matching requests to the given Channel module.
The star character `*` acts as a wildcard matcher, so in the following example route, requests for `room:lobby` and `room:123` would both be dispatched to the `RoomChannel`. In your `UserSocket`, you would have:
```
channel "room:*", HelloWeb.RoomChannel
```
### Channels
Channels handle events from clients, so they are similar to Controllers, but there are two key differences. Channel events can go both directions - incoming and outgoing. Channel connections also persist beyond a single request/response cycle. Channels are the highest level abstraction for real-time communication components in Phoenix.
Each Channel will implement one or more clauses of each of these four callback functions - `join/3`, `terminate/2`, `handle_in/3`, and `handle_out/3`.
### Topics
Topics are string identifiers - names that the various layers use in order to make sure messages end up in the right place. As we saw above, topics can use wildcards. This allows for a useful `"topic:subtopic"` convention. Often, you'll compose topics using record IDs from your application layer, such as `"users:123"`.
### Messages
The [`Phoenix.Socket.Message`](phoenix.socket.message) module defines a struct with the following keys which denotes a valid message. From the [Phoenix.Socket.Message docs](phoenix.socket.message).
* `topic` - The string topic or `"topic:subtopic"` pair namespace, such as `"messages"` or `"messages:123"`
* `event` - The string event name, for example `"phx_join"`
* `payload` - The message payload
* `ref` - The unique string ref
### PubSub
PubSub is provided by the [`Phoenix.PubSub`](https://hexdocs.pm/phoenix_pubsub/2.1.1/Phoenix.PubSub.html) module. Interested parties can receive events by subscribing to topics. Other processes can broadcast events to certain topics.
This is useful to broadcast messages on channel and also for application development in general. For instance, letting all connected [live views](https://github.com/phoenixframework/phoenix_live_view) to know that a new comment has been added to a post.
The PubSub system takes care of getting messages from one node to another so that they can be sent to all subscribers across the cluster. By default, this is done using [Phoenix.PubSub.PG2](../phoenix_pubsub/phoenix.pubsub.pg2), which uses native BEAM messaging.
If your deployment environment does not support distributed Elixir or direct communication between servers, Phoenix also ships with a [Redis Adapter](https://hexdocs.pm/phoenix_pubsub_redis/Phoenix.PubSub.Redis.html) that uses Redis to exchange PubSub data. Please see the [Phoenix.PubSub docs](../phoenix_pubsub/phoenix.pubsub) for more information.
### Client Libraries
Any networked device can connect to Phoenix Channels as long as it has a client library. The following libraries exist today, and new ones are always welcome.
#### Official
Phoenix ships with a JavaScript client that is available when generating a new Phoenix project. The documentation for the JavaScript module is available at <https://hexdocs.pm/phoenix/js/>; the code is in [multiple js files](https://github.com/phoenixframework/phoenix/blob/master/assets/js/phoenix/).
#### 3rd Party
* Swift (iOS)
+ [SwiftPhoenix](https://github.com/davidstump/SwiftPhoenixClient)
* Java (Android)
+ [JavaPhoenixChannels](https://github.com/eoinsha/JavaPhoenixChannels)
* Kotlin (Android)
+ [JavaPhoenixClient](https://github.com/dsrees/JavaPhoenixClient)
* C#
+ [PhoenixSharp](https://github.com/Mazyod/PhoenixSharp)
* Elixir
+ [phoenix\_gen\_socket\_client](https://github.com/Aircloak/phoenix_gen_socket_client)
* GDScript (Godot Game Engine)
+ [GodotPhoenixChannels](https://github.com/alfredbaudisch/GodotPhoenixChannels)
Tying it all together
----------------------
Let's tie all these ideas together by building a simple chat application. Make sure [you created a new Phoenix application](up_and_running) and now we are ready to generate the `UserSocket`.
### Generating a socket
Let's invoke the socket generator to get started:
```
$ mix phx.gen.socket User
```
It will create two files, the client code in `assets/js/user_socket.js` and the server counter-part in `lib/hello_web/channels/user_socket.ex`. After running, the generator will also ask to add the following line to `lib/hello_web/endpoint.ex`:
```
defmodule HelloWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :hello
socket "/socket", HelloWeb.UserSocket,
websocket: true,
longpoll: false
...
end
```
The generator also asks us to import the client code, we will do that later.
Next, we will configure our socket to ensure messages get routed to the correct channel. To do that, we'll uncomment the `"room:*"` channel definition:
```
defmodule HelloWeb.UserSocket do
use Phoenix.Socket
## Channels
channel "room:*", HelloWeb.RoomChannel
...
```
Now, whenever a client sends a message whose topic starts with `"room:"`, it will be routed to our RoomChannel. Next, we'll define a `HelloWeb.RoomChannel` module to manage our chat room messages.
### Joining Channels
The first priority of your channels is to authorize clients to join a given topic. For authorization, we must implement `join/3` in `lib/hello_web/channels/room_channel.ex`.
```
defmodule HelloWeb.RoomChannel do
use Phoenix.Channel
def join("room:lobby", _message, socket) do
{:ok, socket}
end
def join("room:" <> _private_room_id, _params, _socket) do
{:error, %{reason: "unauthorized"}}
end
end
```
For our chat app, we'll allow anyone to join the `"room:lobby"` topic, but any other room will be considered private and special authorization, say from a database, will be required. (We won't worry about private chat rooms for this exercise, but feel free to explore after we finish.)
With our channel in place, let's get the client and server talking.
The generated `assets/js/user_socket.js` defines a simple client based on the socket implementation that ships with Phoenix.
We can use that library to connect to our socket and join our channel, we just need to set our room name to `"room:lobby"` in that file.
```
// assets/js/user_socket.js
// ...
socket.connect()
// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("room:lobby", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
export default socket
```
After that, we need to make sure `assets/js/user_socket.js` gets imported into our application JavaScript file. To do that, uncomment this line in `assets/js/app.js`.
```
// ...
import "./user_socket.js"
```
Save the file and your browser should auto refresh, thanks to the Phoenix live reloader. If everything worked, we should see "Joined successfully" in the browser's JavaScript console. Our client and server are now talking over a persistent connection. Now let's make it useful by enabling chat.
In `lib/hello_web/templates/page/index.html.heex`, we'll replace the existing code with a container to hold our chat messages, and an input field to send them:
```
<div id="messages" role="log" aria-live="polite"></div>
<input id="chat-input" type="text">
```
Now let's add a couple of event listeners to `assets/js/user_socket.js`:
```
// ...
let channel = socket.channel("room:lobby", {})
let chatInput = document.querySelector("#chat-input")
let messagesContainer = document.querySelector("#messages")
chatInput.addEventListener("keypress", event => {
if(event.key === 'Enter'){
channel.push("new_msg", {body: chatInput.value})
chatInput.value = ""
}
})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
export default socket
```
All we had to do is detect that enter was pressed and then `push` an event over the channel with the message body. We named the event `"new_msg"`. With this in place, let's handle the other piece of a chat application, where we listen for new messages and append them to our messages container.
```
// ...
let channel = socket.channel("room:lobby", {})
let chatInput = document.querySelector("#chat-input")
let messagesContainer = document.querySelector("#messages")
chatInput.addEventListener("keypress", event => {
if(event.key === 'Enter'){
channel.push("new_msg", {body: chatInput.value})
chatInput.value = ""
}
})
channel.on("new_msg", payload => {
let messageItem = document.createElement("p")
messageItem.innerText = `[${Date()}] ${payload.body}`
messagesContainer.appendChild(messageItem)
})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
export default socket
```
We listen for the `"new_msg"` event using `channel.on`, and then append the message body to the DOM. Now let's handle the incoming and outgoing events on the server to complete the picture.
### Incoming Events
We handle incoming events with `handle_in/3`. We can pattern match on the event names, like `"new_msg"`, and then grab the payload that the client passed over the channel. For our chat application, we simply need to notify all other `room:lobby` subscribers of the new message with `broadcast!/3`.
```
defmodule HelloWeb.RoomChannel do
use Phoenix.Channel
def join("room:lobby", _message, socket) do
{:ok, socket}
end
def join("room:" <> _private_room_id, _params, _socket) do
{:error, %{reason: "unauthorized"}}
end
def handle_in("new_msg", %{"body" => body}, socket) do
broadcast!(socket, "new_msg", %{body: body})
{:noreply, socket}
end
end
```
`broadcast!/3` will notify all joined clients on this `socket`'s topic and invoke their `handle_out/3` callbacks. `handle_out/3` isn't a required callback, but it allows us to customize and filter broadcasts before they reach each client. By default, `handle_out/3` is implemented for us and simply pushes the message on to the client. Hooking into outgoing events allows for powerful message customization and filtering. Let's see how.
### Intercepting Outgoing Events
We won't implement this for our application, but imagine our chat app allowed users to ignore messages about new users joining a room. We could implement that behavior like this, where we explicitly tell Phoenix which outgoing event we want to intercept and then define a `handle_out/3` callback for those events. (Of course, this assumes that we have an `Accounts` context with an `ignoring_user?/2` function, and that we pass a user in via the `assigns` map). It is important to note that the `handle_out/3` callback will be called for every recipient of a message, so more expensive operations like hitting the database should be considered carefully before being included in `handle_out/3`.
```
intercept ["user_joined"]
def handle_out("user_joined", msg, socket) do
if Accounts.ignoring_user?(socket.assigns[:user], msg.user_id) do
{:noreply, socket}
else
push(socket, "user_joined", msg)
{:noreply, socket}
end
end
```
That's all there is to our basic chat app. Fire up multiple browser tabs and you should see your messages being pushed and broadcasted to all windows!
Using Token Authentication
---------------------------
When we connect, we'll often need to authenticate the client. Fortunately, this is a 4-step process with [Phoenix.Token](phoenix.token).
**Step 1 - Assign a Token in the Connection**
Let's say we have an authentication plug in our app called `OurAuth`. When `OurAuth` authenticates a user, it sets a value for the `:current_user` key in `conn.assigns`. Since the `current_user` exists, we can simply assign the user's token in the connection for use in the layout. We can wrap that behavior up in a private function plug, `put_user_token/2`. This could also be put in its own module as well. To make this all work, we just add `OurAuth` and `put_user_token/2` to the browser pipeline.
```
pipeline :browser do
...
plug OurAuth
plug :put_user_token
end
defp put_user_token(conn, _) do
if current_user = conn.assigns[:current_user] do
token = Phoenix.Token.sign(conn, "user socket", current_user.id)
assign(conn, :user_token, token)
else
conn
end
end
```
Now our `conn.assigns` contains the `current_user` and `user_token`.
**Step 2 - Pass the Token to the JavaScript**
Next, we need to pass this token to JavaScript. We can do so inside a script tag in `web/templates/layout/app.html.heex` right above the app.js script, as follows:
```
<script>window.userToken = "<%= assigns[:user_token] %>";</script>
<script src={Routes.static_path(@conn, "/assets/app.js")}></script>
```
**Step 3 - Pass the Token to the Socket Constructor and Verify**
We also need to pass the `:params` to the socket constructor and verify the user token in the `connect/3` function. To do so, edit `web/channels/user_socket.ex`, as follows:
```
def connect(%{"token" => token}, socket, _connect_info) do
# max_age: 1209600 is equivalent to two weeks in seconds
case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
{:ok, user_id} ->
{:ok, assign(socket, :current_user, user_id)}
{:error, reason} ->
:error
end
end
```
In our JavaScript, we can use the token set previously when constructing the Socket:
```
let socket = new Socket("/socket", {params: {token: window.userToken}})
```
We used [`Phoenix.Token.verify/4`](phoenix.token#verify/4) to verify the user token provided by the client. [`Phoenix.Token.verify/4`](phoenix.token#verify/4) returns either `{:ok, user_id}` or `{:error, reason}`. We can pattern match on that return in a `case` statement. With a verified token, we set the user's id as the value to `:current_user` in the socket. Otherwise, we return `:error`.
**Step 4 - Connect to the socket in JavaScript**
With authentication set up, we can connect to sockets and channels from JavaScript.
```
let socket = new Socket("/socket", {params: {token: window.userToken}})
socket.connect()
```
Now that we are connected, we can join channels with a topic:
```
let channel = socket.channel("topic:subtopic", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
export default socket
```
Note that token authentication is preferable since it's transport agnostic and well-suited for long running-connections like channels, as opposed to using sessions or authentication approaches.
Fault Tolerance and Reliability Guarantees
-------------------------------------------
Servers restart, networks split, and clients lose connectivity. In order to design robust systems, we need to understand how Phoenix responds to these events and what guarantees it offers.
### Handling Reconnection
Clients subscribe to topics, and Phoenix stores those subscriptions in an in-memory ETS table. If a channel crashes, the clients will need to reconnect to the topics they had previously subscribed to. Fortunately, the Phoenix JavaScript client knows how to do this. The server will notify all the clients of the crash. This will trigger each client's `Channel.onError` callback. The clients will attempt to reconnect to the server using an exponential backoff strategy. Once they reconnect, they'll attempt to rejoin the topics they had previously subscribed to. If they are successful, they'll start receiving messages from those topics as before.
### Resending Client Messages
Channel clients queue outgoing messages into a `PushBuffer`, and send them to the server when there is a connection. If no connection is available, the client holds on to the messages until it can establish a new connection. With no connection, the client will hold the messages in memory until it establishes a connection, or until it receives a `timeout` event. The default timeout is set to 5000 milliseconds. The client won't persist the messages in the browser's local storage, so if the browser tab closes, the messages will be gone.
### Resending Server Messages
Phoenix uses an at-most-once strategy when sending messages to clients. If the client is offline and misses the message, Phoenix won't resend it. Phoenix doesn't persist messages on the server. If the server restarts, unsent messages will be gone. If our application needs stronger guarantees around message delivery, we'll need to write that code ourselves. Common approaches involve persisting messages on the server and having clients request missing messages. For an example, see Chris McCord's Phoenix training: [client code](https://github.com/chrismccord/elixirconf_training/blob/master/web/static/js/app.js#L38-L39) and [server code](https://github.com/chrismccord/elixirconf_training/blob/master/web/channels/document_channel.ex#L13-L19).
Example Application
--------------------
To see an example of the application we just built, checkout the project [phoenix\_chat\_example](https://github.com/chrismccord/phoenix_chat_example).
You can also see a live demo at <https://phoenixchat.herokuapp.com/>.
[← Previous Page mix phx.gen.auth](mix_phx_gen_auth) [Next Page → Presence](presence)
| programming_docs |
phoenix Using SSL Using SSL
==========
To prepare an application to serve requests over SSL, we need to add a little bit of configuration and two environment variables. In order for SSL to actually work, we'll need a key file and certificate file from a certificate authority. The environment variables that we'll need are paths to those two files.
The configuration consists of a new `https:` key for our endpoint whose value is a keyword list of port, path to the key file, and path to the cert (PEM) file. If we add the `otp_app:` key whose value is the name of our application, Plug will begin to look for them at the root of our application. We can then put those files in our `priv` directory and set the paths to `priv/our_keyfile.key` and `priv/our_cert.crt`.
Here's an example configuration from `config/prod.exs`.
```
import Config
config :hello, HelloWeb.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "example.com"],
cache_static_manifest: "priv/static/cache_manifest.json",
https: [
port: 443,
cipher_suite: :strong,
otp_app: :hello,
keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
certfile: System.get_env("SOME_APP_SSL_CERT_PATH"),
# OPTIONAL Key for intermediate certificates:
cacertfile: System.get_env("INTERMEDIATE_CERTFILE_PATH")
]
```
Without the `otp_app:` key, we need to provide absolute paths to the files wherever they are on the filesystem in order for Plug to find them.
```
Path.expand("../../../some/path/to/ssl/key.pem", __DIR__)
```
The options under the `https:` key are passed to the Plug adapter, typically [`Plug.Cowboy`](https://hexdocs.pm/plug_cowboy/2.5.2/Plug.Cowboy.html), which in turn uses [`Plug.SSL`](https://hexdocs.pm/plug/1.13.6/Plug.SSL.html) to select the TLS socket options. Please refer to the documentation for [Plug.SSL.configure/1](../plug/plug.ssl#configure/1) for more information on the available options and their defaults. The [Plug HTTPS Guide](../plug/https) and the [Erlang/OTP ssl](https://erlang.org/doc/man/ssl.html) documentation also provide valuable information.
SSL in Development
-------------------
If you would like to use HTTPS in development, a self-signed certificate can be generated by running: [`mix phx.gen.cert`](mix.tasks.phx.gen.cert). This requires Erlang/OTP 20 or later.
With your self-signed certificate, your development configuration in `config/dev.exs` can be updated to run an HTTPS endpoint:
```
config :my_app, MyAppWeb.Endpoint,
...
https: [
port: 4001,
cipher_suite: :strong,
keyfile: "priv/cert/selfsigned_key.pem",
certfile: "priv/cert/selfsigned.pem"
]
```
This can replace your `http` configuration, or you can run HTTP and HTTPS servers on different ports.
Force SSL
----------
In many cases, you'll want to force all incoming requests to use SSL by redirecting HTTP to HTTPS. This can be accomplished by setting the `:force_ssl` option in your endpoint configuration. It expects a list of options which are forwarded to [`Plug.SSL`](https://hexdocs.pm/plug/1.13.6/Plug.SSL.html). By default, it sets the "strict-transport-security" header in HTTPS requests, forcing browsers to always use HTTPS. If an unsafe (HTTP) request is sent, it redirects to the HTTPS version using the `:host` specified in the `:url` configuration. For example:
```
config :my_app, MyAppWeb.Endpoint,
force_ssl: [rewrite_on: [:x_forwarded_proto]]
```
To dynamically redirect to the `host` of the current request, set `:host` in the `:force_ssl` configuration to `nil`.
```
config :my_app, MyAppWeb.Endpoint,
force_ssl: [rewrite_on: [:x_forwarded_proto], host: nil]
```
In these examples, the `rewrite_on:` key specifies the HTTP header used by a reverse proxy or load balancer in front of the application to indicate whether the request was received over HTTP or HTTPS. For more information on the implications of offloading TLS to an external element, in particular relating to secure cookies, refer to the [Plug HTTPS Guide](../plug/https#offloading-tls). Keep in mind that the options passed to [`Plug.SSL`](https://hexdocs.pm/plug/1.13.6/Plug.SSL.html) in that document should be set using the `force_ssl:` endpoint option in a Phoenix application.
HSTS
-----
HSTS or "strict-transport-security" is a mechanism that allows a website to declare itself as only accessible via a secure connection (HTTPS). It was introduced to prevent man-in-the-middle attacks that strip SSL/TLS. It causes web browsers to redirect from HTTP to HTTPS and refuse to connect unless the connection uses SSL/TLS.
With `force_ssl: [hsts: true]` set, the `Strict-Transport-Security` header is set with a max age that defines the length of time the policy is valid for. Modern web browsers will respond to this by redirecting from HTTP to HTTPS for the standard case but it does have other consequences. [RFC6797](https://tools.ietf.org/html/rfc6797) which defines HSTS also specifies **that the browser should keep track of the policy of a host and apply it until it expires.** It also specifies that **traffic on any port other than 80 is assumed to be encrypted** as per the policy.
This can result in unexpected behaviour if you access your application on localhost, for example `https://localhost:4000`, as from that point forward any traffic coming from localhost will be expected to be encrypted, except port 80 which will be redirected to port 443. This has the potential to disrupt traffic to any other local servers or proxies that you may be running on your computer. Other applications or proxies on localhost will refuse to work unless the traffic is encrypted.
If you do inadvertently turn on HSTS for localhost, you may need to reset the cache on your browser before it will accept any HTTP traffic from localhost. For Chrome, you need to `Empty Cache and Hard Reload` which is available from the reload menu that appears when you click and hold the reload icon from the Developer Tools Panel. For Safari, you will need to clear your cache, remove the entry from `~/Library/Cookies/HSTS.plist` (or delete that file entirely) and restart Safari. Alternately, you can set the `:expires` option on `force_ssl` to `0` which should expired the entry to turn off HSTS. More information on the options for HSTS are available at [Plug.SSL](../plug/plug.ssl).
[← Previous Page Custom Error Pages](custom_error_pages)
phoenix Presence Presence
=========
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [Channels guide](channels).
>
>
Phoenix Presence is a feature which allows you to register process information on a topic and replicate it transparently across a cluster. It's a combination of both a server-side and client-side library, which makes it simple to implement. A simple use-case would be showing which users are currently online in an application.
Phoenix Presence is special for a number of reasons. It has no single point of failure, no single source of truth, relies entirely on the standard library with no operational dependencies and self-heals.
Setting up
-----------
We are going to use Presence to track which users are connected on the server and send updates to the client as users join and leave. We will deliver those updates via Phoenix Channels. Therefore, let's create a `RoomChannel`, as we did in the channels guides:
```
$ mix phx.gen.channel Room
```
Follow the steps after the generator and you are ready to start tracking presence.
The Presence generator
-----------------------
To get started with Presence, we'll first need to generate a presence module. We can do this with the [`mix phx.gen.presence`](mix.tasks.phx.gen.presence) task:
```
$ mix phx.gen.presence
* creating lib/hello_web/channels/presence.ex
Add your new module to your supervision tree,
in lib/hello/application.ex:
children = [
...
HelloWeb.Presence,
]
You're all set! See the Phoenix.Presence docs for more details:
https://hexdocs.pm/phoenix/Phoenix.Presence.html
```
If we open up the `lib/hello_web/channels/presence.ex` file, we will see the following line:
```
use Phoenix.Presence,
otp_app: :hello,
pubsub_server: Hello.PubSub
```
This sets up the module for presence, defining the functions we require for tracking presences. As mentioned in the generator task, we should add this module to our supervision tree in `application.ex`:
```
children = [
...
HelloWeb.Presence,
]
```
Next, we will create the channel that we'll communicate presence over. After a user joins, we can push the list of presences down the channel and then track the connection. We can also provide a map of additional information to track.
```
defmodule HelloWeb.RoomChannel do
use Phoenix.Channel
alias HelloWeb.Presence
def join("room:lobby", %{"name" => name}, socket) do
send(self(), :after_join)
{:ok, assign(socket, :name, name)}
end
def handle_info(:after_join, socket) do
{:ok, _} =
Presence.track(socket, socket.assigns.name, %{
online_at: inspect(System.system_time(:second))
})
push(socket, "presence_state", Presence.list(socket))
{:noreply, socket}
end
end
```
Finally, we can use the client-side Presence library included in `phoenix.js` to manage the state and presence diffs that come down the socket. It listens for the `"presence_state"` and `"presence_diff"` events and provides a simple callback for you to handle the events as they happen, with the `onSync` callback.
The `onSync` callback allows you to easily react to presence state changes, which most often results in re-rendering an updated list of active users. You can use the `list` method to format and return each individual presence based on the needs of your application.
To iterate users, we use the `presences.list()` function which accepts a callback. The callback will be called for each presence item with 2 arguments, the presence id and a list of metas (one for each presence for that presence id). We use this to display the users and the number of devices they are online with.
We can see presence working by adding the following to `assets/js/app.js`:
```
import {Socket, Presence} from "phoenix"
let socket = new Socket("/socket", {params: {token: window.userToken}})
let channel = socket.channel("room:lobby", {name: window.location.search.split("=")[1])
let presence = new Presence(channel)
function renderOnlineUsers(presence) {
let response = ""
presence.list((id, {metas: [first, ...rest]}) => {
let count = rest.length + 1
response += `<br>${id} (count: ${count})</br>`
})
document.querySelector("main[role=main]").innerHTML = response
}
socket.connect()
presence.onSync(() => renderOnlineUsers(presence))
channel.join()
```
We can ensure this is working by opening 3 browser tabs. If we navigate to <http://localhost:4000/?name=Alice> on two browser tabs and <http://localhost:4000/?name=Bob> then we should see:
```
Alice (count: 2)
Bob (count: 1)
```
If we close one of the Alice tabs, then the count should decrease to 1. If we close another tab, the user should disappear from the list entirely.
Making it safe
---------------
In our initial implementation, we are passing the name of the user as part of the URL. However, in many systems, you want to allow only logged in users to access the presence functionality. To do so, you should set up token authentication, [as detailed in the token authentication section of the channels guide](channels#using-token-authentication).
With token authentication, you should access `socket.assigns.user_id`, set in `UserSocket`, instead of `socket.assigns.name` set from parameters.
[← Previous Page Channels](channels) [Next Page → Introduction to Testing](testing)
phoenix mix phx.gen.release mix phx.gen.release
====================
Generates release files and optional Dockerfile for release-based deployments.
The following release files are created:
* `lib/app_name/release.ex` - A release module containing tasks for running migrations inside a release
* `rel/overlays/bin/migrate` - A migrate script for conveniently invoking the release system migrations
* `rel/overlays/bin/server` - A server script for conveniently invoking the release system with environment variables to start the phoenix web server
Note, the `rel/overlays` directory is copied into the release build by default when running [`mix release`](https://hexdocs.pm/mix/Mix.Tasks.Release.html).
To skip generating the migration-related files, use the `--no-ecto` flag. To force these migration-related files to be generated, the use `--ecto` flag.
Docker
-------
When the `--docker` flag is passed, the following docker files are generated:
* `Dockerfile` - The Dockerfile for use in any standard docker deployment
* `.dockerignore` - A docker ignore file with standard elixir defaults
For extended release configuration, the [`mix release.init`](https://hexdocs.pm/mix/Mix.Tasks.Release.Init.html)task can be used in addition to this task. See the [`Mix.Release`](https://hexdocs.pm/mix/Mix.Release.html) docs for more details.
Summary
========
Functions
----------
[otp\_vsn()](#otp_vsn/0) Functions
==========
### otp\_vsn()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/mix/tasks/phx.gen.release.ex#L192)
phoenix Deploying on Gigalixir Deploying on Gigalixir
=======================
What we'll need
----------------
The only thing we'll need for this guide is a working Phoenix application. For those of us who need a simple application to deploy, please follow the [Up and Running guide](up_and_running).
Goals
------
Our main goal for this guide is to get a Phoenix application running on Gigalixir.
Steps
------
Let's separate this process into a few steps, so we can keep track of where we are.
* Initialize Git repository
* Install the Gigalixir CLI
* Sign up for Gigalixir
* Create and set up Gigalixir application
* Provision a database
* Make our project ready for Gigalixir
* Deploy time!
* Useful Gigalixir commands
Initializing Git repository
----------------------------
If you haven't already, we'll need to commit our files to git. We can do so by running the following commands in our project directory:
```
$ git init
$ git add .
$ git commit -m "Initial commit"
```
Installing the Gigalixir CLI
-----------------------------
Follow the instructions [here](https://gigalixir.readthedocs.io/en/latest/getting-started-guide.html#install-the-command-line-interface) to install the command-line interface for your platform.
Signing up for Gigalixir
-------------------------
We can sign up for an account at [gigalixir.com](https://www.gigalixir.com) or with the CLI. Let's use the CLI.
```
$ gigalixir signup
```
Gigalixir’s free tier does not require a credit card and comes with 1 app instance and 1 PostgreSQL database for free, but please consider upgrading to a paid plan if you are running a production application.
Next, let's login
```
$ gigalixir login
```
And verify
```
$ gigalixir account
```
Creating and setting up our Gigalixir application
--------------------------------------------------
There are three different ways to deploy a Phoenix app on Gigalixir: with mix, with Elixir's releases, or with Distillery. In this guide, we'll be using Mix because it is the easiest to get up and running, but you won't be able to connect a remote observer or hot upgrade. For more information, see [Mix vs Distillery vs Elixir Releases](https://gigalixir.readthedocs.io/en/latest/modify-app/index.html#mix-vs-distillery-vs-elixir-releases). If you want to deploy with another method, follow the [Getting Started Guide](https://gigalixir.readthedocs.io/en/latest/getting-started-guide.html).
### Creating a Gigalixir application
Let's create a Gigalixir application
```
$ gigalixir create -n "your_app_name"
```
Note: the app name cannot be changed afterwards. A random name is used if you do not provide one.
Verify the app was created
```
$ gigalixir apps
```
Verify that a git remote was created
```
$ git remote -v
```
### Specifying versions
The buildpacks we use default to Elixir, Erlang, and Node.js versions that are quite old and it's generally a good idea to run the same version in production as you do in development, so let's do that.
```
$ echo 'elixir_version=1.10.3' > elixir_buildpack.config
$ echo 'erlang_version=22.3' >> elixir_buildpack.config
$ echo 'node_version=12.16.3' > phoenix_static_buildpack.config
```
Phoenix v1.6 uses `esbuild` to compile your assets, but all Gigalixir images come with `npm`, so we will configure `npm` directly to deploy our assets. Add a `assets/package.json` file if you don't have any with the following:
```
{
"scripts": {
"deploy": "cd .. && mix assets.deploy && rm -f _build/esbuild*"
}
}
```
Finally, don't forget to commit:
```
$ git add elixir_buildpack.config phoenix_static_buildpack.config assets/package.json
$ git commit -m "Set Elixir, Erlang, and Node version"
```
Making our Project ready for Gigalixir
---------------------------------------
There's nothing we need to do to get our app running on Gigalixir, but for a production app, you probably want to enforce SSL. To do that, see [Force SSL](using_ssl#force-ssl)
You may also want to use SSL for your database connection. For that, uncomment the line `ssl: true` in your `Repo` config.
Provisioning a database
------------------------
Let's provision a database for our app
```
$ gigalixir pg:create --free
```
Verify the database was created
```
$ gigalixir pg
```
Verify that a `DATABASE_URL` and `POOL_SIZE` were created
```
$ gigalixir config
```
Deploy Time!
-------------
Our project is now ready to be deployed on Gigalixir.
```
$ git push gigalixir
```
Check the status of your deploy and wait until the app is `Healthy`
```
$ gigalixir ps
```
Run migrations
```
$ gigalixir run mix ecto.migrate
```
Check your app logs
```
$ gigalixir logs
```
If everything looks good, let's take a look at your app running on Gigalixir
```
$ gigalixir open
```
Useful Gigalixir Commands
--------------------------
Open a remote console
```
$ gigalixir account:ssh_keys:add "$(cat ~/.ssh/id_rsa.pub)"
$ gigalixir ps:remote_console
```
To open a remote observer, see [Remote Observer](https://gigalixir.readthedocs.io/en/latest/runtime.html#how-to-launch-a-remote-observer)
To set up clustering, see [Clustering Nodes](https://gigalixir.readthedocs.io/en/latest/cluster.html)
To hot upgrade, see [Hot Upgrades](https://gigalixir.readthedocs.io/en/latest/deploy.html#how-to-hot-upgrade-an-app)
For custom domains, scaling, jobs and other features, see the [Gigalixir Documentation](https://gigalixir.readthedocs.io/)
Troubleshooting
----------------
See [Troubleshooting](https://gigalixir.readthedocs.io/en/latest/troubleshooting.html)
Also, don't hesitate to email [[email protected]](mailto:[email protected]) or [request an invitation](https://elixir-slackin.herokuapp.com/) and join the #gigalixir channel on [Slack](https://elixir-lang.slack.com).
[← Previous Page Deploying with Releases](releases) [Next Page → Deploying on Fly.io](fly)
phoenix Introduction to Deployment Introduction to Deployment
===========================
Once we have a working application, we're ready to deploy it. If you're not quite finished with your own application, don't worry. Just follow the [Up and Running Guide](up_and_running) to create a basic application to work with.
When preparing an application for deployment, there are three main steps:
* Handling of your application secrets
* Compiling your application assets
* Starting your server in production
In this guide, we will learn how to get the production environment running locally. You can use the same techniques in this guide to run your application in production, but depending on your deployment infrastructure, extra steps will be necessary.
As an example of deploying to other infrastructures, we also discuss four different approaches in our guides: using [Elixir's releases](releases) with [`mix release`](https://hexdocs.pm/mix/Mix.Tasks.Release.html), [using Gigalixir](gigalixir), [using Fly](fly), and [using Heroku](heroku). We've also included links to deploying Phoenix on other platforms under [Community Deployment Guides](#community-deployment-guides). Finally, the release guide has a sample Dockerfile you can use if you prefer to deploy with container technologies.
Let's explore those steps above one by one.
Handling of your application secrets
-------------------------------------
All Phoenix applications have data that must be kept secure, for example, the username and password for your production database, and the secret Phoenix uses to sign and encrypt important information. The general recommendation is to keep those in environment variables and load them into your application. This is done in `config/runtime.exs` (formerly `config/prod.secret.exs` or `config/releases.exs`), which is responsible for loading secrets and configuration from environment variables.
Therefore, you need to make sure the proper relevant variables are set in production:
```
$ mix phx.gen.secret
REALLY_LONG_SECRET
$ export SECRET_KEY_BASE=REALLY_LONG_SECRET
$ export DATABASE_URL=ecto://USER:PASS@HOST/database
```
Do not copy those values directly, set `SECRET_KEY_BASE` according to the result of [`mix phx.gen.secret`](mix.tasks.phx.gen.secret) and `DATABASE_URL` according to your database address.
If for some reason you do not want to rely on environment variables, you can hard code the secrets in your `config/runtime.exs` but make sure not to check the file into your version control system.
With your secret information properly secured, it is time to configure assets!
Before taking this step, we need to do one bit of preparation. Since we will be readying everything for production, we need to do some setup in that environment by getting our dependencies and compiling.
```
$ mix deps.get --only prod
$ MIX_ENV=prod mix compile
```
Compiling your application assets
----------------------------------
This step is required only if you have compilable assets like JavaScript and stylesheets. By default, Phoenix uses `esbuild` but everything is encapsulated in a single `mix assets.deploy` task defined in your `mix.exs`:
```
$ MIX_ENV=prod mix assets.deploy
Check your digested files at "priv/static".
```
And that is it! The Mix task by default builds the assets and then generates digests with a cache manifest file so Phoenix can quickly serve assets in production.
> Note: if you run the task above in your local machine, it will generate many digested assets in `priv/static`. You can prune them by running `mix phx.digest.clean --all`.
>
>
Keep in mind that, if you by any chance forget to run the steps above, Phoenix will show an error message:
```
$ PORT=4001 MIX_ENV=prod mix phx.server
10:50:18.732 [info] Running MyAppWeb.Endpoint with Cowboy on http://example.com
10:50:18.735 [error] Could not find static manifest at "my_app/_build/prod/lib/foo/priv/static/cache_manifest.json". Run "mix phx.digest" after building your static files or remove the configuration from "config/prod.exs".
```
The error message is quite clear: it says Phoenix could not find a static manifest. Just run the commands above to fix it or, if you are not serving or don't care about assets at all, you can just remove the `cache_static_manifest` configuration from `config/prod.exs`.
Starting your server in production
-----------------------------------
To run Phoenix in production, we need to set the [`PORT`](port) and `MIX_ENV` environment variables when invoking [`mix phx.server`](mix.tasks.phx.server):
```
$ PORT=4001 MIX_ENV=prod mix phx.server
10:59:19.136 [info] Running MyAppWeb.Endpoint with Cowboy on http://example.com
```
To run in detached mode so that the Phoenix server does not stop and continues to run even if you close the terminal:
```
$ PORT=4001 MIX_ENV=prod elixir --erl "-detached" -S mix phx.server
```
In case you get an error message, please read it carefully, and open up a bug report if it is still not clear how to address it.
You can also run your application inside an interactive shell:
```
$ PORT=4001 MIX_ENV=prod iex -S mix phx.server
10:59:19.136 [info] Running MyAppWeb.Endpoint with Cowboy on http://example.com
```
Putting it all together
------------------------
The previous sections give an overview about the main steps required to deploy your Phoenix application. In practice, you will end-up adding steps of your own as well. For example, if you are using a database, you will also want to run [`mix ecto.migrate`](https://hexdocs.pm/ecto_sql/3.8.1/Mix.Tasks.Ecto.Migrate.html) before starting the server to ensure your database is up to date.
Overall, here is a script you can use as a starting point:
```
# Initial setup
$ mix deps.get --only prod
$ MIX_ENV=prod mix compile
# Compile assets
$ MIX_ENV=prod mix assets.deploy
# Custom tasks (like DB migrations)
$ MIX_ENV=prod mix ecto.migrate
# Finally run the server
$ PORT=4001 MIX_ENV=prod mix phx.server
```
And that's it. Next, you can use one of our official guides to deploy:
* [with Elixir's releases](releases)
* [to Gigalixir](gigalixir), an Elixir-centric Platform as a Service (PaaS)
* [to Fly.io](fly), a PaaS that deploys your servers close to your users with built-in distribution support
* and [to Heroku](heroku), one of the most popular PaaS.
Community Deployment Guides
----------------------------
* [Render](https://render.com) has first class support for Phoenix applications. There are guides for hosting Phoenix with [Mix releases](https://render.com/docs/deploy-phoenix), [Distillery](https://render.com/docs/deploy-phoenix-distillery), and as a [Distributed Elixir Cluster](https://render.com/docs/deploy-elixir-cluster).
[← Previous Page Testing Channels](testing_channels) [Next Page → Deploying with Releases](releases)
| programming_docs |
phoenix Deploying on Fly.io Deploying on Fly.io
====================
What we'll need
----------------
The only thing we'll need for this guide is a working Phoenix application. For those of us who need a simple application to deploy, please follow the [Up and Running guide](up_and_running).
You can just:
```
$ mix phx.new my_app
```
Goals
------
The main goal for this guide is to get a Phoenix application running on [Fly.io](https://fly.io).
Sections
---------
Let's separate this process into a few steps, so we can keep track of where we are.
* Install the Fly.io CLI
* Sign up for Fly.io
* Deploy the app to Fly.io
* Extra Fly.io tips
* Helpful Fly.io resources
Installing the Fly.io CLI
--------------------------
Follow the instructions [here](https://fly.io/docs/getting-started/installing-flyctl/) to install Flyctl, the command-line interface for the Fly.io platform.
Sign up for Fly.io
-------------------
We can [sign up for an account](https://fly.io/docs/getting-started/login-to-fly/) using the CLI.
```
$ fly auth signup
```
Or sign in.
```
$ flyctl auth login
```
Fly has a [free tier](https://fly.io/docs/about/pricing/) for most applications. A credit card is required when setting up an account to help prevent abuse. See the [pricing](https://fly.io/docs/about/pricing/) page for more details.
Deploy the app to Fly.io
-------------------------
To tell Fly about your application, run `fly launch` in the directory with your source code. This creates and configures a Fly.io app.
```
$ fly launch
```
This scans your source, detects the Phoenix project, and runs `mix phx.gen.release --docker` for you! This creates a Dockerfile for you.
The `fly launch` command walks you through a few questions.
* You can name the app or have it generate a random name for you.
* Choose an organization (defaults to `personal`). Organizations are a way of sharing applications and resources between Fly.io users.
* Choose a region to deploy to. Defaults to the nearest Fly.io region. You can check out the [complete list of regions here](https://fly.io/docs/reference/regions/).
* Sets up a Postgres DB for you.
* Builds the Dockerfile.
* Deploys your application!
The `fly launch` command also created a `fly.toml` file for you. This is where you can set ENV values and other config.
### Storing secrets on Fly.io
You may also have some secrets you'd like to set on your app.
Use [`fly secrets`](https://fly.io/docs/reference/secrets/#setting-secrets) to configure those.
```
$ fly secrets set MY_SECRET_KEY=my_secret_value
```
### Deploying again
When you want to deploy changes to your application, use `fly deploy`.
```
$ fly deploy
```
Note: On Apple Silicon (M1) computers, docker runs cross-platform builds using qemu which might not always work. If you get a segmentation fault error like the following:
```
=> [build 7/17] RUN mix deps.get --only
=> => # qemu: uncaught target signal 11 (Segmentation fault) - core dumped
```
You can use fly's remote builder by adding the `--remote-only` flag:
```
$ fly deploy --remote-only
```
You can always check on the status of a deploy
```
$ fly status
```
Check your app logs
```
$ fly logs
```
If everything looks good, open your app on Fly
```
$ fly open
```
Extra Fly.io tips
------------------
### Getting an IEx shell into a running node
Elixir supports getting a IEx shell into a running production node.
There are a couple prerequisites, we first need to establish an [SSH Shell](https://fly.io/docs/flyctl/ssh/) to our machine on Fly.io.
This step sets up a root certificate for your account and then issues a certificate.
```
$ fly ssh establish
$ fly ssh issue
```
With SSH configured, let's open a console.
```
$ fly ssh console
Connecting to my-app-1234.internal... complete
/ #
```
If all has gone smoothly, then you have a shell into the machine! Now we just need to launch our remote IEx shell. The deployment Dockerfile was configured to pull our application into `/app`. So the command for an app named `my_app` looks like this:
```
$ app/bin/my_app remote
Erlang/OTP 23 [erts-11.2.1] [source] [64-bit] [smp:1:1] [ds:1:1:10] [async-threads:1]
Interactive Elixir (1.11.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(my_app@fdaa:0:1da8:a7b:ac4:b204:7e29:2)1>
```
Now we have a running IEx shell into our node! You can safely disconnect using CTRL+C, CTRL+C.
### Clustering your application
Elixir and the BEAM have the incredible ability to be clustered together and pass messages seamlessly between nodes. This portion of the guide walks you through clustering your Elixir application.
There are 2 parts to getting clustering quickly setup on Fly.io.
* Installing and using `libcluster`
* Scaling the application to multiple instances
#### Adding `libcluster`
The widely adopted library [libcluster](https://github.com/bitwalker/libcluster) helps here.
There are multiple strategies that `libcluster` can use to find and connect with other nodes. The strategy we'll use on Fly.io is `DNSPoll`.
After installing `libcluster`, add it to the application like this:
```
defmodule MyApp.Application do
use Application
def start(_type, _args) do
topologies = Application.get_env(:libcluster, :topologies) || []
children = [
# ...
# setup for clustering
{Cluster.Supervisor, [topologies, [name: MyApp.ClusterSupervisor]]}
]
# ...
end
# ...
end
```
Our next step is to add the `topologies` configuration to `config/runtime.exs`.
```
app_name =
System.get_env("FLY_APP_NAME") ||
raise "FLY_APP_NAME not available"
config :libcluster,
topologies: [
fly6pn: [
strategy: Cluster.Strategy.DNSPoll,
config: [
polling_interval: 5_000,
query: "#{app_name}.internal",
node_basename: app_name
]
]
]
```
This configures `libcluster` to use the `DNSPoll` strategy and look for other deployed apps using the `$FLY_APP_NAME` on the `.internal` private network.
#### Controlling the name for our node
We need to control the naming of our Elixir nodes. To help them connect up, we'll name them using this pattern: `[email protected]`. To do this, we'll generate the release config.
```
$ mix release.init
```
Then edit the generated `rel/env.sh.eex` file and add the following lines:
```
ip=$(grep fly-local-6pn /etc/hosts | cut -f 1)
export RELEASE_DISTRIBUTION=name
export RELEASE_NODE=$FLY_APP_NAME@$ip
```
After making the change, deploy your app!
```
$ fly deploy
```
For our app to be clustered, we have to have multiple instances. Next we'll add an additional node instance.
#### Running multiple instances
There are two ways to run multiple instances.
1. Scale our application to have multiple instances in one region.
2. Add an instance to another region (multiple regions).
Let's first start with a baseline of our single deployment.
```
$ fly status
...
Instances
ID VERSION REGION DESIRED STATUS HEALTH CHECKS RESTARTS CREATED
f9014bf7 26 sea run running 1 total, 1 passing 0 1h8m ago
```
#### Scaling in a single region
Let's scale up to 2 instances in our current region.
```
$ fly scale count 2
Count changed to 2
```
Checking the status, we can see what happened.
```
$ fly status
...
Instances
ID VERSION REGION DESIRED STATUS HEALTH CHECKS RESTARTS CREATED
eb4119d3 27 sea run running 1 total, 1 passing 0 39s ago
f9014bf7 27 sea run running 1 total, 1 passing 0 1h13m ago
```
We now have two instances in the same region.
Let's make sure they are clustered together. We can check the logs:
```
$ fly logs
...
app[eb4119d3] sea [info] 21:50:21.924 [info] [libcluster:fly6pn] connected to :"my-app-1234@fdaa:0:1da8:a7b:ac2:f901:4bf7:2"
...
```
But that's not as rewarding as seeing it from inside a node. From an IEx shell, we can ask the node we're connected to, what other nodes it can see.
```
$ fly ssh console
$ /app/bin/my_app remote
```
```
iex(my-app-1234@fdaa:0:1da8:a7b:ac2:f901:4bf7:2)1> Node.list
[:"my-app-1234@fdaa:0:1da8:a7b:ac4:eb41:19d3:2"]
```
The IEx prompt is included to help show the IP address of the node we are connected to. Then getting the `Node.list` returns the other node. Our two instances are connected and clustered!
#### Scaling to multiple regions
Fly makes it easy to deploy instances closer to your users. Through the magic of DNS, users are directed to the nearest region where your application is located. You can read more about [Fly.io regions here](https://fly.io/docs/reference/regions/).
Starting back from our baseline of a single instance running in `sea` which is Seattle, Washington (US), let's add the region `ewr` which is Parsippany, NJ (US). This puts an instance on both coasts of the US.
```
$ fly regions add ewr
Region Pool:
ewr
sea
Backup Region:
iad
lax
sjc
vin
```
Looking at the status shows that we're only in 1 region because our count is set to 1.
```
$ fly status
...
Instances
ID VERSION REGION DESIRED STATUS HEALTH CHECKS RESTARTS CREATED
cdf6c422 29 sea run running 1 total, 1 passing 0 58s ago
```
Let's add a 2nd instance and see it deploy to `ewr`.
```
$ fly scale count 2
Count changed to 2
```
Now the status shows we have two instances spread across 2 regions!
```
$ fly status
...
Instances
ID VERSION REGION DESIRED STATUS HEALTH CHECKS RESTARTS CREATED
0a8e6666 30 ewr run running 1 total, 1 passing 0 16s ago
cdf6c422 30 sea run running 1 total, 1 passing 0 6m47s ago
```
Let's ensure they are clustered together.
```
$ fly ssh console
$ /app/bin/my_app remote
```
```
iex(my-app-1234@fdaa:0:1da8:a7b:ac2:cdf6:c422:2)1> Node.list
[:"my-app-1234@fdaa:0:1da8:a7b:ab2:a8e:6666:2"]
```
We have two instances of our application deployed to the West and East coasts of the North American continent and they are clustered together! Our users will automatically be directed to the server nearest them.
The Fly.io platform has built-in distribution support making it easy to cluster distributed Elixir nodes in multiple regions.
Helpful Fly.io resources
-------------------------
Open the Dashboard for your account
```
$ fly dashboard
```
Deploy your application
```
$ fly deploy
```
Show the status of your deployed application
```
$ fly status
```
Access and tail the logs
```
$ fly logs
```
Scaling your application up or down
```
$ fly scale count 2
```
Refer to the [Fly.io Elixir documentation](https://fly.io/docs/getting-started/elixir) for additional information.
[Working with Fly.io applications](https://fly.io/docs/getting-started/working-with-fly-apps/) covers things like:
* Status and logs
* Custom domains
* Certificates
Troubleshooting
----------------
See [Troubleshooting](https://fly.io/docs/getting-started/troubleshooting/#welcome-message)
Visit the [Fly.io Community](https://community.fly.io/) to find solutions and ask questions.
[← Previous Page Deploying on Gigalixir](gigalixir) [Next Page → Deploying on Heroku](heroku)
phoenix Directory structure Directory structure
====================
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
When we use [`mix phx.new`](mix.tasks.phx.new) to generate a new Phoenix application, it builds a top-level directory structure like this:
```
├── _build
├── assets
├── config
├── deps
├── lib
│ ├── hello
│ ├── hello.ex
│ ├── hello_web
│ └── hello_web.ex
├── priv
└── test
```
We will go over those directories one by one:
* `_build` - a directory created by the `mix` command line tool that ships as part of Elixir that holds all compilation artifacts. As we have seen in "[Up and Running](up_and_running)", `mix` is the main interface to your application. We use Mix to compile our code, create databases, run our server, and more. This directory must not be checked into version control and it can be removed at any time. Removing it will force Mix to rebuild your application from scratch.
* `assets` - a directory that keeps everything related to source front-end assets, such as JavaScript and CSS, and automatically managed by the `esbuild` tool.
* `config` - a directory that holds your project configuration. The `config/config.exs` file is the entry point for your configuration. At the end of the `config/config.exs`, it imports environment specific configuration, which can be found in `config/dev.exs`, `config/test.exs`, and `config/prod.exs`. Finally, `config/runtime.exs` is executed and it is the best place to read secrets and other dynamic configuration.
* `deps` - a directory with all of our Mix dependencies. You can find all dependencies listed in the `mix.exs` file, inside the `defp deps do` function definition. This directory must not be checked into version control and it can be removed at any time. Removing it will force Mix to download all deps from scratch.
* `lib` - a directory that holds your application source code. This directory is broken into two subdirectories, `lib/hello` and `lib/hello_web`. The `lib/hello` directory will be responsible to host all of your business logic and business domain. It typically interacts directly with the database - it is the "Model" in Model-View-Controller (MVC) architecture. `lib/hello_web` is responsible for exposing your business domain to the world, in this case, through a web application. It holds both the View and Controller from MVC. We will discuss the contents of these directories with more detail in the next sections.
* `priv` - a directory that keeps all resources that are necessary in production but are not directly part of your source code. You typically keep database scripts, translation files, and more in here. Static and generated assets, sourced from the `assets` directory, are also served from here by default.
* `test` - a directory with all of our application tests. It often mirrors the same structure found in `lib`.
The lib/hello directory
------------------------
The `lib/hello` directory hosts all of your business domain. Since our project does not have any business logic yet, the directory is mostly empty. You will only find three files:
```
lib/hello
├── application.ex
├── mailer.ex
└── repo.ex
```
The `lib/hello/application.ex` file defines an Elixir application named `Hello.Application`. That's because at the end of the day Phoenix applications are simply Elixir applications. The `Hello.Application` module defines which services are part of our application:
```
children = [
# Start the Ecto repository
Hello.Repo,
# Start the Telemetry supervisor
HelloWeb.Telemetry,
# Start the PubSub system
{Phoenix.PubSub, name: Hello.PubSub},
# Start the Endpoint (http/https)
HelloWeb.Endpoint
# Start a worker by calling: Hello.Worker.start_link(arg)
# {Hello.Worker, arg}
]
```
If it is your first time with Phoenix, you don't need to worry about the details right now. For now, suffice it to say our application starts a database repository, a PubSub system for sharing messages across processes and nodes, and the application endpoint, which effectively serves HTTP requests. These services are started in the order they are defined and, whenever shutting down your application, they are stopped in the reverse order.
You can learn more about applications in [Elixir's official docs for Application](https://hexdocs.pm/elixir/Application.html).
The `lib/hello/mailer.ex` file holds the `Hello.Mailer` module, which defines the main interface to deliver e-mails:
```
defmodule Hello.Mailer do
use Swoosh.Mailer, otp_app: :hello
end
```
In the same `lib/hello` directory, we will find a `lib/hello/repo.ex`. It defines a `Hello.Repo` module which is our main interface to the database. If you are using Postgres (the default database), you will see something like this:
```
defmodule Hello.Repo do
use Ecto.Repo,
otp_app: :hello,
adapter: Ecto.Adapters.Postgres
end
```
And that's it for now. As you work on your project, we will add files and modules to this directory.
The lib/hello\_web directory
-----------------------------
The `lib/hello_web` directory holds the web-related parts of our application. It looks like this when expanded:
```
lib/hello_web
├── controllers
│ └── page_controller.ex
├── templates
│ ├── layout
│ │ ├── app.html.heex
│ │ ├── live.html.heex
│ │ └── root.html.heex
│ └── page
│ └── index.html.heex
├── views
│ ├── error_helpers.ex
│ ├── error_view.ex
│ ├── layout_view.ex
│ └── page_view.ex
├── endpoint.ex
├── gettext.ex
├── router.ex
└── telemetry.ex
```
All of the files which are currently in the `controllers`, `templates`, and `views` directories are there to create the "Welcome to Phoenix!" page we saw in the "[Up and running](up_and_running)" guide.
By looking at `templates` and `views` directories, we can see Phoenix provides features for handling layouts and error pages out of the box.
Besides the directories mentioned, `lib/hello_web` has four files at its root. `lib/hello_web/endpoint.ex` is the entry-point for HTTP requests. Once the browser accesses <http://localhost:4000>, the endpoint starts processing the data, eventually leading to the router, which is defined in `lib/hello_web/router.ex`. The router defines the rules to dispatch requests to "controllers", which then uses "views" and "templates" to render HTML pages back to clients. We explore these layers in length in other guides, starting with the "[Request life-cycle](request_lifecycle)" guide coming next.
Through *Telemetry*, Phoenix is able to collect metrics and send monitoring events of your application. The `lib/hello_web/telemetry.ex` file defines the supervisor responsible for managing the telemetry processes. You can find more information on this topic in the [Telemetry guide](telemetry).
Finally, there is a `lib/hello_web/gettext.ex` file which provides internationalization through [Gettext](https://hexdocs.pm/gettext/Gettext.html). If you are not worried about internationalization, you can safely skip this file and its contents.
The assets directory
---------------------
The `assets` directory contains source files related to front-end assets, such as JavaScript and CSS. Since Phoenix v1.6, we use [`esbuild`](https://github.com/evanw/esbuild/) to compile assets, which is managed by the [`esbuild`](https://github.com/phoenixframework/esbuild) Elixir package. The integration with `esbuild` is baked into your app. The relevant config can be found in your `config/config.exs` file.
Your other static assets are placed in the `priv/static` folder, where `priv/static/assets` is kept for generated assets. Everything in `priv/static` is served by the [`Plug.Static`](https://hexdocs.pm/plug/1.13.6/Plug.Static.html) plug configured in `lib/hello_web/endpoint.ex`. When running in dev mode (`MIX_ENV=dev`), Phoenix watches for any changes you make in the `assets` directory, and then takes care of updating your front end application in your browser as you work.
Note that when you first create your Phoenix app using [`mix phx.new`](mix.tasks.phx.new) it is possible to specify options that will affect the presence and layout of the `assets` directory. In fact, Phoenix apps can bring their own front end tools or not have a front-end at all (handy if you're writing an API for example). For more information you can run [`mix help phx.new`](mix.tasks.phx.new) or see the documentation in [Mix tasks](mix_tasks).
If the default esbuild integration does not cover your needs, for example because you want to use another build tool, you can switch to a [custom assets build](asset_management#custom_builds).
As for CSS, Phoenix ships with a handful of custom styles as well as the [Milligram CSS Framework](https://milligram.io/), providing a minimal setup for projects. You may move to any CSS framework of your choice. Additional references can be found in the [asset management](asset_management#css) guide.
[← Previous Page Community](community) [Next Page → Request life-cycle](request_lifecycle)
| programming_docs |
phoenix Phoenix.Digester.Gzip Phoenix.Digester.Gzip
======================
Gzip compressor for Phoenix.Digester
Summary
========
Functions
----------
[compress\_file(file\_path, content)](#compress_file/2) Callback implementation for [`Phoenix.Digester.Compressor.compress_file/2`](phoenix.digester.compressor#c:compress_file/2).
[file\_extensions()](#file_extensions/0) Callback implementation for [`Phoenix.Digester.Compressor.file_extensions/0`](phoenix.digester.compressor#c:file_extensions/0).
Functions
==========
### compress\_file(file\_path, content)[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/digester/gzip.ex#L7)
Callback implementation for [`Phoenix.Digester.Compressor.compress_file/2`](phoenix.digester.compressor#c:compress_file/2).
### file\_extensions()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/digester/gzip.ex#L15)
Callback implementation for [`Phoenix.Digester.Compressor.file_extensions/0`](phoenix.digester.compressor#c:file_extensions/0).
phoenix Plug Plug
=====
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [Request life-cycle guide](request_lifecycle).
>
>
Plug lives at the heart of Phoenix's HTTP layer, and Phoenix puts Plug front and center. We interact with plugs at every step of the request life-cycle, and the core Phoenix components like endpoints, routers, and controllers are all just plugs internally. Let's jump in and find out just what makes Plug so special.
[Plug](https://github.com/elixir-lang/plug) is a specification for composable modules in between web applications. It is also an abstraction layer for connection adapters of different web servers. The basic idea of Plug is to unify the concept of a "connection" that we operate on. This differs from other HTTP middleware layers such as Rack, where the request and response are separated in the middleware stack.
At the simplest level, the Plug specification comes in two flavors: *function plugs* and *module plugs*.
Function plugs
---------------
In order to act as a plug, a function needs to:
1. accept a connection struct (`%Plug.Conn{}`) as its first argument, and connection options as its second one;
2. return a connection struct.
Any function that meets these two criteria will do. Here's an example.
```
def introspect(conn, _opts) do
IO.puts """
Verb: #{inspect(conn.method)}
Host: #{inspect(conn.host)}
Headers: #{inspect(conn.req_headers)}
"""
conn
end
```
This function does the following:
1. It receives a connection and options (that we do not use)
2. It prints some connection information to the terminal
3. It returns the connection
Pretty simple, right? Let's see this function in action by adding it to our endpoint in `lib/hello_web/endpoint.ex`. We can plug it anywhere, so let's do it by inserting `plug :introspect` right before we delegate the request to the router:
```
defmodule HelloWeb.Endpoint do
...
plug :introspect
plug HelloWeb.Router
def introspect(conn, _opts) do
IO.puts """
Verb: #{inspect(conn.method)}
Host: #{inspect(conn.host)}
Headers: #{inspect(conn.req_headers)}
"""
conn
end
end
```
Function plugs are plugged by passing the function name as an atom. To try the plug out, go back to your browser and fetch <http://localhost:4000>. You should see something like this printed in your shell terminal:
```
Verb: "GET"
Host: "localhost"
Headers: [...]
```
Our plug simply prints information from the connection. Although our initial plug is very simple, you can do virtually anything you want inside of it. To learn about all fields available in the connection and all of the functionality associated to it, see the [documentation for `Plug.Conn`](../plug/plug.conn).
Now let's look at the other plug variant, the module plugs.
Module plugs
-------------
Module plugs are another type of plug that let us define a connection transformation in a module. The module only needs to implement two functions:
* [`init/1`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:init/1) which initializes any arguments or options to be passed to [`call/2`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:call/2)
* [`call/2`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:call/2) which carries out the connection transformation. [`call/2`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:call/2) is just a function plug that we saw earlier
To see this in action, let's write a module plug that puts the `:locale` key and value into the connection assign for downstream use in other plugs, controller actions, and our views. Put the contents below in a file named `lib/hello_web/plugs/locale.ex`:
```
defmodule HelloWeb.Plugs.Locale do
import Plug.Conn
@locales ["en", "fr", "de"]
def init(default), do: default
def call(%Plug.Conn{params: %{"locale" => loc}} = conn, _default) when loc in @locales do
assign(conn, :locale, loc)
end
def call(conn, default) do
assign(conn, :locale, default)
end
end
```
To give it a try, let's add this module plug to our router, by appending `plug HelloWeb.Plugs.Locale, "en"` to our `:browser` pipeline in `lib/hello_web/router.ex`:
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
plug HelloWeb.Plugs.Locale, "en"
end
...
```
In the [`init/1`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:init/1) callback, we pass a default locale to use if none is present in the params. We also use pattern matching to define multiple [`call/2`](https://hexdocs.pm/plug/1.13.6/Plug.html#c:call/2) function heads to validate the locale in the params, and fall back to `"en"` if there is no match. The [`assign/3`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html#assign/3) is a part of the [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html) module and it's how we store values in the `conn` data structure.
To see the assign in action, go to the layout in `lib/hello_web/templates/layout/app.html.heex` and add the following close to the main container:
```
<main class="container">
<p>Locale: <%= @locale %></p>
```
Go to <http://localhost:4000/> and you should see the locale exhibited. Visit <http://localhost:4000/?locale=fr> and you should see the assign changed to `"fr"`. Someone can use this information alongside [Gettext](https://hexdocs.pm/gettext/Gettext.html) to provide a fully internationalized web application.
That's all there is to Plug. Phoenix embraces the plug design of composable transformations all the way up and down the stack. Let's see some examples!
Where to plug
--------------
The endpoint, router, and controllers in Phoenix accept plugs.
### Endpoint plugs
Endpoints organize all the plugs common to every request, and apply them before dispatching into the router with its custom pipelines. We added a plug to the endpoint like this:
```
defmodule HelloWeb.Endpoint do
...
plug :introspect
plug HelloWeb.Router
```
The default endpoint plugs do quite a lot of work. Here they are in order:
* [`Plug.Static`](https://hexdocs.pm/plug/1.13.6/Plug.Static.html) - serves static assets. Since this plug comes before the logger, requests for static assets are not logged.
* `Phoenix.LiveDashboard.RequestLogger` - sets up the *Request Logger* for Phoenix LiveDashboard, this will allow you to have the option to either pass a query parameter to stream requests logs or to enable/disable a cookie that streams requests logs from your dashboard.
* [`Plug.RequestId`](https://hexdocs.pm/plug/1.13.6/Plug.RequestId.html) - generates a unique request ID for each request.
* [`Plug.Telemetry`](https://hexdocs.pm/plug/1.13.6/Plug.Telemetry.html) - adds instrumentation points so Phoenix can log the request path, status code and request time by default.
* [`Plug.Parsers`](https://hexdocs.pm/plug/1.13.6/Plug.Parsers.html) - parses the request body when a known parser is available. By default, this plug can handle URL-encoded, multipart and JSON content (with [`Jason`](https://hexdocs.pm/jason/1.3.0/Jason.html)). The request body is left untouched if the request content-type cannot be parsed.
* [`Plug.MethodOverride`](https://hexdocs.pm/plug/1.13.6/Plug.MethodOverride.html) - converts the request method to PUT, PATCH or DELETE for POST requests with a valid `_method` parameter.
* [`Plug.Head`](https://hexdocs.pm/plug/1.13.6/Plug.Head.html) - converts HEAD requests to GET requests and strips the response body.
* [`Plug.Session`](https://hexdocs.pm/plug/1.13.6/Plug.Session.html) - a plug that sets up session management. Note that `fetch_session/2` must still be explicitly called before using the session, as this plug just sets up how the session is fetched.
In the middle of the endpoint, there is also a conditional block:
```
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :hello
end
```
This block is only executed in development. It enables:
* live reloading - if you change a CSS file, they are updated in-browser without refreshing the page;
* [code reloading](phoenix.codereloader) - so we can see changes to our application without restarting the server;
* check repo status - which makes sure our database is up to date, raising a readable and actionable error otherwise.
### Router plugs
In the router, we can declare plugs inside pipelines:
```
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {HelloWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug HelloWeb.Plugs.Locale, "en"
end
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :index
end
```
Routes are defined inside scopes and scopes may pipe through multiple pipelines. Once a route matches, Phoenix invokes all plugs defined in all pipelines associated to that route. For example, accessing "/" will pipe through the `:browser` pipeline, consequently invoking all of its plugs.
As we will see in the [routing guide](routing), the pipelines themselves are plugs. There, we will also discuss all plugs in the `:browser` pipeline.
### Controller plugs
Finally, controllers are plugs too, so we can do:
```
defmodule HelloWeb.PageController do
use HelloWeb, :controller
plug HelloWeb.Plugs.Locale, "en"
```
In particular, controller plugs provide a feature that allows us to execute plugs only within certain actions. For example, you can do:
```
defmodule HelloWeb.PageController do
use HelloWeb, :controller
plug HelloWeb.Plugs.Locale, "en" when action in [:index]
```
And the plug will only be executed for the `index` action.
Plugs as composition
---------------------
By abiding by the plug contract, we turn an application request into a series of explicit transformations. It doesn't stop there. To really see how effective Plug's design is, let's imagine a scenario where we need to check a series of conditions and then either redirect or halt if a condition fails. Without plug, we would end up with something like this:
```
defmodule HelloWeb.MessageController do
use HelloWeb, :controller
def show(conn, params) do
case Authenticator.find_user(conn) do
{:ok, user} ->
case find_message(params["id"]) do
nil ->
conn |> put_flash(:info, "That message wasn't found") |> redirect(to: "/")
message ->
if Authorizer.can_access?(user, message) do
render(conn, :show, page: message)
else
conn |> put_flash(:info, "You can't access that page") |> redirect(to: "/")
end
end
:error ->
conn |> put_flash(:info, "You must be logged in") |> redirect(to: "/")
end
end
end
```
Notice how just a few steps of authentication and authorization require complicated nesting and duplication? Let's improve this with a couple of plugs.
```
defmodule HelloWeb.MessageController do
use HelloWeb, :controller
plug :authenticate
plug :fetch_message
plug :authorize_message
def show(conn, params) do
render(conn, :show, page: conn.assigns[:message])
end
defp authenticate(conn, _) do
case Authenticator.find_user(conn) do
{:ok, user} ->
assign(conn, :user, user)
:error ->
conn |> put_flash(:info, "You must be logged in") |> redirect(to: "/") |> halt()
end
end
defp fetch_message(conn, _) do
case find_message(conn.params["id"]) do
nil ->
conn |> put_flash(:info, "That message wasn't found") |> redirect(to: "/") |> halt()
message ->
assign(conn, :message, message)
end
end
defp authorize_message(conn, _) do
if Authorizer.can_access?(conn.assigns[:user], conn.assigns[:message]) do
conn
else
conn |> put_flash(:info, "You can't access that page") |> redirect(to: "/") |> halt()
end
end
end
```
To make this all work, we converted the nested blocks of code and used `halt(conn)` whenever we reached a failure path. The `halt(conn)` functionality is essential here: it tells Plug that the next plug should not be invoked.
At the end of the day, by replacing the nested blocks of code with a flattened series of plug transformations, we are able to achieve the same functionality in a much more composable, clear, and reusable way.
To learn more about plugs, see the documentation for the [Plug project](https://hexdocs.pm/plug/1.13.6/Plug.html), which provides many built-in plugs and functionalities.
[← Previous Page Request life-cycle](request_lifecycle) [Next Page → Routing](routing)
phoenix Testing Channels Testing Channels
=================
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [Introduction to Testing guide](testing).
>
>
> **Requirement**: This guide expects that you have gone through the [Channels guide](channels).
>
>
In the Channels guide, we saw that a "Channel" is a layered system with different components. Given this, there would be cases when writing unit tests for our Channel functions may not be enough. We may want to verify that its different moving parts are working together as we expect. This integration testing would assure us that we correctly defined our channel route, the channel module, and its callbacks; and that the lower-level layers such as the PubSub and Transport are configured correctly and are working as intended.
Generating channels
--------------------
As we progress through this guide, it would help to have a concrete example we could work off of. Phoenix comes with a Mix task for generating a basic channel and tests. These generated files serve as a good reference for writing channels and their corresponding tests. Let's go ahead and generate our Channel:
```
$ mix phx.gen.channel Room
* creating lib/hello_web/channels/room_channel.ex
* creating test/hello_web/channels/room_channel_test.exs
Add the channel to your `lib/hello_web/channels/user_socket.ex` handler, for example:
channel "room:lobby", HelloWeb.RoomChannel
```
This creates a channel, its test and instructs us to add a channel route in `lib/hello_web/channels/user_socket.ex`. It is important to add the channel route or our channel won't function at all!
The ChannelCase
----------------
Open up `test/hello_web/channels/room_channel_test.exs` and you will find this:
```
defmodule HelloWeb.RoomChannelTest do
use HelloWeb.ChannelCase
```
Similar to `ConnCase` and `DataCase`, we now have a `ChannelCase`. All three of them have been generated for us when we started our Phoenix application. Let's take a look at it. Open up `test/support/channel_case.ex`:
```
defmodule HelloWeb.ChannelCase do
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
import Phoenix.ChannelTest
# The default endpoint for testing
@endpoint HelloWeb.Endpoint
end
end
setup tags do
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Demo.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
:ok
end
end
```
It is very straight-forward. It sets up a case template that imports all of [`Phoenix.ChannelTest`](phoenix.channeltest) on use. In the `setup` block, it starts the SQL Sandbox, which we discussed in the [Testing contexts guide](testing_contexts).
Subscribe and joining
----------------------
Now that we know that Phoenix provides with a custom Test Case just for channels and what it provides, we can move on to understanding the rest of `test/hello_web/channels/room_channel_test.exs`.
First off, is the setup block:
```
setup do
{:ok, _, socket} =
UserSocket
|> socket("user_id", %{some: :assign})
|> subscribe_and_join(RoomChannel, "room:lobby")
%{socket: socket}
end
```
The `setup` block sets up a [`Phoenix.Socket`](phoenix.socket) based on the `UserSocket` module, which you can find at `lib/hello_web/channels/user_socket.ex`. Then it says we want to subscribe and join the `RoomChannel`, accessible as `"room:lobby"` in the `UserSocket`. At the end of the test, we return the `%{socket: socket}` as metadata, so we can reuse it on every test.
In a nutshell, `subscribe_and_join/3` emulates the client joining a channel and subscribes the test process to the given topic. This is a necessary step since clients need to join a channel before they can send and receive events on that channel.
Testing a synchronous reply
----------------------------
The first test block in our generated channel test looks like:
```
test "ping replies with status ok", %{socket: socket} do
ref = push(socket, "ping", %{"hello" => "there"})
assert_reply ref, :ok, %{"hello" => "there"}
end
```
This tests the following code in our `MyAppWeb.RoomChannel`:
```
# Channels can be used in a request/response fashion
# by sending replies to requests from the client
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
```
As is stated in the comment above, we see that a `reply` is synchronous since it mimics the request/response pattern we are familiar with in HTTP. This synchronous reply is best used when we only want to send an event back to the client when we are done processing the message on the server. For example, when we save something to the database and then send a message to the client only once that's done.
In the `test "ping replies with status ok", %{socket: socket} do` line, we see that we have the map `%{socket: socket}`. This gives us access to the `socket` in the setup block.
We emulate the client pushing a message to the channel with `push/3`. In the line `ref = push(socket, "ping", %{"hello" => "there"})`, we push the event `"ping"` with the payload `%{"hello" => "there"}` to the channel. This triggers the `handle_in/3` callback we have for the `"ping"` event in our channel. Note that we store the `ref` since we need that on the next line for asserting the reply. With `assert_reply ref, :ok, %{"hello" => "there"}`, we assert that the server sends a synchronous reply `:ok, %{"hello" => "there"}`. This is how we check that the `handle_in/3` callback for the `"ping"` was triggered.
### Testing a Broadcast
It is common to receive messages from the client and broadcast to everyone subscribed to a current topic. This common pattern is simple to express in Phoenix and is one of the generated `handle_in/3` callbacks in our `MyAppWeb.RoomChannel`.
```
def handle_in("shout", payload, socket) do
broadcast(socket, "shout", payload)
{:noreply, socket}
end
```
Its corresponding test looks like:
```
test "shout broadcasts to room:lobby", %{socket: socket} do
push(socket, "shout", %{"hello" => "all"})
assert_broadcast "shout", %{"hello" => "all"}
end
```
We notice that we access the same `socket` that is from the setup block. How handy! We also do the same `push/3` as we did in the synchronous reply test. So we `push` the `"shout"` event with the payload `%{"hello" => "all"}`.
Since the `handle_in/3` callback for the `"shout"` event just broadcasts the same event and payload, all subscribers in the `"room:lobby"` should receive the message. To check that, we do `assert_broadcast "shout", %{"hello" => "all"}`.
**NOTE:** `assert_broadcast/3` tests that the message was broadcast in the PubSub system. For testing if a client receives a message, use `assert_push/3`.
### Testing an asynchronous push from the server
The last test in our `MyAppWeb.RoomChannelTest` verifies that broadcasts from the server are pushed to the client. Unlike the previous tests discussed, we are indirectly testing that our channel's `handle_out/3` callback is triggered. This `handle_out/3` is defined in our `MyApp.RoomChannel` as:
```
def handle_out(event, payload, socket) do
push(socket, event, payload)
{:noreply, socket}
end
```
Since the `handle_out/3` event is only triggered when we call `broadcast/3` from our channel, we will need to emulate that in our test. We do that by calling `broadcast_from` or `broadcast_from!`. Both serve the same purpose with the only difference of `broadcast_from!` raising an error when broadcast fails.
The line `broadcast_from!(socket, "broadcast", %{"some" => "data"})` will trigger our `handle_out/3` callback above which pushes the same event and payload back to the client. To test this, we do `assert_push "broadcast", %{"some" => "data"}`.
That's it. Now you are ready to develop and fully test real-time applications. To learn more about other functionality provided when testing channels, check out the documentation for [`Phoenix.ChannelTest`](phoenix.channeltest).
[← Previous Page Testing Controllers](testing_controllers) [Next Page → Introduction to Deployment](deployment)
| programming_docs |
phoenix Introduction to Testing Introduction to Testing
========================
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
Testing has become integral to the software development process, and the ability to easily write meaningful tests is an indispensable feature for any modern web framework. Phoenix takes this seriously, providing support files to make all the major components of the framework easy to test. It also generates test modules with real-world examples alongside any generated modules to help get us going.
Elixir ships with a built-in testing framework called [ExUnit](https://hexdocs.pm/ex_unit). ExUnit strives to be clear and explicit, keeping magic to a minimum. Phoenix uses ExUnit for all of its testing, and we will use it here as well.
Running tests
--------------
When Phoenix generates a web application for us, it also includes tests. To run them, simply type [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html):
```
$ mix test
....
Finished in 0.09 seconds
3 tests, 0 failures
Randomized with seed 652656
```
We already have three tests!
In fact, we already have a directory structure completely set up for testing, including a test helper and support files.
```
test
├── hello_web
│ ├── channels
│ ├── controllers
│ │ └── page_controller_test.exs
│ └── views
│ ├── error_view_test.exs
│ ├── layout_view_test.exs
│ └── page_view_test.exs
├── support
│ ├── channel_case.ex
│ ├── conn_case.ex
│ └── data_case.ex
└── test_helper.exs
```
The test cases we get for free include `test/hello_web/controllers/page_controller_test.exs`, `test/hello_web/views/error_view_test.exs`, and `test/hello_web/views/page_view_test.exs`. They are testing our controllers and views. If you haven't read the guides for controllers and views, now is a good time.
Understanding test modules
---------------------------
We are going to use the next sections to get acquainted with Phoenix testing structure. We will start with the three test files generated by Phoenix.
The first test file we'll look at is `test/hello_web/controllers/page_controller_test.exs`.
```
defmodule HelloWeb.PageControllerTest do
use HelloWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get(conn, "/")
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
```
There are a couple of interesting things happening here.
Our test files simply define modules. At the top of each module, you will find a line such as:
```
use HelloWeb.ConnCase
```
If you were to write an Elixir library, outside of Phoenix, instead of `use HelloWeb.ConnCase` you would write `use ExUnit.Case`. However, Phoenix already ships with a bunch of functionality for testing controllers and `HelloWeb.ConnCase` builds on top of [`ExUnit.Case`](https://hexdocs.pm/ex_unit/ExUnit.Case.html) to bring these functionalities in. We will explore the `HelloWeb.ConnCase` module soon.
Then we define each test using the `test/3` macro. The `test/3` macro receives three arguments: the test name, the testing context that we are pattern matching on, and the contents of the test. In this test, we access the root page of our application by a "GET" HTTP request on the path "/" with the `get/2` macro. Then we **assert** that the rendered page contains the string "Welcome to Phoenix!".
When writing tests in Elixir, we use assertions to check that something is true. In our case, `assert html_response(conn, 200) =~ "Welcome to Phoenix!"` is doing a couple things:
* It asserts that `conn` has rendered a response
* It asserts that the response has the 200 status code (which means OK in HTTP parlance)
* It asserts that the type of the response is HTML
* It asserts that the result of `html_response(conn, 200)`, which is an HTML response, has the string "Welcome to Phoenix!" in it
However, from where does the `conn` we use on `get` and `html_response` come from? To answer this question, let's take a look at `HelloWeb.ConnCase`.
The ConnCase
-------------
If you open up `test/support/conn_case.ex`, you will find this (with comments removed):
```
defmodule HelloWeb.ConnCase do
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
alias HelloWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint HelloWeb.Endpoint
end
end
setup tags do
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Demo.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
%{conn: Phoenix.ConnTest.build_conn()}
end
end
```
There is a lot to unpack here.
The second line says this is a case template. This is a ExUnit feature that allows developers to replace the built-in `use ExUnit.Case` by their own case. This line is pretty much what allows us to write `use HelloWeb.ConnCase` at the top of our controller tests.
Now that we have made this module a case template, we can define callbacks that are invoked on certain occasions. The `using` callback defines code to be injected on every module that calls `use HelloWeb.ConnCase`. In this case, we import [`Plug.Conn`](../plug/plug.conn), so all of the connection helpers available in controllers are also available in tests, and then imports [`Phoenix.ConnTest`](phoenix.conntest). You can consult these modules to learn all functionality available.
Then it aliases the module with all path helpers, so we can easily generate URLs in our tests. Finally, it sets the `@endpoint` module attribute with the name of our endpoint.
Then our case template defines a `setup` block. The `setup` block will be called before test. Most of the setup block is on setting up the SQL Sandbox, which we will talk about it later. In the last line of the `setup` block, we will find this:
```
%{conn: Phoenix.ConnTest.build_conn()}
```
The last line of `setup` can return test metadata that will be available in each test. The metadata we are passing forward here is a newly built [`Plug.Conn`](https://hexdocs.pm/plug/1.13.6/Plug.Conn.html). In our test, we extract the connection out of this metadata at the very beginning of our test:
```
test "GET /", %{conn: conn} do
```
And that's where the connection comes from! At first, the testing structure does come with a bit of indirection, but this indirection pays off as our test suite grows, since it allows us to cut down the amount of boilerplate.
View tests
-----------
The other test files in our application are responsible for testing our views.
The error view test case, `test/hello_web/views/error_view_test.exs`, illustrates a few interesting things of its own.
```
defmodule HelloWeb.ErrorViewTest do
use HelloWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(HelloWeb.ErrorView, "404.html", []) ==
"Not Found"
end
test "renders 500.html" do
assert render_to_string(HelloWeb.ErrorView, "500.html", []) ==
"Internal Server Error"
end
end
```
`HelloWeb.ErrorViewTest` sets `async: true` which means that this test case will be run in parallel with other test cases. While individual tests within the case still run serially, this can greatly increase overall test speeds.
It also imports [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) in order to use the `render_to_string/3` function. With that, all the assertions can be simple string equality tests.
The page view case, `test/hello_web/views/page_view_test.exs`, does not contain any tests by default, but it is here for us when we need to add functions to our `HelloWeb.PageView` module.
```
defmodule HelloWeb.PageViewTest do
use HelloWeb.ConnCase, async: true
end
```
Running tests per directory/file
---------------------------------
Now that we have an idea what our tests are doing, let's look at different ways to run them.
As we saw near the beginning of this guide, we can run our entire suite of tests with [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html).
```
$ mix test
....
Finished in 0.2 seconds
3 tests, 0 failures
Randomized with seed 540755
```
If we would like to run all the tests in a given directory, `test/hello_web/controllers` for instance, we can pass the path to that directory to [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html).
```
$ mix test test/hello_web/controllers/
.
Finished in 0.2 seconds
1 tests, 0 failures
Randomized with seed 652376
```
In order to run all the tests in a specific file, we can pass the path to that file into [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html).
```
$ mix test test/hello_web/views/error_view_test.exs
...
Finished in 0.2 seconds
2 tests, 0 failures
Randomized with seed 220535
```
And we can run a single test in a file by appending a colon and a line number to the filename.
Let's say we only wanted to run the test for the way `HelloWeb.ErrorView` renders `500.html`. The test begins on line 11 of the file, so this is how we would do it.
```
$ mix test test/hello_web/views/error_view_test.exs:11
Including tags: [line: "11"]
Excluding tags: [:test]
.
Finished in 0.1 seconds
2 tests, 0 failures, 1 excluded
Randomized with seed 288117
```
We chose to run this specifying the first line of the test, but actually, any line of that test will do. These line numbers would all work - `:11`, `:12`, or `:13`.
Running tests using tags
-------------------------
ExUnit allows us to tag our tests individually or for the whole module. We can then choose to run only the tests with a specific tag, or we can exclude tests with that tag and run everything else.
Let's experiment with how this works.
First, we'll add a `@moduletag` to `test/hello_web/views/error_view_test.exs`.
```
defmodule HelloWeb.ErrorViewTest do
use HelloWeb.ConnCase, async: true
@moduletag :error_view_case
...
end
```
If we use only an atom for our module tag, ExUnit assumes that it has a value of `true`. We could also specify a different value if we wanted.
```
defmodule HelloWeb.ErrorViewTest do
use HelloWeb.ConnCase, async: true
@moduletag error_view_case: "some_interesting_value"
...
end
```
For now, let's leave it as a simple atom `@moduletag :error_view_case`.
We can run only the tests from the error view case by passing `--only error_view_case` into [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html).
```
$ mix test --only error_view_case
Including tags: [:error_view_case]
Excluding tags: [:test]
...
Finished in 0.1 seconds
3 tests, 0 failures, 1 excluded
Randomized with seed 125659
```
> Note: ExUnit tells us exactly which tags it is including and excluding for each test run. If we look back to the previous section on running tests, we'll see that line numbers specified for individual tests are actually treated as tags.
>
>
```
$ mix test test/hello_web/views/error_view_test.exs:11
Including tags: [line: "11"]
Excluding tags: [:test]
.
Finished in 0.2 seconds
2 tests, 0 failures, 1 excluded
Randomized with seed 364723
```
Specifying a value of `true` for `error_view_case` yields the same results.
```
$ mix test --only error_view_case:true
Including tags: [error_view_case: "true"]
Excluding tags: [:test]
...
Finished in 0.1 seconds
3 tests, 0 failures, 1 excluded
Randomized with seed 833356
```
Specifying `false` as the value for `error_view_case`, however, will not run any tests because no tags in our system match `error_view_case: false`.
```
$ mix test --only error_view_case:false
Including tags: [error_view_case: "false"]
Excluding tags: [:test]
Finished in 0.1 seconds
3 tests, 0 failures, 3 excluded
Randomized with seed 622422
The --only option was given to "mix test" but no test executed
```
We can use the `--exclude` flag in a similar way. This will run all of the tests except those in the error view case.
```
$ mix test --exclude error_view_case
Excluding tags: [:error_view_case]
.
Finished in 0.2 seconds
3 tests, 0 failures, 2 excluded
Randomized with seed 682868
```
Specifying values for a tag works the same way for `--exclude` as it does for `--only`.
We can tag individual tests as well as full test cases. Let's tag a few tests in the error view case to see how this works.
```
defmodule HelloWeb.ErrorViewTest do
use HelloWeb.ConnCase, async: true
@moduletag :error_view_case
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
@tag individual_test: "yup"
test "renders 404.html" do
assert render_to_string(HelloWeb.ErrorView, "404.html", []) ==
"Not Found"
end
@tag individual_test: "nope"
test "renders 500.html" do
assert render_to_string(HelloWeb.ErrorView, "500.html", []) ==
"Internal Server Error"
end
end
```
If we would like to run only tests tagged as `individual_test`, regardless of their value, this will work.
```
$ mix test --only individual_test
Including tags: [:individual_test]
Excluding tags: [:test]
..
Finished in 0.1 seconds
3 tests, 0 failures, 1 excluded
Randomized with seed 813729
```
We can also specify a value and run only tests with that.
```
$ mix test --only individual_test:yup
Including tags: [individual_test: "yup"]
Excluding tags: [:test]
.
Finished in 0.1 seconds
3 tests, 0 failures, 2 excluded
Randomized with seed 770938
```
Similarly, we can run all tests except for those tagged with a given value.
```
$ mix test --exclude individual_test:nope
Excluding tags: [individual_test: "nope"]
...
Finished in 0.2 seconds
3 tests, 0 failures, 1 excluded
Randomized with seed 539324
```
We can be more specific and exclude all the tests from the error view case except the one tagged with `individual_test` that has the value "yup".
```
$ mix test --exclude error_view_case --include individual_test:yup
Including tags: [individual_test: "yup"]
Excluding tags: [:error_view_case]
..
Finished in 0.2 seconds
3 tests, 0 failures, 1 excluded
Randomized with seed 61472
```
Finally, we can configure ExUnit to exclude tags by default. The default ExUnit configuration is done in the `test/test_helper.exs` file:
```
ExUnit.start(exclude: [error_view_case: true])
Ecto.Adapters.SQL.Sandbox.mode(Hello.Repo, :manual)
```
Now when we run [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html), it only runs one spec from our `page_controller_test.exs`.
```
$ mix test
Excluding tags: [error_view_case: true]
.
Finished in 0.2 seconds
3 tests, 0 failures, 2 excluded
Randomized with seed 186055
```
We can override this behavior with the `--include` flag, telling [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html) to include tests tagged with `error_view_case`.
```
$ mix test --include error_view_case
Including tags: [:error_view_case]
Excluding tags: [error_view_case: true]
....
Finished in 0.2 seconds
3 tests, 0 failures
Randomized with seed 748424
```
This technique can be very useful to control very long running tests, which you may only want to run in CI or in specific scenarios.
Randomization
--------------
Running tests in random order is a good way to ensure that our tests are truly isolated. If we notice that we get sporadic failures for a given test, it may be because a previous test changes the state of the system in ways that aren't cleaned up afterward, thereby affecting the tests which follow. Those failures might only present themselves if the tests are run in a specific order.
ExUnit will randomize the order tests run in by default, using an integer to seed the randomization. If we notice that a specific random seed triggers our intermittent failure, we can re-run the tests with that same seed to reliably recreate that test sequence in order to help us figure out what the problem is.
```
$ mix test --seed 401472
....
Finished in 0.2 seconds
3 tests, 0 failures
Randomized with seed 401472
```
Concurrency and partitioning
-----------------------------
As we have seen, ExUnit allows developers to run tests concurrently. This allows developers to use all of the power in their machine to run their test suites as fast as possible. Couple this with Phoenix performance, most test suites compile and run in a fraction of the time compared to other frameworks.
While developers usually have powerful machines available to them during development, this may not always be the case in your Continuous Integration servers. For this reason, ExUnit also supports out of the box test partitioning in test environments. If you open up your `config/test.exs`, you will find the database name set to:
```
database: "hello_test#{System.get_env("MIX_TEST_PARTITION")}",
```
By default, the `MIX_TEST_PARTITION` environment variable has no value, and therefore it has no effect. But in your CI server, you can, for example, split your test suite across machines by using four distinct commands:
```
$ MIX_TEST_PARTITION=1 mix test --partitions 4
$ MIX_TEST_PARTITION=2 mix test --partitions 4
$ MIX_TEST_PARTITION=3 mix test --partitions 4
$ MIX_TEST_PARTITION=4 mix test --partitions 4
```
That's all you need to do and ExUnit and Phoenix will take care of all rest, including setting up the database for each distinct partition with a distinct name.
Going further
--------------
While ExUnit is a simple test framework, it provides a really flexible and robust test runner through the [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html) command. We recommend you to run [`mix help test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html) or [read the docs online](https://hexdocs.pm/mix/Mix.Tasks.Test.html)
We've seen what Phoenix gives us with a newly generated app. Furthermore, whenever you generate a new resource, Phoenix will generate all appropriate tests for that resource too. For example, you can create a complete scaffold with schema, context, controllers, and views by running the following command at the root of your application:
```
$ mix phx.gen.html Blog Post posts title body:text
* creating lib/demo_web/controllers/post_controller.ex
* creating lib/demo_web/templates/post/edit.html.heex
* creating lib/demo_web/templates/post/form.html.heex
* creating lib/demo_web/templates/post/index.html.heex
* creating lib/demo_web/templates/post/new.html.heex
* creating lib/demo_web/templates/post/show.html.heex
* creating lib/demo_web/views/post_view.ex
* creating test/demo_web/controllers/post_controller_test.exs
* creating lib/demo/blog/post.ex
* creating priv/repo/migrations/20200215122336_create_posts.exs
* creating lib/demo/blog.ex
* injecting lib/demo/blog.ex
* creating test/demo/blog_test.exs
* injecting test/demo/blog_test.exs
Add the resource to your browser scope in lib/demo_web/router.ex:
resources "/posts", PostController
Remember to update your repository by running migrations:
$ mix ecto.migrate
```
Now let's follow the directions and add the new resources route to our `lib/hello_web/router.ex` file and run the migrations.
When we run [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html) again, we see that we now have nineteen tests!
```
$ mix test
................
Finished in 0.1 seconds
19 tests, 0 failures
Randomized with seed 537537
```
At this point, we are at a great place to transition to the rest of the testing guides, in which we'll examine these tests in much more detail, and add some of our own.
[← Previous Page Presence](presence) [Next Page → Testing Contexts](testing_contexts)
phoenix Installation Installation
=============
In order to build a Phoenix application, we will need a few dependencies installed in our Operating System:
* the Erlang VM and the Elixir programming language
* a database - Phoenix recommends PostgreSQL, but you can pick others or not use a database at all
* and other optional packages.
Please take a look at this list and make sure to install anything necessary for your system. Having dependencies installed in advance can prevent frustrating problems later on.
Elixir 1.12 or later
---------------------
Phoenix is written in Elixir, and our application code will also be written in Elixir. We won't get far in a Phoenix app without it! The Elixir site maintains a great [Installation Page](https://elixir-lang.org/install.html) to help.
If we have just installed Elixir for the first time, we will need to install the Hex package manager as well. Hex is necessary to get a Phoenix app running (by installing dependencies) and to install any extra dependencies we might need along the way.
Here's the command to install Hex (If you have Hex already installed, it will upgrade Hex to the latest version):
```
$ mix local.hex
```
Erlang 22 or later
-------------------
Elixir code compiles to Erlang byte code to run on the Erlang virtual machine. Without Erlang, Elixir code has no virtual machine to run on, so we need to install Erlang as well.
When we install Elixir using instructions from the Elixir [Installation Page](https://elixir-lang.org/install.html), we will usually get Erlang too. If Erlang was not installed along with Elixir, please see the [Erlang Instructions](https://elixir-lang.org/install.html#installing-erlang) section of the Elixir Installation Page for instructions.
Phoenix
--------
To check that we are on Elixir 1.12 and Erlang 22 or later, run:
```
elixir -v
Erlang/OTP 22 [erts-10.7] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Elixir 1.12.1
```
Once we have Elixir and Erlang, we are ready to install the Phoenix application generator:
```
$ mix archive.install hex phx_new
```
The `phx.new` generator is now available to generate new applications in the next guide, called [Up and Running](up_and_running). The flags mentioned below are command line options to the generator; see all available options by calling [`mix help phx.new`](mix.tasks.phx.new).
PostgreSQL
-----------
PostgreSQL is a relational database server. Phoenix configures applications to use it by default, but we can switch to MySQL, MSSQL, or SQLite3 by passing the `--database` flag when creating a new application.
In order to talk to databases, Phoenix applications use another Elixir package, called [Ecto](https://github.com/elixir-ecto/ecto). If you don't plan to use databases in your application, you can pass the `--no-ecto` flag.
However, if you are just getting started with Phoenix, we recommend you to install PostgreSQL and make sure it is running. The PostgreSQL wiki has [installation guides](https://wiki.postgresql.org/wiki/Detailed_installation_guides) for a number of different systems.
inotify-tools (for Linux users)
--------------------------------
Phoenix provides a very handy feature called Live Reloading. As you change your views or your assets, it automatically reloads the page in the browser. In order for this functionality to work, you need a filesystem watcher.
macOS and Windows users already have a filesystem watcher, but Linux users must install inotify-tools. Please consult the [inotify-tools wiki](https://github.com/rvoicilas/inotify-tools/wiki) for distribution-specific installation instructions.
Summary
--------
At the end of this section, you must have installed Elixir, Hex, Phoenix, and PostgreSQL. Now that we have everything installed, let's create our first Phoenix application and get [up and running](up_and_running).
[← Previous Page Overview](overview) [Next Page → Up and Running](up_and_running)
| programming_docs |
phoenix Phoenix.Socket.Broadcast Phoenix.Socket.Broadcast
=========================
Defines a message sent from pubsub to channels and vice-versa.
The message format requires the following keys:
* `:topic` - The string topic or topic:subtopic pair namespace, for example "messages", "messages:123"
* `:event`- The string event name, for example "phx\_join"
* `:payload` - The message payload
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix/blob/v1.6.11/lib/phoenix/socket/message.ex#L70)
```
@type t() :: %Phoenix.Socket.Broadcast{event: term(), payload: term(), topic: term()}
```
phoenix mix phx.gen.json mix phx.gen.json
=================
Generates controller, views, and context for a JSON resource.
```
mix phx.gen.json Accounts User users name:string age:integer
```
The first argument is the context module followed by the schema module and its plural name (used as the schema table name).
The context is an Elixir module that serves as an API boundary for the given resource. A context often holds many related resources. Therefore, if the context already exists, it will be augmented with functions for the given resource.
> Note: A resource may also be split over distinct contexts (such as `Accounts.User` and `Payments.User`).
>
>
The schema is responsible for mapping the database fields into an Elixir struct. It is followed by an optional list of attributes, with their respective names and types. See [`mix phx.gen.schema`](mix.tasks.phx.gen.schema) for more information on attributes.
Overall, this generator will add the following files to `lib/`:
* a context module in `lib/app/accounts.ex` for the accounts API
* a schema in `lib/app/accounts/user.ex`, with an `users` table
* a view in `lib/app_web/views/user_view.ex`
* a controller in `lib/app_web/controllers/user_controller.ex`
A migration file for the repository and test files for the context and controller features will also be generated.
The context app
----------------
The location of the web files (controllers, views, templates, etc) in an umbrella application will vary based on the `:context_app` config located in your applications `:generators` configuration. When set, the Phoenix generators will generate web files directly in your lib and test folders since the application is assumed to be isolated to web specific functionality. If `:context_app` is not set, the generators will place web related lib and test files in a `web/` directory since the application is assumed to be handling both web and domain specific functionality. Example configuration:
```
config :my_app_web, :generators, context_app: :my_app
```
Alternatively, the `--context-app` option may be supplied to the generator:
```
mix phx.gen.json Sales User users --context-app warehouse
```
Web namespace
--------------
By default, the controller and view will be namespaced by the schema name. You can customize the web module namespace by passing the `--web` flag with a module name, for example:
```
mix phx.gen.json Sales User users --web Sales
```
Which would generate a `lib/app_web/controllers/sales/user_controller.ex` and `lib/app_web/views/sales/user_view.ex`.
Customizing the context, schema, tables and migrations
-------------------------------------------------------
In some cases, you may wish to bootstrap JSON views, controllers, and controller tests, but leave internal implementation of the context or schema to yourself. You can use the `--no-context` and `--no-schema` flags for file generation control.
You can also change the table name or configure the migrations to use binary ids for primary keys, see [`mix phx.gen.schema`](mix.tasks.phx.gen.schema) for more information.
phoenix mix phx.gen.context mix phx.gen.context
====================
Generates a context with functions around an Ecto schema.
```
$ mix phx.gen.context Accounts User users name:string age:integer
```
The first argument is the context module followed by the schema module and its plural name (used as the schema table name).
The context is an Elixir module that serves as an API boundary for the given resource. A context often holds many related resources. Therefore, if the context already exists, it will be augmented with functions for the given resource.
> Note: A resource may also be split over distinct contexts (such as Accounts.User and Payments.User).
>
>
The schema is responsible for mapping the database fields into an Elixir struct.
Overall, this generator will add the following files to `lib/your_app`:
* a context module in `accounts.ex`, serving as the API boundary
* a schema in `accounts/user.ex`, with a `users` table
A migration file for the repository and test files for the context will also be generated.
Generating without a schema
----------------------------
In some cases, you may wish to bootstrap the context module and tests, but leave internal implementation of the context and schema to yourself. Use the `--no-schema` flags to accomplish this.
table
------
By default, the table name for the migration and schema will be the plural name provided for the resource. To customize this value, a `--table` option may be provided. For example:
```
$ mix phx.gen.context Accounts User users --table cms_users
```
binary\_id
-----------
Generated migration can use `binary_id` for schema's primary key and its references with option `--binary-id`.
Default options
----------------
This generator uses default options provided in the `:generators` configuration of your application. These are the defaults:
```
config :your_app, :generators,
migration: true,
binary_id: false,
sample_binary_id: "11111111-1111-1111-1111-111111111111"
```
You can override those options per invocation by providing corresponding switches, e.g. `--no-binary-id` to use normal ids despite the default configuration or `--migration` to force generation of the migration.
Read the documentation for `phx.gen.schema` for more information on attributes.
Skipping prompts
-----------------
This generator will prompt you if there is an existing context with the same name, in order to provide more instructions on how to correctly use phoenix contexts. You can skip this prompt and automatically merge the new schema access functions and tests into the existing context using `--merge-with-existing-context`. To prevent changes to the existing context and exit the generator, use `--no-merge-with-existing-context`.
phoenix mix phx.gen.secret mix phx.gen.secret
===================
Generates a secret and prints it to the terminal.
```
$ mix phx.gen.secret [length]
```
By default, mix phx.gen.secret generates a key 64 characters long.
The minimum value for `length` is 32.
phoenix Phoenix.Router.MalformedURIError exception Phoenix.Router.MalformedURIError exception
===========================================
Exception raised when the URI is malformed on matching.
phoenix mix phx.new mix phx.new
============
Creates a new Phoenix project.
It expects the path of the project as an argument.
```
$ mix phx.new PATH [--module MODULE] [--app APP]
```
A project at the given PATH will be created. The application name and module name will be retrieved from the path, unless `--module` or `--app` is given.
Options
--------
* `--umbrella` - generate an umbrella project, with one application for your domain, and a second application for the web interface.
* `--app` - the name of the OTP application
* `--module` - the name of the base module in the generated skeleton
* `--database` - specify the database adapter for Ecto. One of:
+ `postgres` - via <https://github.com/elixir-ecto/postgrex>
+ `mysql` - via <https://github.com/elixir-ecto/myxql>
+ `mssql` - via <https://github.com/livehelpnow/tds>
+ `sqlite3` - via <https://github.com/elixir-sqlite/ecto_sqlite3>Please check the driver docs for more information and requirements. Defaults to "postgres".
* `--no-assets` - do not generate the assets folder. When choosing this option, you will need to manually handle JavaScript/CSS if building HTML apps
* `--no-ecto` - do not generate Ecto files
* `--no-html` - do not generate HTML views
* `--no-gettext` - do not generate gettext files
* `--no-dashboard` - do not include Phoenix.LiveDashboard
* `--no-live` - comment out LiveView socket setup in assets/js/app.js and also on the endpoint (the latter also requires `--no-dashboard`)
* `--no-mailer` - do not generate Swoosh mailer files
* `--binary-id` - use `binary_id` as primary key type in Ecto schemas
* `--verbose` - use verbose output
* `-v`, `--version` - prints the Phoenix installer version
When passing the `--no-ecto` flag, Phoenix generators such as `phx.gen.html`, `phx.gen.json`, `phx.gen.live`, and `phx.gen.context` may no longer work as expected as they generate context files that rely on Ecto for the database access. In those cases, you can pass the `--no-context` flag to generate most of the HTML and JSON files but skip the context, allowing you to fill in the blanks as desired.
Similarly, if `--no-html` is given, the files generated by `phx.gen.html` will no longer work, as important HTML components will be missing.
Installation
-------------
[`mix phx.new`](mix.tasks.phx.new#content) by default prompts you to fetch and install your dependencies. You can enable this behaviour by passing the `--install` flag or disable it with the `--no-install` flag.
Examples
---------
```
$ mix phx.new hello_world
```
Is equivalent to:
```
$ mix phx.new hello_world --module HelloWorld
```
Or without the HTML and JS bits (useful for APIs):
```
$ mix phx.new ~/Workspace/hello_world --no-html --no-assets
```
As an umbrella:
```
$ mix phx.new hello --umbrella
```
Would generate the following directory structure and modules:
```
hello_umbrella/ Hello.Umbrella
apps/
hello/ Hello
hello_web/ HelloWeb
```
You can read more about umbrella projects using the official [Elixir guide](https://elixir-lang.org/getting-started/mix-otp/dependencies-and-umbrella-apps.html#umbrella-projects)
phoenix mix phx.server mix phx.server
===============
Starts the application by configuring all endpoints servers to run.
Note: to start the endpoint without using this mix task you must set `server: true` in your [`Phoenix.Endpoint`](phoenix.endpoint) configuration.
Command line options
---------------------
* `--open` - open browser window for each started endpoint
Furthermore, this task accepts the same command-line options as [`mix run`](https://hexdocs.pm/mix/Mix.Tasks.Run.html).
For example, to run `phx.server` without recompiling:
```
$ mix phx.server --no-compile
```
The `--no-halt` flag is automatically added.
Note that the `--no-deps-check` flag cannot be used this way, because Mix needs to check dependencies to find `phx.server`.
To run `phx.server` without checking dependencies, you can run:
```
$ mix do deps.loadpaths --no-deps-check, phx.server
```
phoenix Views and templates Views and templates
====================
> **Requirement**: This guide expects that you have gone through the [introductory guides](installation) and got a Phoenix application [up and running](up_and_running).
>
>
> **Requirement**: This guide expects that you have gone through the [request life-cycle guide](request_lifecycle).
>
>
The main job of a Phoenix view is to render the body of the response which gets sent back to browsers and to API clients. Most of the time, we use templates to build these responses, but we can also craft them by hand. We will learn how.
Rendering templates
--------------------
Phoenix assumes a strong naming convention from controllers to views to the templates they render. `PageController` requires a `PageView` to render templates in the `lib/hello_web/templates/page/` directory. While all of these can be customizable (see [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) and [`Phoenix.Template`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.Template.html) for more information), we recommend users stick with Phoenix' convention.
A newly generated Phoenix application has three view modules - `ErrorView`, `LayoutView`, and `PageView` - which are all in the `lib/hello_web/views/` directory.
Let's take a quick look at `LayoutView`.
```
defmodule HelloWeb.LayoutView do
use HelloWeb, :view
end
```
That's simple enough. There's only one line, `use HelloWeb, :view`. This line calls the `view/0` function defined in `HelloWeb` which sets up the basic imports and configuration for our views and templates.
All of the imports and aliases we make in our view will also be available in our templates. That's because templates are effectively compiled into functions inside their respective views. For example, if you define a function in your view, you will be able to invoke it directly from the template. Let's see this in practice.
Open up our application layout template, `lib/hello_web/templates/layout/root.html.heex`, and change this line,
```
<%= live_title_tag assigns[:page_title] || "Hello", suffix: " · Phoenix Framework" %>
```
to call a `title/0` function, like this.
```
<title><%= title() %></title>
```
Now let's add a `title/0` function to our `LayoutView`.
```
defmodule HelloWeb.LayoutView do
use HelloWeb, :view
def title() do
"Awesome New Title!"
end
end
```
When we reload our home page, we should see our new title. Since templates are compiled inside the view, we could invoke the view function simply as `title()`, otherwise we would have to type `HelloWeb.LayoutView.title()`.
As you may recall, Elixir templates use `.heex`, which stands for "HTML+EEx". EEx is an Elixir library that uses `<%= expression %>` to execute Elixir expressions and interpolate their results into the template. This is frequently used to display assigns we have set by way of the `@` shortcut. In your controller, if you invoke:
```
render(conn, "show.html", username: "joe")
```
Then you can access said username in the templates as `<%= @username %>`. In addition to displaying assigns and functions, we can use pretty much any Elixir expression. For example, in order to have conditionals:
```
<%= if some_condition? do %>
<p>Some condition is true for user: <%= @username %></p>
<% else %>
<p>Some condition is false for user: <%= @username %></p>
<% end %>
```
or even loops:
```
<table>
<tr>
<th>Number</th>
<th>Power</th>
</tr>
<%= for number <- 1..10 do %>
<tr>
<td><%= number %></td>
<td><%= number * number %></td>
</tr>
<% end %>
</table>
```
Did you notice the use of `<%= %>` versus `<% %>` above? All expressions that output something to the template **must** use the equals sign (`=`). If this is not included the code will still be executed but nothing will be inserted into the template.
### HTML extensions
Besides allowing interpolation of Elixir expressions via `<%= %>`, `.heex` templates come with HTML-aware extensions. For example, let's see what happens if you try to interpolate a value with "<" or ">" in it, which would lead to HTML injection:
```
<%= "<b>Bold?</b>" %>
```
Once you render the template, you will see the literal `<b>` on the page. This means users cannot inject HTML content on the page. If you want to allow them to do so, you can call `raw`, but do so with extreme care:
```
<%= raw "<b>Bold?</b>" %>
```
Another super power of HEEx templates is validation of HTML and lean interpolation syntax of attributes. You can write:
```
<div title="My div" class={@class}>
<p>Hello <%= @username %></p>
</div>
```
Notice how you could simply use `key={value}`. HEEx will automatically handle special values such as `false` to remove the attribute or a list of classes.
To interpolate a dynamic number of attributes in a keyword list or map, do:
```
<div title="My div" {@many_attributes}>
<p>Hello <%= @username %></p>
</div>
```
Also, try removing the closing `</div>` or renaming it to `</div-typo>`. HEEx templates will let you know about your error.
### HTML components
The last feature provided by HEEx is the idea of components. Components are pure functions that can be either local (same module) or remote (external module).
HEEx allows invoking those function components directly in the template using an HTML-like notation. For example, a remote function:
```
<MyApp.Weather.city name="Kraków"/>
```
A local function can be invoked with a leading dot:
```
<.city name="Kraków"/>
```
where the component could be defined as follows:
```
defmodule MyApp.Weather do
use Phoenix.Component
def city(assigns) do
~H"""
The chosen city is: <%= @name %>.
"""
end
def country(assigns) do
~H"""
The chosen country is: <%= @name %>.
"""
end
end
```
In the example above, we used the `~H` sigil syntax to embed HEEx templates directly into our modules. We have already invoked the `city` component and calling the `country` component wouldn't be different:
```
<div title="My div" {@many_attributes}>
<p>Hello <%= @username %></p>
<MyApp.Weather.country name="Brazil" />
</div>
```
You can learn more about components in [Phoenix.Component](../phoenix_live_view/phoenix.component).
### Understanding template compilation
Phoenix templates are compiled into Elixir code, which make them extremely performant. Let's learn more about this.
When a template is compiled into a view, it is simply compiled as a `render/2` function that expects two arguments: the template name and the assigns.
You can prove this by temporarily adding this function clause to your `PageView` module in `lib/hello_web/views/page_view.ex`.
```
defmodule HelloWeb.PageView do
use HelloWeb, :view
def render("index.html", assigns) do
"rendering with assigns #{inspect Map.keys(assigns)}"
end
end
```
Now if you fire up the server with [`mix phx.server`](mix.tasks.phx.server) and visit [`http://localhost:4000`](http://localhost:4000), you should see the following text below your layout header instead of the main template page:
```
rendering with assigns [:conn]
```
By defining our own clause in `render/2`, it takes higher priority than the template, but the template is still there, which you can verify by simply removing the newly added clause.
Pretty neat, right? At compile-time, Phoenix precompiles all `*.html.heex` templates and turns them into `render/2` function clauses on their respective view modules. At runtime, all templates are already loaded in memory. There's no disk reads, complex file caching, or template engine computation involved.
### Manually rendering templates
So far, Phoenix has taken care of putting everything in place and rendering views for us. However, we can also render views directly.
Let's create a new template to play around with, `lib/hello_web/templates/page/test.html.heex`:
```
This is the message: <%= @message %>
```
This doesn't correspond to any action in our controller, which is fine. We'll exercise it in an [`IEx`](https://hexdocs.pm/iex/IEx.html) session. At the root of our project, we can run `iex -S mix`, and then explicitly render our template. Let's give it a try by calling [`Phoenix.View.render/3`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html#render/3) with the view name, the template name, and a set of assigns we might have wanted to pass and we got the rendered template as a string:
```
iex(1)> Phoenix.View.render(HelloWeb.PageView, "test.html", message: "Hello from IEx!")
%Phoenix.LiveView.Rendered{
dynamic: #Function<1.71437968/1 in Hello16Web.PageView."test.html"/1>,
fingerprint: 142353463236917710626026938006893093300,
root: false,
static: ["This is the message: ", ""]
}
```
The output we got above is not very helpful. That's the internal representation of how Phoenix keeps our rendered templates. Luckily, we can convert them into strings with `render_to_string/3`:
```
iex(2)> Phoenix.View.render_to_string(HelloWeb.PageView, "test.html", message: "Hello from IEx!")
"This is the message: Hello from IEx!"
```
That's much better! Let's test out the HTML escaping, just for fun:
```
iex(3)> Phoenix.View.render_to_string(HelloWeb.PageView, "test.html", message: "<script>badThings();</script>")
"This is the message: <script>badThings();</script>"
```
Sharing views and templates
----------------------------
Now that we have acquainted ourselves with [`Phoenix.View.render/3`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html#render/3), we are ready to share views and templates from inside other views and templates. We use `render/3` to compose our templates and at the end Phoenix will convert them all into the proper representation to send to the browser.
For example, if you want to render the `test.html` template from inside our layout, you can invoke [`render/3`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html#render/3) directly from the layout `lib/hello_web/templates/layout/root.html.heex`:
```
<%= Phoenix.View.render(HelloWeb.PageView, "test.html", message: "Hello from layout!") %>
```
If you visit the [welcome page](http://localhost:4000), you should see the message from the layout.
Since [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) is automatically imported into our templates, we could even skip the [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) module name and simply invoke `render(...)` directly:
```
<%= render(HelloWeb.PageView, "test.html", message: "Hello from layout!") %>
```
If you want to render a template within the same view, you can skip the view name, and simply call `render("test.html", message: "Hello from sibling template!")` instead. For example, open up `lib/hello_web/templates/page/index.html.heex` and add this at the top:
```
<%= render("test.html", message: "Hello from sibling template!") %>
```
Now if you visit the Welcome page, you see the template results also shown.
Layouts
--------
Layouts are just templates. They have a view, just like other templates. In a newly generated app, this is `lib/hello_web/views/layout_view.ex`. You may be wondering how the string resulting from a rendered view ends up inside a layout. That's a great question! If we look at `lib/hello_web/templates/layout/root.html.heex`, just about at the end of the `<body>`, we will see this.
```
<%= @inner_content %>
```
In other words, the inner template is placed in the `@inner_content` assign.
Rendering JSON
---------------
The view's job is not only to render HTML templates. Views are about data presentation. Given a bag of data, the view's purpose is to present that in a meaningful way given some format, be it HTML, JSON, CSV, or others. Many web apps today return JSON to remote clients, and Phoenix views are *great* for JSON rendering.
Phoenix uses the [`Jason`](https://hexdocs.pm/jason/1.3.0/Jason.html) library to encode JSON, so all we need to do in our views is to format the data we would like to respond with as a list or a map, and Phoenix will do the rest.
While it is possible to respond with JSON back directly from the controller and skip the view, Phoenix views provide a much more structured approach for doing so. Let's take our `PageController`, and see what it may look like when we respond with some static page maps as JSON, instead of HTML.
```
defmodule HelloWeb.PageController do
use HelloWeb, :controller
def show(conn, _params) do
page = %{title: "foo"}
render(conn, "show.json", page: page)
end
def index(conn, _params) do
pages = [%{title: "foo"}, %{title: "bar"}]
render(conn, "index.json", pages: pages)
end
end
```
Here, we have our `show/2` and `index/2` actions returning static page data. Instead of passing in `"show.html"` to [`render/3`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html#render/3) as the template name, we pass `"show.json"`. This way, we can have views that are responsible for rendering HTML as well as JSON by pattern matching on different file types.
```
defmodule HelloWeb.PageView do
use HelloWeb, :view
def render("index.json", %{pages: pages}) do
%{data: Enum.map(pages, fn page -> %{title: page.title} end)}
end
def render("show.json", %{page: page}) do
%{data: %{title: page.title}}
end
end
```
In the view we see our `render/2` function pattern matching on `"index.json"`, `"show.json"`, and `"page.json"`. The `"index.json"` and `"show.json"` are the ones requested directly from the controller. They also match on the assigns sent by the controller. Phoenix understands the `.json` extension and will take care of converting the data-structures we return into JSON. `"index.json"` will respond like this:
```
{
"data": [
{
"title": "foo"
},
{
"title": "bar"
},
]
}
```
And `"show.json"` like this:
```
{
"data": {
"title": "foo"
}
}
```
However, there is some duplication between `index.json` and `show.json`, as both encode the same logic on how to render pages. We can address this by moving the page rendering to a separate function clause and using `render_many/3` and `render_one/3` to reuse it:
```
defmodule HelloWeb.PageView do
use HelloWeb, :view
def render("index.json", %{pages: pages}) do
%{data: render_many(pages, HelloWeb.PageView, "page.json")}
end
def render("show.json", %{page: page}) do
%{data: render_one(page, HelloWeb.PageView, "page.json")}
end
def render("page.json", %{page: page}) do
%{title: page.title}
end
end
```
The [`render_many/3`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html#render_many/3) function takes the data we want to respond with (`pages`), a view, and a string to pattern match on the `render/2` function defined on view. It will map over each item in `pages` and call `PageView.render("page.json", %{page: page})`. [`render_one/3`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html#render_one/3) follows the same signature, ultimately using the `render/2` matching `page.json` to specify what each `page` looks like.
It's useful to build our views like this so that they are composable. Imagine a situation where our `Page` has a `has_many` relationship (#NOTE: We haven't talked about has\_many relationship yet#) with `Author`, and depending on the request, we may want to send back `author` data with the `page`. We can easily accomplish this with a new `render/2`:
```
defmodule HelloWeb.PageView do
use HelloWeb, :view
alias HelloWeb.AuthorView
def render("page_with_authors.json", %{page: page}) do
%{title: page.title,
authors: render_many(page.authors, AuthorView, "author.json")}
end
def render("page.json", %{page: page}) do
%{title: page.title}
end
end
```
The name used in assigns is determined from the view. For example `PageView` will use `%{page: page}` and `AuthorView` will use `%{author: author}`. This can be overridden with the `as` option. Let's assume that the author view uses `%{writer: writer}` instead of `%{author: author}`:
```
def render("page_with_authors.json", %{page: page}) do
%{title: page.title,
authors: render_many(page.authors, AuthorView, "author.json", as: :writer)}
end
```
Error pages
------------
Phoenix has a view called `ErrorView` which lives in `lib/hello_web/views/error_view.ex`. The purpose of `ErrorView` is to handle errors in a general way, from one centralized location. Similar to the views we built in this guide, error views can return both HTML and JSON responses. See the [Custom Error Pages How-To](custom_error_pages) for more information.
[← Previous Page Controllers](controllers) [Next Page → Ecto](ecto)
| programming_docs |
phoenix Phoenix.Logger Phoenix.Logger
===============
Instrumenter to handle logging of various instrumentation events.
Instrumentation
----------------
Phoenix uses the `:telemetry` library for instrumentation. The following events are published by Phoenix with the following measurements and metadata:
* `[:phoenix, :endpoint, :start]` - dispatched by [`Plug.Telemetry`](https://hexdocs.pm/plug/1.13.6/Plug.Telemetry.html) in your endpoint, usually after code reloading
+ Measurement: `%{system_time: system_time}`
+ Metadata: `%{conn: Plug.Conn.t, options: Keyword.t}`
+ Options: `%{log: Logger.level | false}`
+ Disable logging: In your endpoint `plug Plug.Telemetry, ..., log: Logger.level | false`
+ Configure log level dynamically: `plug Plug.Telemetry, ..., log: {Mod, Fun, Args}`
* `[:phoenix, :endpoint, :stop]` - dispatched by [`Plug.Telemetry`](https://hexdocs.pm/plug/1.13.6/Plug.Telemetry.html) in your endpoint whenever the response is sent
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{conn: Plug.Conn.t, options: Keyword.t}`
+ Options: `%{log: Logger.level | false}`
+ Disable logging: In your endpoint `plug Plug.Telemetry, ..., log: Logger.level | false`
+ Configure log level dynamically: `plug Plug.Telemetry, ..., log: {Mod, Fun, Args}`
* `[:phoenix, :router_dispatch, :start]` - dispatched by [`Phoenix.Router`](phoenix.router) before dispatching to a matched route
+ Measurement: `%{system_time: System.system_time}`
+ Metadata: `%{conn: Plug.Conn.t, route: binary, plug: module, plug_opts: term, path_params: map, pipe_through: [atom], log: Logger.level | false}`
+ Disable logging: Pass `log: false` to the router macro, for example: `get("/page", PageController, :index, log: false)`
+ Configure log level dynamically: `get("/page", PageController, :index, log: {Mod, Fun, Args})`
* `[:phoenix, :router_dispatch, :exception]` - dispatched by [`Phoenix.Router`](phoenix.router) after exceptions on dispatching a route
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{conn: Plug.Conn.t, kind: :throw | :error | :exit, reason: term(), stacktrace: Exception.stacktrace()}`
+ Disable logging: This event is not logged
* `[:phoenix, :router_dispatch, :stop]` - dispatched by [`Phoenix.Router`](phoenix.router) after successfully dispatching a matched route
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{conn: Plug.Conn.t, route: binary, plug: module, plug_opts: term, path_params: map, pipe_through: [atom], log: Logger.level | false}`
+ Disable logging: This event is not logged
* `[:phoenix, :error_rendered]` - dispatched at the end of an error view being rendered
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{conn: Plug.Conn.t, status: Plug.Conn.status, kind: Exception.kind, reason: term, stacktrace: Exception.stacktrace}`
+ Disable logging: Set `render_errors: [log: false]` on your endpoint configuration
* `[:phoenix, :socket_connected]` - dispatched by [`Phoenix.Socket`](phoenix.socket), at the end of a socket connection
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{endpoint: atom, transport: atom, params: term, connect_info: map, vsn: binary, user_socket: atom, result: :ok | :error, serializer: atom, log: Logger.level | false}`
+ Disable logging: `use Phoenix.Socket, log: false` or `socket "/foo", MySocket, websocket: [log: false]` in your endpoint
* `[:phoenix, :channel_joined]` - dispatched at the end of a channel join
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{result: :ok | :error, params: term, socket: Phoenix.Socket.t}`
+ Disable logging: This event cannot be disabled
* `[:phoenix, :channel_handled_in]` - dispatched at the end of a channel handle in
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{event: binary, params: term, socket: Phoenix.Socket.t}`
+ Disable logging: This event cannot be disabled
To see an example of how Phoenix LiveDashboard uses these events to create metrics, visit <https://hexdocs.pm/phoenix_live_dashboard/metrics.html>.
Parameter filtering
--------------------
When logging parameters, Phoenix can filter out sensitive parameters such as passwords and tokens. Parameters to be filtered can be added via the `:filter_parameters` option:
```
config :phoenix, :filter_parameters, ["password", "secret"]
```
With the configuration above, Phoenix will filter any parameter that contains the terms `password` or `secret`. The match is case sensitive.
Phoenix's default is `["password"]`.
Phoenix can filter all parameters by default and selectively keep parameters. This can be configured like so:
```
config :phoenix, :filter_parameters, {:keep, ["id", "order"]}
```
With the configuration above, Phoenix will filter all parameters, except those that match exactly `id` or `order`. If a kept parameter matches, all parameters nested under that one will also be kept.
Dynamic log level
------------------
In some cases you may wish to set the log level dynamically on a per-request basis. To do so, set the `:log` option to a tuple, `{Mod, Fun, Args}`. The `Plug.Conn.t()` for the request will be prepended to the provided list of arguments.
When invoked, your function must return a [`Logger.level()`](https://hexdocs.pm/logger/Logger.html#t:level/0) or `false` to disable logging for the request.
For example, in your Endpoint you might do something like this:
```
# lib/my_app_web/endpoint.ex
plug Plug.Telemetry,
event_prefix: [:phoenix, :endpoint],
log: {__MODULE__, :log_level, []}
# Disables logging for routes like /status/*
def log_level(%{path_info: ["status" | _]}), do: false
def log_level(_), do: :info
```
Disabling
----------
When you are using custom logging system it is not always desirable to enable [`Phoenix.Logger`](phoenix.logger#content) by default. You can always disable this in general by:
```
config :phoenix, :logger, false
```
phoenix Phoenix.Tracker behaviour Phoenix.Tracker behaviour
==========================
Provides distributed presence tracking to processes.
Tracker shards use a heartbeat protocol and CRDT to replicate presence information across a cluster in an eventually consistent, conflict-free manner. Under this design, there is no single source of truth or global process. Each node runs a pool of trackers and node-local changes are replicated across the cluster and handled locally as a diff of changes.
Implementing a Tracker
-----------------------
To start a tracker, first add the tracker to your supervision tree:
```
children = [
# ...
{MyTracker, [name: MyTracker, pubsub_server: MyApp.PubSub]}
]
```
Next, implement `MyTracker` with support for the [`Phoenix.Tracker`](phoenix.tracker#content) behaviour callbacks. An example of a minimal tracker could include:
```
defmodule MyTracker do
use Phoenix.Tracker
def start_link(opts) do
opts = Keyword.merge([name: __MODULE__], opts)
Phoenix.Tracker.start_link(__MODULE__, opts, opts)
end
def init(opts) do
server = Keyword.fetch!(opts, :pubsub_server)
{:ok, %{pubsub_server: server, node_name: Phoenix.PubSub.node_name(server)}}
end
def handle_diff(diff, state) do
for {topic, {joins, leaves}} <- diff do
for {key, meta} <- joins do
IO.puts "presence join: key \"#{key}\" with meta #{inspect meta}"
msg = {:join, key, meta}
Phoenix.PubSub.direct_broadcast!(state.node_name, state.pubsub_server, topic, msg)
end
for {key, meta} <- leaves do
IO.puts "presence leave: key \"#{key}\" with meta #{inspect meta}"
msg = {:leave, key, meta}
Phoenix.PubSub.direct_broadcast!(state.node_name, state.pubsub_server, topic, msg)
end
end
{:ok, state}
end
end
```
Trackers must implement `start_link/1`, [`init/1`](#c:init/1), and [`handle_diff/2`](#c:handle_diff/2). The [`init/1`](#c:init/1) callback allows the tracker to manage its own state when running within the [`Phoenix.Tracker`](phoenix.tracker#content) server. The `handle_diff` callback is invoked with a diff of presence join and leave events, grouped by topic. As replicas heartbeat and replicate data, the local tracker state is merged with the remote data, and the diff is sent to the callback. The handler can use this information to notify subscribers of events, as done above.
An optional `handle_info/2` callback may also be invoked to handle application specific messages within your tracker.
Special Considerations
-----------------------
Operations within `handle_diff/2` happen *in the tracker server's context*. Therefore, blocking operations should be avoided when possible, and offloaded to a supervised task when required. Also, a crash in the `handle_diff/2` will crash the tracker server, so operations that may crash the server should be offloaded with a [`Task.Supervisor`](https://hexdocs.pm/elixir/Task.Supervisor.html) spawned process.
Summary
========
Types
------
[presence()](#t:presence/0) [topic()](#t:topic/0) Callbacks
----------
[handle\_diff(map, state)](#c:handle_diff/2) [handle\_info(message, state)](#c:handle_info/2) [init(t)](#c:init/1) Functions
----------
[child\_spec(init\_arg)](#child_spec/1) Returns a specification to start this module under a supervisor.
[get\_by\_key(tracker\_name, topic, key)](#get_by_key/3) Gets presences tracked under a given topic and key pair.
[graceful\_permdown(tracker\_name)](#graceful_permdown/1) Gracefully shuts down by broadcasting permdown to all replicas.
[list(tracker\_name, topic)](#list/2) Lists all presences tracked under a given topic.
[start\_link(tracker, tracker\_arg, pool\_opts)](#start_link/3) Starts a tracker pool.
[track(tracker\_name, pid, topic, key, meta)](#track/5) Tracks a presence.
[untrack(tracker\_name, pid)](#untrack/2) [untrack(tracker\_name, pid, topic, key)](#untrack/4) Untracks a presence.
[update(tracker\_name, pid, topic, key, meta)](#update/5) Updates a presence's metadata.
Types
======
### presence()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L77)
```
@type presence() :: {key :: String.t(), meta :: map()}
```
### topic()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L78)
```
@type topic() :: String.t()
```
Callbacks
==========
### handle\_diff(map, state)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L81)
```
@callback handle_diff(
%{required(topic()) => {joins :: [presence()], leaves :: [presence()]}},
state :: term()
) :: {:ok, state :: term()}
```
### handle\_info(message, state)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L82)
```
@callback handle_info(message :: term(), state :: term()) :: {:noreply, state :: term()}
```
### init(t)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L80)
```
@callback init(Keyword.t()) :: {:ok, state :: term()} | {:error, reason :: term()}
```
Functions
==========
### child\_spec(init\_arg)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L73)
Returns a specification to start this module under a supervisor.
See [`Supervisor`](https://hexdocs.pm/elixir/Supervisor.html).
### get\_by\_key(tracker\_name, topic, key)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L228)
```
@spec get_by_key(atom(), topic(), term()) :: [presence()]
```
Gets presences tracked under a given topic and key pair.
* `server_name` - The registered name of the tracker server
* `topic` - The [`Phoenix.PubSub`](phoenix.pubsub) topic
* `key` - The key of the presence
Returns a lists of presence metadata.
#### Examples
```
iex> Phoenix.Tracker.get_by_key(MyTracker, "lobby", "user1")
[{#PID<0.88.0>, %{name: "User 1"}, {#PID<0.89.0>, %{name: "User 1"}]
```
### graceful\_permdown(tracker\_name)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L243)
```
@spec graceful_permdown(atom()) :: :ok
```
Gracefully shuts down by broadcasting permdown to all replicas.
#### Examples
```
iex> Phoenix.Tracker.graceful_permdown(MyTracker)
:ok
```
### list(tracker\_name, topic)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L207)
```
@spec list(atom(), topic()) :: [presence()]
```
Lists all presences tracked under a given topic.
* `server_name` - The registered name of the tracker server
* `topic` - The [`Phoenix.PubSub`](phoenix.pubsub) topic
Returns a lists of presences in key/metadata tuple pairs.
#### Examples
```
iex> Phoenix.Tracker.list(MyTracker, "lobby")
[{123, %{name: "user 123"}}, {456, %{name: "user 456"}}]
```
### start\_link(tracker, tracker\_arg, pool\_opts)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L282)
Starts a tracker pool.
* `tracker` - The tracker module implementing the [`Phoenix.Tracker`](phoenix.tracker#content) behaviour
* `tracker_arg` - The argument to pass to the tracker handler [`init/1`](#c:init/1)
* `pool_opts` - The list of options used to construct the shard pool
#### Required `pool_opts`:
* `:name` - The name of the server, such as: `MyApp.Tracker` This will also form the common prefix for all shard names
* `:pubsub_server` - The name of the PubSub server, such as: `MyApp.PubSub`
#### Optional `pool_opts`:
* `:broadcast_period` - The interval in milliseconds to send delta broadcasts across the cluster. Default `1500`
* `:max_silent_periods` - The max integer of broadcast periods for which no delta broadcasts have been sent. Default `10` (15s heartbeat)
* `:down_period` - The interval in milliseconds to flag a replica as temporarily down. Default `broadcast_period * max_silent_periods * 2` (30s down detection). Note: This must be at least 2x the `broadcast_period`.
* `:permdown_period` - The interval in milliseconds to flag a replica as permanently down, and discard its state. Note: This must be at least greater than the `down_period`. Default `1_200_000` (20 minutes)
* `:clock_sample_periods` - The numbers of heartbeat windows to sample remote clocks before collapsing and requesting transfer. Default `2`
* `:max_delta_sizes` - The list of delta generation sizes to keep before falling back to sending entire state. Defaults `[100, 1000, 10_000]`.
* `:log_level` - The log level to log events, defaults `:debug` and can be disabled with `false`
* `:pool_size` - The number of tracker shards to launch. Default `1`
### track(tracker\_name, pid, topic, key, meta)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L132)
```
@spec track(atom(), pid(), topic(), term(), map()) ::
{:ok, ref :: binary()} | {:error, reason :: term()}
```
Tracks a presence.
* `server_name` - The registered name of the tracker server
* `pid` - The Pid to track
* `topic` - The [`Phoenix.PubSub`](phoenix.pubsub) topic for this presence
* `key` - The key identifying this presence
* `meta` - The map of metadata to attach to this presence
A process may be tracked multiple times, provided the topic and key pair are unique for any prior calls for the given process.
#### Examples
```
iex> Phoenix.Tracker.track(MyTracker, self(), "lobby", u.id, %{stat: "away"})
{:ok, "1WpAofWYIAA="}
iex> Phoenix.Tracker.track(MyTracker, self(), "lobby", u.id, %{stat: "away"})
{:error, {:already_tracked, #PID<0.56.0>, "lobby", "123"}}
```
### untrack(tracker\_name, pid)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L162)
### untrack(tracker\_name, pid, topic, key)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L157)
```
@spec untrack(atom(), pid(), topic(), term()) :: :ok
```
Untracks a presence.
* `server_name` - The registered name of the tracker server
* `pid` - The Pid to untrack
* `topic` - The [`Phoenix.PubSub`](phoenix.pubsub) topic to untrack for this presence
* `key` - The key identifying this presence
All presences for a given Pid can be untracked by calling the [`Phoenix.Tracker.untrack/2`](#untrack/2) signature of this function.
#### Examples
```
iex> Phoenix.Tracker.untrack(MyTracker, self(), "lobby", u.id)
:ok
iex> Phoenix.Tracker.untrack(MyTracker, self())
:ok
```
### update(tracker\_name, pid, topic, key, meta)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/tracker.ex#L187)
```
@spec update(atom(), pid(), topic(), term(), map() | (map() -> map())) ::
{:ok, ref :: binary()} | {:error, reason :: term()}
```
Updates a presence's metadata.
* `server_name` - The registered name of the tracker server
* `pid` - The Pid being tracked
* `topic` - The [`Phoenix.PubSub`](phoenix.pubsub) topic to update for this presence
* `key` - The key identifying this presence
* `meta` - Either a new map of metadata to attach to this presence, or a function. The function will receive the current metadata as input and the return value will be used as the new metadata
#### Examples
```
iex> Phoenix.Tracker.update(MyTracker, self(), "lobby", u.id, %{stat: "zzz"})
{:ok, "1WpAofWYIAA="}
iex> Phoenix.Tracker.update(MyTracker, self(), "lobby", u.id, fn meta -> Map.put(meta, :away, true) end)
{:ok, "1WpAofWYIAA="}
```
phoenix Phoenix.PubSub.Adapter behaviour Phoenix.PubSub.Adapter behaviour
=================================
Specification to implement a custom PubSub adapter.
Summary
========
Types
------
[adapter\_name()](#t:adapter_name/0) Callbacks
----------
[broadcast(adapter\_name, topic, message, dispatcher)](#c:broadcast/4) Broadcasts the given topic, message, and dispatcher to all nodes in the cluster (except the current node itself).
[child\_spec(keyword)](#c:child_spec/1) Returns a child specification that mounts the processes required for the adapter.
[direct\_broadcast(adapter\_name, node\_name, topic, message, dispatcher)](#c:direct_broadcast/5) Broadcasts the given topic, message, and dispatcher to given node in the cluster (it may point to itself).
[node\_name(adapter\_name)](#c:node_name/1) Returns the node name as an atom or a binary.
Types
======
### adapter\_name()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub/adapter.ex#L6)
```
@type adapter_name() :: atom()
```
Callbacks
==========
### broadcast(adapter\_name, topic, message, dispatcher)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub/adapter.ex#L33)
```
@callback broadcast(
adapter_name(),
topic :: Phoenix.PubSub.topic(),
message :: Phoenix.PubSub.message(),
dispatcher :: Phoenix.PubSub.dispatcher()
) :: :ok | {:error, term()}
```
Broadcasts the given topic, message, and dispatcher to all nodes in the cluster (except the current node itself).
### child\_spec(keyword)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub/adapter.ex#L22)
```
@callback child_spec(keyword()) :: Supervisor.child_spec()
```
Returns a child specification that mounts the processes required for the adapter.
`child_spec` will receive all options given [`Phoenix.PubSub`](phoenix.pubsub). Note, however, that the `:name` under options is the name of the complete PubSub system. The reserved key space to be used by the adapter is under the `:adapter_name` key.
### direct\_broadcast(adapter\_name, node\_name, topic, message, dispatcher)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub/adapter.ex#L45)
```
@callback direct_broadcast(
adapter_name(),
node_name :: Phoenix.PubSub.node_name(),
topic :: Phoenix.PubSub.topic(),
message :: Phoenix.PubSub.message(),
dispatcher :: Phoenix.PubSub.dispatcher()
) :: :ok | {:error, term()}
```
Broadcasts the given topic, message, and dispatcher to given node in the cluster (it may point to itself).
### node\_name(adapter\_name)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub/adapter.ex#L11)
```
@callback node_name(adapter_name()) :: Phoenix.PubSub.node_name()
```
Returns the node name as an atom or a binary.
| programming_docs |
phoenix Phoenix.PubSub.PG2 Phoenix.PubSub.PG2
===================
Phoenix PubSub adapter based on `:pg`/`:pg2`.
It runs on Distributed Erlang and is the default adapter.
Summary
========
Functions
----------
[child\_spec(init\_arg)](#child_spec/1) Returns a specification to start this module under a supervisor.
Functions
==========
### child\_spec(init\_arg)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub/pg2.ex#L9)
Returns a specification to start this module under a supervisor.
See [`Supervisor`](https://hexdocs.pm/elixir/Supervisor.html).
phoenix Phoenix.PubSub Phoenix.PubSub
===============
Realtime Publisher/Subscriber service.
Getting started
----------------
You start Phoenix.PubSub directly in your supervision tree:
```
{Phoenix.PubSub, name: :my_pubsub}
```
You can now use the functions in this module to subscribe and broadcast messages:
```
iex> alias Phoenix.PubSub
iex> PubSub.subscribe(:my_pubsub, "user:123")
:ok
iex> Process.info(self(), :messages)
{:messages, []}
iex> PubSub.broadcast(:my_pubsub, "user:123", {:user_update, %{id: 123, name: "Shane"}})
:ok
iex> Process.info(self(), :messages)
{:messages, [{:user_update, %{id: 123, name: "Shane"}}]}
```
Adapters
---------
Phoenix PubSub was designed to be flexible and support multiple backends. There are two officially supported backends:
* [`Phoenix.PubSub.PG2`](phoenix.pubsub.pg2) - the default adapter that ships as part of Phoenix.PubSub. It uses Distributed Elixir, directly exchanging notifications between servers. It supports a `:pool_size` option to be given alongside the name, defaults to `1`. Note the `:pool_size` must be the same throughout the cluster, therefore don't configure the pool size based on `System.schedulers_online/1`, especially if you are using machines with different specs.
* `Phoenix.PubSub.Redis` - uses Redis to exchange data between servers. It requires the `:phoenix_pubsub_redis` dependency.
See [`Phoenix.PubSub.Adapter`](phoenix.pubsub.adapter) to implement a custom adapter.
Custom dispatching
-------------------
Phoenix.PubSub allows developers to perform custom dispatching by passing a `dispatcher` module which is responsible for local message deliveries.
The dispatcher must be available on all nodes running the PubSub system. The `dispatch/3` function of the given module will be invoked with the subscriptions entries, the broadcaster identifier (either a pid or `:none`), and the message to broadcast.
You may want to use the dispatcher to perform special delivery for certain subscriptions. This can be done by passing the :metadata option during subscriptions. For instance, Phoenix Channels use a custom `value` to provide "fastlaning", allowing messages broadcast to thousands or even millions of users to be encoded once and written directly to sockets instead of being encoded per channel.
Summary
========
Types
------
[dispatcher()](#t:dispatcher/0) [message()](#t:message/0) [node\_name()](#t:node_name/0) [t()](#t:t/0) [topic()](#t:topic/0) Functions
----------
[broadcast!(pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)](#broadcast!/4) Raising version of [`broadcast/4`](#broadcast/4).
[broadcast(pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)](#broadcast/4) Broadcasts message on given topic across the whole cluster.
[broadcast\_from!(pubsub, from, topic, message, dispatcher \\ \_\_MODULE\_\_)](#broadcast_from!/5) Raising version of [`broadcast_from/5`](#broadcast_from/5).
[broadcast\_from(pubsub, from, topic, message, dispatcher \\ \_\_MODULE\_\_)](#broadcast_from/5) Broadcasts message on given topic from the given process across the whole cluster.
[child\_spec(options)](#child_spec/1) Returns a child specification for pubsub with the given `options`.
[direct\_broadcast!(node\_name, pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)](#direct_broadcast!/5) Raising version of [`direct_broadcast/5`](#direct_broadcast/5).
[direct\_broadcast(node\_name, pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)](#direct_broadcast/5) Broadcasts message on given topic to a given node.
[local\_broadcast(pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)](#local_broadcast/4) Broadcasts message on given topic only for the current node.
[local\_broadcast\_from(pubsub, from, topic, message, dispatcher \\ \_\_MODULE\_\_)](#local_broadcast_from/5) Broadcasts message on given topic from a given process only for the current node.
[node\_name(pubsub)](#node_name/1) Returns the node name of the PubSub server.
[subscribe(pubsub, topic, opts \\ [])](#subscribe/3) Subscribes the caller to the PubSub adapter's topic.
[unsubscribe(pubsub, topic)](#unsubscribe/2) Unsubscribes the caller from the PubSub adapter's topic.
Types
======
### dispatcher()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L68)
```
@type dispatcher() :: module()
```
### message()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L67)
```
@type message() :: term()
```
### node\_name()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L64)
```
@type node_name() :: atom() | binary()
```
### t()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L65)
```
@type t() :: atom()
```
### topic()[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L66)
```
@type topic() :: binary()
```
Functions
==========
### broadcast!(pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L234)
```
@spec broadcast!(t(), topic(), message(), dispatcher()) :: :ok
```
Raising version of [`broadcast/4`](#broadcast/4).
### broadcast(pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L146)
```
@spec broadcast(t(), topic(), message(), dispatcher()) :: :ok | {:error, term()}
```
Broadcasts message on given topic across the whole cluster.
* `pubsub` - The name of the pubsub system
* `topic` - The topic to broadcast to, ie: `"users:123"`
* `message` - The payload of the broadcast
A custom dispatcher may also be given as a fourth, optional argument. See the "Custom dispatching" section in the module documentation.
### broadcast\_from!(pubsub, from, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L245)
```
@spec broadcast_from!(t(), pid(), topic(), message(), dispatcher()) :: :ok
```
Raising version of [`broadcast_from/5`](#broadcast_from/5).
### broadcast\_from(pubsub, from, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L167)
```
@spec broadcast_from(t(), pid(), topic(), message(), dispatcher()) ::
:ok | {:error, term()}
```
Broadcasts message on given topic from the given process across the whole cluster.
* `pubsub` - The name of the pubsub system
* `from` - The pid that will send the message
* `topic` - The topic to broadcast to, ie: `"users:123"`
* `message` - The payload of the broadcast
A custom dispatcher may also be given as a fifth, optional argument. See the "Custom dispatching" section in the module documentation.
### child\_spec(options)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L93)
```
@spec child_spec(keyword()) :: Supervisor.child_spec()
```
Returns a child specification for pubsub with the given `options`.
The `:name` is required as part of `options`. The remaining options are described below.
#### Options
* `:name` - the name of the pubsub to be started
* `:adapter` - the adapter to use (defaults to [`Phoenix.PubSub.PG2`](phoenix.pubsub.pg2))
* `:pool_size` - number of pubsub partitions to launch (defaults to one partition for every 4 cores)
### direct\_broadcast!(node\_name, pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L256)
```
@spec direct_broadcast!(node_name(), t(), topic(), message(), dispatcher()) :: :ok
```
Raising version of [`direct_broadcast/5`](#direct_broadcast/5).
### direct\_broadcast(node\_name, pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L224)
Broadcasts message on given topic to a given node.
* `node_name` - The target node name
* `pubsub` - The name of the pubsub system
* `topic` - The topic to broadcast to, ie: `"users:123"`
* `message` - The payload of the broadcast
**DO NOT** use this function if you wish to broadcast to the current node, as it is always serialized, use [`local_broadcast/4`](#local_broadcast/4) instead.
A custom dispatcher may also be given as a fifth, optional argument. See the "Custom dispatching" section in the module documentation.
### local\_broadcast(pubsub, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L187)
```
@spec local_broadcast(t(), topic(), message(), dispatcher()) :: :ok
```
Broadcasts message on given topic only for the current node.
* `pubsub` - The name of the pubsub system
* `topic` - The topic to broadcast to, ie: `"users:123"`
* `message` - The payload of the broadcast
A custom dispatcher may also be given as a fourth, optional argument. See the "Custom dispatching" section in the module documentation.
### local\_broadcast\_from(pubsub, from, topic, message, dispatcher \\ \_\_MODULE\_\_)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L204)
```
@spec local_broadcast_from(t(), pid(), topic(), message(), dispatcher()) :: :ok
```
Broadcasts message on given topic from a given process only for the current node.
* `pubsub` - The name of the pubsub system
* `from` - The pid that will send the message
* `topic` - The topic to broadcast to, ie: `"users:123"`
* `message` - The payload of the broadcast
A custom dispatcher may also be given as a fifth, optional argument. See the "Custom dispatching" section in the module documentation.
### node\_name(pubsub)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L267)
```
@spec node_name(t()) :: node_name()
```
Returns the node name of the PubSub server.
### subscribe(pubsub, topic, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L119)
```
@spec subscribe(t(), topic(), keyword()) :: :ok | {:error, term()}
```
Subscribes the caller to the PubSub adapter's topic.
* `pubsub` - The name of the pubsub system
* `topic` - The topic to subscribe to, for example: `"users:123"`
* `opts` - The optional list of options. See below.
#### Duplicate Subscriptions
Callers should only subscribe to a given topic a single time. Duplicate subscriptions for a Pid/topic pair are allowed and will cause duplicate events to be sent; however, when using [`Phoenix.PubSub.unsubscribe/2`](#unsubscribe/2), all duplicate subscriptions will be dropped.
#### Options
* `:metadata` - provides metadata to be attached to this subscription. The metadata can be used by custom dispatching mechanisms. See the "Custom dispatching" section in the module documentation
### unsubscribe(pubsub, topic)[Source](https://github.com/phoenixframework/phoenix_pubsub/blob/v2.1.1/lib/phoenix/pubsub.ex#L131)
```
@spec unsubscribe(t(), topic()) :: :ok
```
Unsubscribes the caller from the PubSub adapter's topic.
phoenix Test factories Test factories
===============
Many projects depend on external libraries to build their test data. Some of those libraries are called factories because they provide convenience functions for producing different groups of data. However, given Ecto is able to manage complex data trees, we can implement such functionality without relying on third-party projects.
To get started, let's create a file at "test/support/factory.ex" with the following contents:
```
defmodule MyApp.Factory do
alias MyApp.Repo
# Factories
def build(:post) do
%MyApp.Post{title: "hello world"}
end
def build(:comment) do
%MyApp.Comment{body: "good post"}
end
def build(:post_with_comments) do
%MyApp.Post{
title: "hello with comments",
comments: [
build(:comment, body: "first"),
build(:comment, body: "second")
]
}
end
def build(:user) do
%MyApp.User{
email: "hello#{System.unique_integer()}",
username: "hello#{System.unique_integer()}"
}
end
# Convenience API
def build(factory_name, attributes) do
factory_name |> build() |> struct!(attributes)
end
def insert!(factory_name, attributes \\ []) do
factory_name |> build(attributes) |> Repo.insert!()
end
end
```
Our factory module defines four "factories" as different clauses to the build function: `:post`, `:comment`, `:post_with_comments` and `:user`. Each clause defines structs with the fields that are required by the database. In certain cases, the generated struct also needs to generate unique fields, such as the user's email and username. We did so by calling Elixir's `System.unique_integer()` - you could call `System.unique_integer([:positive])` if you need a strictly positive number.
At the end, we defined two functions, `build/2` and `insert!/2`, which are conveniences for building structs with specific attributes and for inserting data directly in the repository respectively.
That's literally all that is necessary for building our factories. We are now ready to use them in our tests. First, open up your "mix.exs" and make sure the "test/support/factory.ex" file is compiled:
```
def project do
[...,
elixirc_paths: elixirc_paths(Mix.env),
...]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
```
Now in any of the tests that need to generate data, we can import the `MyApp.Factory` module and use its functions:
```
import MyApp.Factory
build(:post)
#=> %MyApp.Post{id: nil, title: "hello world", ...}
build(:post, title: "custom title")
#=> %MyApp.Post{id: nil, title: "custom title", ...}
insert!(:post, title: "custom title")
#=> %MyApp.Post{id: ..., title: "custom title"}
```
By building the functionality we need on top of Ecto capabilities, we are able to extend and improve our factories on whatever way we desire, without being constrained to third-party limitations.
[← Previous Page Schemaless queries](schemaless-queries)
phoenix Schemaless queries Schemaless queries
===================
Most queries in Ecto are written using schemas. For example, to retrieve all posts in a database, one may write:
```
MyApp.Repo.all(Post)
```
In the construct above, Ecto knows all fields and their types in the schema, rewriting the query above to:
```
query =
from p in Post,
select: %Post{title: p.title, body: p.body, ...}
MyApp.Repo.all(query)
```
Although you might use schemas for most of your queries, Ecto also adds the ability to write regular schemaless queries when preferred.
One example is this ability to select all desired fields without duplication:
```
from "posts", select: [:title, :body]
```
When a list of fields is given, Ecto will automatically convert the list of fields to a map or a struct.
Support for passing a list of fields or keyword lists is available to almost all query constructs. For example, we can use an update query to change the title of a given post without a schema:
```
def update_title(post, new_title) do
query =
from "posts",
where: [id: ^post.id],
update: [set: [title: ^new_title]]
MyApp.Repo.update_all(query, [])
end
```
The [`Ecto.Query.update/3`](ecto.query#update/3) construct supports four commands:
* `:set` - sets the given column to the given values
* `:inc` - increments the given column by the given value
* `:push` - pushes (appends) the given value to the end of an array column
* `:pull` - pulls (removes) the given value from an array column
For example, we can increment a column atomically by using the `:inc` command, with or without schemas:
```
def increment_page_views(post) do
query =
from "posts",
where: [id: ^post.id],
update: [inc: [page_views: 1]]
MyApp.Repo.update_all(query, [])
end
```
Let's take a look at another example. Imagine you are writing a reporting view, it may be counter-productive to think how your existing application schemas relate to the report being generated. It is often simpler to write a query that returns only the data you need, without trying to fit the data into existing schemas:
```
import Ecto.Query
def running_activities(start_at, end_at) do
query =
from u in "users",
join: a in "activities",
on: a.user_id == u.id,
where:
a.start_at > type(^start_at, :naive_datetime) and
a.end_at < type(^end_at, :naive_datetime),
group_by: a.user_id,
select: %{
user_id: a.user_id,
interval: a.end_at - a.start_at,
count: count(u.id)
}
MyApp.Repo.all(query)
end
```
The function above does not rely on schemas. It returns only the data that matters for building the report. Notice how we use the `type/2` function to specify what is the expected type of the argument we are interpolating, benefiting from the same type casting guarantees a schema would give.
By allowing regular data structures to be given to most query operations, Ecto makes queries with and without schemas more accessible. Not only that, it also enables developers to write dynamic queries, where fields, filters, ordering cannot be specified upfront.
insert\_all, update\_all and delete\_all
-----------------------------------------
Ecto allows all database operations to be expressed without a schema. One of the functions provided is [`Ecto.Repo.insert_all/3`](ecto.repo#c:insert_all/3). With `insert_all`, developers can insert multiple entries at once into a repository:
```
MyApp.Repo.insert_all(
Post,
[
[title: "hello", body: "world"],
[title: "another", body: "post"]
]
)
```
Updates and deletes can also be done without schemas via [`Ecto.Repo.update_all/3`](ecto.repo#c:update_all/3) and [`Ecto.Repo.delete_all/2`](ecto.repo#c:delete_all/2) respectively:
```
# Use the ID to trigger updates
post = from p in "posts", where: [id: ^id]
# Update the title for all matching posts
{1, _} =
MyApp.Repo.update_all post, set: [title: "new title"]
# Delete all matching posts
{1, _} =
MyApp.Repo.delete_all post
```
It is not hard to see how these operations directly map to their SQL variants, keeping the database at your fingertips without the need to intermediate all operations through schemas.
[← Previous Page Replicas and dynamic repositories](replicas-and-dynamic-repositories) [Next Page → Test factories](test-factories)
phoenix Ecto.InvalidChangesetError exception Ecto.InvalidChangesetError exception
=====================================
Raised when we cannot perform an action because the changeset is invalid.
Summary
========
Functions
----------
[message(map)](#message/1) Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
Functions
==========
### message(map)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/exceptions.ex#L92)
Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
| programming_docs |
phoenix Ecto.QueryError exception Ecto.QueryError exception
==========================
Raised at runtime when the query is invalid.
phoenix Ecto.Association.NotLoaded Ecto.Association.NotLoaded
===========================
Struct returned by associations when they are not loaded.
The fields are:
* `__field__` - the association field in `owner`
* `__owner__` - the schema that owns the association
* `__cardinality__` - the cardinality of the association
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/association.ex#L14)
```
@type t() :: %Ecto.Association.NotLoaded{
__cardinality__: atom(),
__field__: atom(),
__owner__: any()
}
```
phoenix Embedded Schemas Embedded Schemas
=================
Embedded schemas allow you to define and validate structured data. This data can live in memory, or can be stored in the database. Some use cases for embedded schemas include:
* You are maintaining intermediate-state data, like when UI form fields map onto multiple tables in a database.
* You are working within a persisted parent schema and you want to embed data that is...
+ simple, like a map of user preferences inside a User schema.
+ changes often, like a list of product images with associated structured data inside a Product schema.
+ requires complex tracking and validation, like an Address schema inside a User schema.
* You are using a document storage database and you want to interact with and manipulate embedded documents.
User Profile Example
---------------------
Let's explore an example where we have a User and want to store "profile" information about them. The data we want to store is UI-dependent information which is likely to change over time alongside changes in the UI. Also, this data is not necessarily important enough to warrant new User `field`s in the User schema, as it is not data that is fundamental to the User. An embedded schema is a good solution for this kind of data.
```
defmodule User do
use Ecto.Schema
schema "users" do
field :full_name, :string
field :email, :string
field :avatar_url, :string
field :confirmed_at, :naive_datetime
embeds_one :profile do
field :online, :boolean
field :dark_mode, :boolean
field :visibility, Ecto.Enum, values: [:public, :private, :friends_only]
end
timestamps()
end
end
```
### Embeds
There are two ways to represent embedded data within a schema, `embeds_many`, which creates a list of embeds, and `embeds_one`, which creates only a single instance of the embed. Your choice here affects the behavior of embed-specific functions like [`Ecto.Changeset.put_embed/4`](ecto.changeset#put_embed/4) and [`Ecto.Changeset.cast_embed/3`](ecto.changeset#cast_embed/3), so choose whichever is most appropriate to your use case. In our example we are going to use `embeds_one` since users will only ever have one profile associated with them.
```
defmodule User do
use Ecto.Schema
schema "users" do
field :full_name, :string
field :email, :string
field :avatar_url, :string
field :confirmed_at, :naive_datetime
embeds_one :profile do
field :online, :boolean
field :dark_mode, :boolean
field :visibility, Ecto.Enum, values: [:public, :private, :friends_only]
end
timestamps()
end
end
```
### Extracting the embeds
While the above User schema is simple and sufficient, we might want to work independently with the embedded profile struct. For example, if there was a lot of functionality devoted solely to manipulating the profile data, we'd want to consider extracting the embedded schema into its own module.
```
# user/user.ex
defmodule User do
use Ecto.Schema
schema "users" do
field :full_name, :string
field :email, :string
field :avatar_url, :string
field :confirmed_at, :naive_datetime
embeds_one :profile, UserProfile
timestamps()
end
end
# user/user_profile.ex
defmodule UserProfile do
use Ecto.Schema
embedded_schema do
field :online, :boolean
field :dark_mode, :boolean
field :visibility, Ecto.Enum, values: [:public, :private, :friends_only]
end
end
```
It is important to remember that `embedded_schema` has many use cases independent of `embeds_one` and `embeds_many`. You can think of embedded schemas as persistence agnostic `schema`s. This makes embedded schemas ideal for scenarios where you want to manage structured data without necessarily persisting it. For example, if you want to build a contact form, you still want to parse and validate the data, but the data is likely not persisted anywhere. Instead, it is used to send an email. Embedded schemas would be a good fit for such a use case.
### Migrations
If you wish to save your embedded schema to the database, you need to write a migration to include the embedded data.
```
alter table("users") do
add :profile, :map
end
```
Whether you use `embeds_one` or `embeds_many`, it is recommended to use the `:map` data type (although `{:array, :map}` will work with `embeds_many` as well). The reason is that typical relational databases are likely to represent a `:map` as JSON (or JSONB in Postgres), allowing Ecto adapter libraries more flexibility over how to efficiently store the data.
### Changesets
Changeset functionality for embeds will allow you to enforce arbitrary validations on the data. You can define a changeset function for each module. For example, the UserProfile module could require the `online` and `visibility` fields to be present when generating a changeset.
```
defmodule UserProfile do
# ...
def changeset(%UserProfile{} = profile, attrs \\ %{}) do
profile
|> cast(attrs, [:online, :dark_mode, :visibility])
|> validate_required([:online, :visibility])
end
end
profile = %UserProfile{}
UserProfile.changeset(profile, %{online: true, visibility: :public})
```
Meanwhile, the User changeset function can require its own validations without worrying about the details of the UserProfile changes because it can pass that responsibility to UserProfile via `cast_embed/3`. A validation failure in an embed will cause the parent changeset to be invalid, even if the parent changeset itself had no errors.
```
defmodule User do
# ...
def changeset(user, attrs \\ %{}) do
user
|> cast(attrs, [:full_name, :email, :avatar_url])
|> cast_embed(:profile, required: true)
end
end
changeset = User.changeset(%User{}, %{profile: %{online: true}})
changeset.valid? # => false; "visibility can't be blank"
changeset = User.changeset(%User{}, %{profile: %{online: true, visibility: :public}})
changeset.valid? # => true
```
In situations where you have kept the embedded schema within the parent module, e.g., you have not extracted a UserProfile, you can still have custom changeset functions for the embedded data within the parent schema.
```
defmodule User do
use Ecto.Schema
schema "users" do
field :full_name, :string
field :email, :string
field :avatar_url, :string
field :confirmed_at, :naive_datetime
embeds_one :profile, Profile do
field :online, :boolean
field :dark_mode, :boolean
field :visibility, Ecto.Enum, values: [:public, :private, :friends_only]
end
timestamps()
end
def changeset(%User{} = user, attrs \\ %{}) do
user
|> cast(attrs, [:full_name, :email])
|> cast_embed(:profile, required: true, with: &profile_changeset/2)
end
def profile_changeset(profile, attrs \\ %{}) do
profile
|> cast(attrs, [:online, :dark_mode, :visibility])
|> validate_required([:online, :visibility])
end
end
changeset = User.changeset(%User{}, %{profile: %{online: true, visibility: :public}})
changeset.valid? # => true
```
### Querying embedded data
Once you have written embedded data to the database, you can use it in queries on the parent schema.
```
user_changeset = User.changeset(%User{}, %{profile: %{online: true, visibility: :public}})
{:ok, _user} = Repo.insert(user_changeset)
(Ecto.Query.from u in User, select: {u.profile["online"], u.profile["visibility"]}) |> Repo.one
# => {true, "public"}
(Ecto.Query.from u in User, select: u.profile, where: u.profile["visibility"] == ^:public) |> Repo.all
# => [
# %UserProfile{
# id: "...",
# online: true,
# dark_mode: nil,
# visibility: :public
# }
#]
```
In databases where `:map`s are stored as JSONB (like Postgres), Ecto constructs the appropriate jsonpath queries for you. More examples of embedded schema queries are documented in [`json_extract_path/2`](ecto.query.api#json_extract_path/2).
[← Previous Page Getting Started](getting-started) [Next Page → Testing with Ecto](testing-with-ecto)
phoenix Changelog for v3.x Changelog for v3.x
===================
v3.8.4 (2022-06-04)
--------------------
### Enhancements
* [Ecto.Multi] Add `one/2` and `all/2` functions
* [Ecto.Query] Support `literal(...)` in `fragment`
### Bug fix
* [Ecto.Schema] Make sure fields are inspected in the correct order in Elixir v1.14+
v3.8.3 (2022-05-11)
--------------------
### Bug fix
* [Ecto.Query] Allow source aliases to be used in `type/2`
* [Ecto.Schema] Avoid "undefined behaviour/struct" warnings and errors during compilation
v3.8.2 (2022-05-05)
--------------------
### Bug fix
* [Ecto.Adapter] Do not require adapter metadata to be raw maps
* [Ecto.Association] Respect `join_where` in many to many `on_replace` deletes
* [Ecto.Changeset] Check if list is in `empty_values` before nested validations
v3.8.1 (2022-04-27)
--------------------
### Bug fix
* [Ecto.Query] Fix regression where a join's on parameter on `update_all` was out of order
v3.8.0 (2022-04-26)
--------------------
Ecto v3.8 requires Elixir v1.10+.
### Enhancements
* [Ecto] Add new Embedded chapter to Introductory guides
* [Ecto.Changeset] Allow custom `:error_key` in unique\_constraint
* [Ecto.Changeset] Add `:match` option to all constraint functions
* [Ecto.Query] Support dynamic aliases
* [Ecto.Query] Allow using `type/2` with virtual fields
* [Ecto.Query] Suggest alternatives to inexistent fields in queries
* [Ecto.Query] Support passing queries using subqueries to `insert_all`
* [Ecto.Repo] Allow `stacktrace: true` so stacktraces are included in telemetry events and logs
* [Ecto.Schema] Validate options given to schema fields
### Bug fixes
* [Ecto.Changeset] Address regression on `validate_subset` no longer working with custom array types
* [Ecto.Changeset] **Potentially breaking change**: Detect `empty_values` inside lists when casting. This may cause issues if you were relying on the casting of empty values (by default, only `""`).
* [Ecto.Query] Handle atom list sigils in `select`
* [Ecto.Query] Improve tracking of `select_merge` inside subqueries
* [Ecto.Repo] Properly handle literals in queries given to `insert_all`
* [Ecto.Repo] Don't surface persisted data as changes on embed updates
* [Ecto.Schema] Preserve parent prefix on join tables
v3.7.2 (2022-03-13)
--------------------
### Enhancements
* [Ecto.Schema] Add option to skip validations for default values
* [Ecto.Query] Allow coalesce in `type/2`
* [Ecto.Query] Support parameterized types in type/2
* [Ecto.Query] Allow arbitrary parentheses in query expressions
v3.7.1 (2021-08-27)
--------------------
### Enhancements
* [Ecto.Embedded] Make [`Ecto.Embedded`](ecto.embedded) public and describe struct fields
### Bug fixes
* [Ecto.Repo] Make sure parent changeset is included in changes for `insert`/`update`/`delete` when there are errors processing the parent itself
v3.7.0 (2021-08-19)
--------------------
### Enhancements
* [Ecto.Changeset] Add [`Ecto.Changeset.traverse_validations/2`](ecto.changeset#traverse_validations/2)
* [Ecto.Enum] Add [`Ecto.Enum.mappings/2`](ecto.enum#mappings/2) and [`Ecto.Enum.dump_values/2`](ecto.enum#dump_values/2)
* [Ecto.Query] Add support for dynamic `as(^as)` and `parent_as(^as)`
* [Ecto.Repo] Add stale changeset to [`Ecto.StaleEntryError`](ecto.staleentryerror) fields
* [Ecto.Schema] Add support for `@schema_context` to set context metadata on schema definition
### Bug fixes
* [Ecto.Changeset] Fix changeset inspection not redacting when embedded
* [Ecto.Changeset] Use semantic comparison on `validate_inclusion`, `validate_exclusion`, and `validate_subset`
* [Ecto.Enum] Raise on duplicate values in [`Ecto.Enum`](ecto.enum)
* [Ecto.Query] Make sure `hints` are included in the query cache
* [Ecto.Repo] Support placeholders in `insert_all` without schemas
* [Ecto.Repo] Wrap in a subquery when query given to `Repo.aggregate` has combination
* [Ecto.Repo] Fix CTE subqueries not finding parent bindings
* [Ecto.Repo] Return changeset with assocs if any of the assocs are invalid
v3.6.2 (2021-05-28)
--------------------
### Enhancements
* [Ecto.Query] Support macros in `with_cte`
* [Ecto.Repo] Add [`Ecto.Repo.all_running/0`](ecto.repo#all_running/0) to list all running repos
### Bug fixes
* [Ecto.Query] Do not omit nil fields in a subquery select
* [Ecto.Query] Allow `parent_as` to look for an alias all the way up across subqueries
* [Ecto.Query] Raise if a nil value is given to a query from a nested map parameter
* [Ecto.Query] Fix `insert_all` when using both `:on_conflict` and `:placeholders`
* [mix ecto.load] Do not pass `--force` to underlying compile task
v3.6.1 (2021-04-12)
--------------------
### Enhancements
* [Ecto.Changeset] Allow the `:query` option in `unsafe_validate_unique`
### Bug fixes
* [Ecto.Changeset] Add the relation id in `apply_changes` if the relation key exists (instead of hardcoding it to `id`)
v3.6.0 (2021-04-03)
--------------------
### Enhancements
* [Ecto.Changeset] Support `:repo_opts` in `unsafe_validate_unique`
* [Ecto.Changeset] Add a validation error if trying to cast a cardinality one embed/assoc with anything other than a map or keyword list
* [Ecto.Enum] Allow enums to map to custom values
* [Ecto.Multi] Add [`Ecto.Multi.put/3`](ecto.multi#put/3) for directly storing values
* [Ecto.Query] **Potentially breaking change**: optimize `many_to_many` queries so it no longer load intermediary tables in more occasions. This may cause issues if you are using [`Ecto.assoc/2`](ecto#assoc/2) to load `many_to_many` associations and then trying to access intermediate bindings (which is discouraged but it was possible)
* [Ecto.Repo] Allow `insert_all` to be called with a query instead of rows
* [Ecto.Repo] Add `:placeholders` support to `insert_all` to avoid sending the same value multiple times
* [Ecto.Schema] Support `:preload_order` on `has_many` and `many_to_many` associations
* [Ecto.UUID] Add bang UUID conversion methods
* [Ecto.Query] The `:hints` option now accepts dynamic values when supplied as tuples
* [Ecto.Query] Support `select: map(source, fields)` where `source` is a fragment
* [Ecto.Query] Allow referring to the parent query in a join's subquery select via `parent_as`
* [mix ecto] Support file and line interpolation on `ECTO_EDITOR`
### Bug fixes
* [Ecto.Changeset] Change `apply_changes/1` to add the relation to the `struct.relation_id` if relation struct is persisted
* [Ecto.Query] Remove unnecessary INNER JOIN in many to many association query
* [Ecto.Query] Allow parametric types to be interpolated in queries
* [Ecto.Schema] Raise [`ArgumentError`](https://hexdocs.pm/elixir/ArgumentError.html) when default has invalid type
v3.5.8 (2021-02-21)
--------------------
### Enhancements
* [Ecto.Query] Support map/2 on fragments and subqueries
v3.5.7 (2021-02-07)
--------------------
### Bug fixes
* [Ecto.Query] Fixes param ordering issue on dynamic queries with subqueries
v3.5.6 (2021-01-20)
--------------------
### Enhancements
* [Ecto.Schema] Support `on_replace: :delete_if_exists` on associations
### Bug fixes
* [Ecto.Query] Allow unary minus operator in query expressions
* [Ecto.Schema] Allow nil values on typed maps
v3.5.5 (2020-11-12)
--------------------
### Enhancements
* [Ecto.Query] Add support for subqueries operators: `all`, `any`, and `exists`
### Bug fixes
* [Ecto.Changeset] Use association source on `put_assoc` with maps/keywords
* [Ecto.Enum] Add `cast` clause for nil values on [`Ecto.Enum`](ecto.enum)
* [Ecto.Schema] Allow nested type `:any` for non-virtual fields
v3.5.4 (2020-10-28)
--------------------
### Enhancements
* [mix ecto.drop] Provide `--force-drop` for databases that may support it
* [guides] Add new "Multi tenancy with foreign keys" guide
### Bug fixes
* [Ecto.Changeset] Make keys optional in specs
* [Ecto.Enum] Make sure `values/2` works for virtual fields
* [Ecto.Query] Fix missing type on CTE queries that select a single field
v3.5.3 (2020-10-21)
--------------------
### Bug fixes
* [Ecto.Query] Do not reset parameter counter for nested CTEs
* [Ecto.Type] Fix regression where array type with nils could no longer be cast/load/dump
* [Ecto.Type] Fix CaseClauseError when casting a decimal with a binary remainder
v3.5.2 (2020-10-12)
--------------------
### Enhancements
* [Ecto.Repo] Add Repo.reload/2 and Repo.reload!/2
### Bug fixes
* [Ecto.Changeset] Fix "**schema**/1 is undefined or private" error while inspecting a schemaless changeset
* [Ecto.Repo] Invoke [`Ecto.Repo.default_options/1`](ecto.repo#c:default_options/1) per entry-point operation
v3.5.1 (2020-10-08)
--------------------
### Enhancements
* [Ecto.Changeset] Warn if there are duplicate IDs in the parent schema for `cast_assoc/3`/`cast_embed/3`
* [Ecto.Schema] Allow `belongs_to` to accept options for parameterized types
### Bug fixes
* [Ecto.Query] Keep field types when using a subquery with source
v3.5.0 (2020-10-03)
--------------------
v3.5 requires Elixir v1.8+.
### Bug fixes
* [Ecto.Changeset] Ensure `:empty_values` in `cast/4` does not automatically propagate to following cast calls. If you want a given set of `:empty_values` to apply to all `cast/4` calls, change the value stored in `changeset.empty_values` instead
* [Ecto.Changeset] **Potentially breaking change**: Do not force repository updates to happen when using `optimistic_lock`. The lock field will only be incremented if the record has other changes. If no changes, nothing happens.
* [Ecto.Changeset] Do not automatically share empty values across `cast/3` calls
* [Ecto.Query] Consider query prefix in cte/combination query cache
* [Ecto.Query] Allow the entry to be marked as nil when using left join with subqueries
* [Ecto.Query] Support subqueries inside dynamic expressions
* [Ecto.Repo] Fix preloading when using dynamic repos and the sandbox in automatic mode
* [Ecto.Repo] Do not duplicate collections when associations are preloaded for repeated elements
### Enhancements
* [Ecto.Enum] Add [`Ecto.Enum`](ecto.enum) as a custom parameterized type
* [Ecto.Query] Allow `:prefix` in `from` to be set to nil
* [Ecto.Query] Do not restrict subqueries in `where` to map/struct types
* [Ecto.Query] Allow atoms in query without interpolation in order to support Ecto.Enum
* [Ecto.Schema] Do not validate uniqueness if there is a prior error on the field
* [Ecto.Schema] Allow `redact: true` in `field`
* [Ecto.Schema] Support parameterized types via [`Ecto.ParameterizedType`](ecto.parameterizedtype)
* [Ecto.Schema] Rewrite embeds and assocs as parameterized types. This means `__schema__(:type, assoc_or_embed)` now returns a parameterized type. To check if something is an association, use `__schema__(:assocs)` or `__schema__(:embeds)` instead
v3.4.6 (2020-08-07)
--------------------
### Enhancements
* [Ecto.Query] Allow `count/0` on `type/2`
* [Ecto.Multi] Support anonymous functions in multiple functions
### Bug fixes
* [Ecto.Query] Consider booleans as literals in unions, subqueries, ctes, etc
* [Ecto.Schema] Generate IDs for nested embeds
v3.4.5 (2020-06-14)
--------------------
### Enhancements
* [Ecto.Changeset] Allow custom error key in `unsafe_validate_unique`
* [Ecto.Changeset] Improve performance when casting large params maps
### Bug fixes
* [Ecto.Changeset] Improve error message for invalid `cast_assoc`
* [Ecto.Query] Fix inspecting query with fragment CTE
* [Ecto.Query] Fix inspecting dynamics with aliased bindings
* [Ecto.Query] Improve error message when selecting a single atom
* [Ecto.Repo] Reduce data-copying when preloading multiple associations
* [Ecto.Schema] Do not define a compile-time dependency for schema in `:join_through`
v3.4.4 (2020-05-11)
--------------------
### Enhancements
* [Ecto.Schema] Add `join_where` support to `many_to_many`
v3.4.3 (2020-04-27)
--------------------
### Enhancements
* [Ecto.Query] Support `as/1` and `parent_as/1` for lazy named bindings and to allow parent references from subqueries
* [Ecto.Query] Support `x in subquery(query)`
### Bug fixes
* [Ecto.Query] Do not raise for missing assocs if :force is given to preload
* [Ecto.Repo] Return error from `Repo.delete` on invalid changeset from `prepare_changeset`
v3.4.2 (2020-04-10)
--------------------
### Enhancements
* [Ecto.Changeset] Support multiple fields in `unique_constraint/3`
v3.4.1 (2020-04-08)
--------------------
### Enhancements
* [Ecto] Add [`Ecto.embedded_load/3`](ecto#embedded_load/3) and [`Ecto.embedded_dump/2`](ecto#embedded_dump/2)
* [Ecto.Query] Improve error message on invalid JSON expressions
* [Ecto.Repo] Emit `[:ecto, :repo, :init]` telemetry event upon Repo init
### Bug fixes
* [Ecto.Query] Do not support JSON selectors on `type/2`
### Deprecations
* [Ecto.Repo] Deprecate `conflict_target: {:constraint, _}`. It is a discouraged approach and `{:unsafe_fragment, _}` is still available if someone definitely needs it
v3.4.0 (2020-03-24)
--------------------
v3.4 requires Elixir v1.7+.
### Enhancements
* [Ecto.Query] Allow dynamic queries in CTE and improve error message
* [Ecto.Query] Add [`Ecto.Query.API.json_extract_path/2`](ecto.query.api#json_extract_path/2) and JSON path support to query syntax. For example, `posts.metadata["tags"][0]["name"]` will return the name of the first tag stored in the `:map` metadata field
* [Ecto.Repo] Add new `default_options/1` callback to repository
* [Ecto.Repo] Support passing `:telemetry_options` to repository operations
### Bug fixes
* [Ecto.Changeset] Properly add validation annotation to `validate_acceptance`
* [Ecto.Query] Raise if there is loaded non-empty association data without related key when preloading. This typically means not all fields have been loaded in a query
* [Ecto.Schema] Show meaningful error in case `schema` is invoked twice in an [`Ecto.Schema`](ecto.schema)
v3.3.4 (2020-02-27)
--------------------
### Bug fixes
* [mix ecto] Do not rely on map ordering when parsing repos
* [mix ecto.gen.repo] Improve error message when a repo is not given
v3.3.3 (2020-02-14)
--------------------
### Enhancements
* [Ecto.Query] Support fragments in `lock`
* [Ecto.Query] Handle `nil` in `select_merge` with similar semantics to SQL databases (i.e. it simply returns `nil` itself)
v3.3.2 (2020-01-28)
--------------------
### Enhancements
* [Ecto.Changeset] Only bump optimistic lock in case of success
* [Ecto.Query] Allow macros in Ecto window expressions
* [Ecto.Schema] Support `:join_defaults` on `many_to_many` associations
* [Ecto.Schema] Allow MFargs to be given to association `:defaults`
* [Ecto.Type] Add `Ecto.Type.embedded_load` and `Ecto.Type.embedded_dump`
### Bug fixes
* [Ecto.Repo] Ignore empty hostname when parsing database url (Elixir v1.10 support)
* [Ecto.Repo] Rewrite combinations on Repo.exists? queries
* [Ecto.Schema] Respect child `@schema_prefix` in `cast_assoc`
* [mix ecto.gen.repo] Use `config_path` when writing new config in [`mix ecto.gen.repo`](mix.tasks.ecto.gen.repo)
v3.3.1 (2019-12-27)
--------------------
### Enhancements
* [Ecto.Query.WindowAPI] Support `filter/2`
### Bug fixes
* [Ecto.Query.API] Fix `coalesce/2` usage with mixed types
v3.3.0 (2019-12-11)
--------------------
### Enhancements
* [Ecto.Adapter] Add `storage_status/1` callback to `Ecto.Adapters.Storage` behaviour
* [Ecto.Changeset] Add [`Ecto.Changeset.apply_action!/2`](ecto.changeset#apply_action!/2)
* [Ecto.Changeset] Remove actions restriction in [`Ecto.Changeset.apply_action/2`](ecto.changeset#apply_action/2)
* [Ecto.Repo] Introduce `c:Ecto.Repo.aggregate/2`
* [Ecto.Repo] Support `{:replace_all_except, fields}` in `:on_conflict`
### Bug fixes
* [Ecto.Query] Make sure the `:prefix` option in `:from`/`:join` also cascades to subqueries
* [Ecto.Query] Make sure the `:prefix` option in `:join` also cascades to queries
* [Ecto.Query] Use database returned values for literals. Previous Ecto versions knew literals from queries should not be discarded for combinations but, even if they were not discarded, we would ignore the values returned by the database
* [Ecto.Repo] Do not wrap schema operations in a transaction if already inside a transaction. We have also removed the **private** option called `:skip_transaction`
### Deprecations
* [Ecto.Repo] `:replace_all_except_primary_keys` is deprecated in favor of `{:replace_all_except, fields}` in `:on_conflict`
v3.2.5 (2019-11-03)
--------------------
### Bug fixes
* [Ecto.Query] Fix a bug where executing some queries would leak the `{:maybe, ...}` type
v3.2.4 (2019-11-02)
--------------------
### Bug fixes
* [Ecto.Query] Improve error message on invalid join binding
* [Ecto.Query] Make sure the `:prefix` option in `:join` also applies to through associations
* [Ecto.Query] Invoke custom type when loading aggregations from the database (but fallback to database value if it can't be cast)
* [mix ecto.gen.repo] Support Elixir v1.9 style configs
v3.2.3 (2019-10-17)
--------------------
### Bug fixes
* [Ecto.Changeset] Do not convert enums given to `validate_inclusion` to a list
### Enhancements
* [Ecto.Changeset] Improve error message on non-atom keys to change/put\_change
* [Ecto.Changeset] Allow :with to be given as a `{module, function, args}` tuple on `cast_association/cast_embed`
* [Ecto.Changeset] Add `fetch_change!/2` and `fetch_field!/2`
v3.2.2 (2019-10-01)
--------------------
### Bug fixes
* [Ecto.Query] Fix keyword arguments given to `:on` when a bind is not given to join
* [Ecto.Repo] Make sure a preload given to an already preloaded has\_many :through is loaded
v3.2.1 (2019-09-17)
--------------------
### Enhancements
* [Ecto.Changeset] Add rollover logic for default incrementer in `optimistic_lock`
* [Ecto.Query] Also expand macros when used inside `type/2`
### Bug fixes
* [Ecto.Query] Ensure queries with non-cacheable queries in CTEs/combinations are also not-cacheable
v3.2.0 (2019-09-07)
--------------------
v3.2 requires Elixir v1.6+.
### Enhancements
* [Ecto.Query] Add common table expressions support `with_cte/3` and `recursive_ctes/2`
* [Ecto.Query] Allow `dynamic/3` to be used in `order_by`, `distinct`, `group_by`, as well as in `partition_by`, `order_by`, and `frame` inside `windows`
* [Ecto.Query] Allow filters in `type/2` expressions
* [Ecto.Repo] Merge options given to the repository into the changeset `repo_opts` and assign it back to make it available down the chain
* [Ecto.Repo] Add `prepare_query/3` callback that is invoked before query operations
* [Ecto.Repo] Support `:returning` option in `Ecto.Repo.update/2`
* [Ecto.Repo] Support passing a one arity function to `Ecto.Repo.transaction/2`, where the argument is the current repo
* [Ecto.Type] Add a new `embed_as/1` callback to [`Ecto.Type`](ecto.type) that allows adapters to control embedding behaviour
* [Ecto.Type] Add `use Ecto.Type` for convenience that implements the new required callbacks
### Bug fixes
* [Ecto.Association] Ensure we delete an association before inserting when replacing on `has_one`
* [Ecto.Query] Do not allow interpolated `nil` in literal keyword list when building query
* [Ecto.Query] Do not remove literals from combinations, otherwise UNION/INTERSECTION queries may not match the number of values in `select`
* [Ecto.Query] Do not attempt to merge at compile-time non-keyword lists given to `select_merge`
* [Ecto.Repo] Do not override `:through` associations on preload unless forcing
* [Ecto.Repo] Make sure prefix option cascades to combinations and recursive queries
* [Ecto.Schema] Use OS time without drift when generating timestamps
* [Ecto.Type] Allow any datetime in `datetime_add`
v3.1.7 (2019-06-27)
--------------------
### Bug fixes
* [Ecto.Changeset] Make sure `put_assoc` with empty changeset propagates on insert
v3.1.6 (2019-06-19)
--------------------
### Enhancements
* [Ecto.Repo] Add `:read_only` repositories
* [Ecto.Schema] Also validate options given to `:through` associations
### Bug fixes
* [Ecto.Changeset] Do not mark `put_assoc` from `[]` to `[]` or from `nil` to `nil` as change
* [Ecto.Query] Remove named binding when excluding joins
* [mix ecto.gen.repo] Use `:config_path` instead of hardcoding to `config/config.exs`
v3.1.5 (2019-06-06)
--------------------
### Enhancements
* [Ecto.Repo] Allow `:default_dynamic_repo` option on `use Ecto.Repo`
* [Ecto.Schema] Support `{:fragment, ...}` in the `:where` option for associations
### Bug fixes
* [Ecto.Query] Fix handling of literals in combinators (union, except, intersection)
v3.1.4 (2019-05-07)
--------------------
### Bug fixes
* [Ecto.Changeset] Convert validation enums to lists before adding them as validation metadata
* [Ecto.Schema] Properly propagate prefix to join\_through source in many\_to\_many associations
v3.1.3 (2019-04-30)
--------------------
### Enhancements
* [Ecto.Changeset] Expose the enum that was validated against in errors from enum-based validations
v3.1.2 (2019-04-24)
--------------------
### Enhancements
* [Ecto.Query] Add support for `type+over`
* [Ecto.Schema] Allow schema fields to be excluded from queries
### Bug fixes
* [Ecto.Changeset] Do not list a field as changed if it is updated to its original value
* [Ecto.Query] Keep literal numbers and bitstring in subqueries and unions
* [Ecto.Query] Improve error message for invalid `type/2` expression
* [Ecto.Query] Properly count interpolations in `select_merge/2`
v3.1.1 (2019-04-04)
--------------------
### Bug fixes
* [Ecto] Do not require Jason (i.e. it should continue to be an optional dependency)
* [Ecto.Repo] Make sure `many_to_many` and [`Ecto.Multi`](ecto.multi) work with dynamic repos
v3.1.0 (2019-04-02)
--------------------
v3.1 requires Elixir v1.5+.
### Enhancements
* [Ecto.Changeset] Add `not_equal_to` option for `validate_number`
* [Ecto.Query] Improve error message for missing `fragment` arguments
* [Ecto.Query] Improve error message on missing struct key for structs built in `select`
* [Ecto.Query] Allow dynamic named bindings
* [Ecto.Repo] Add dynamic repository support with `Ecto.Repo.put_dynamic_repo/1` and `Ecto.Repo.get_dynamic_repo/0` (experimental)
* [Ecto.Type] Cast naive\_datetime/utc\_datetime strings without seconds
### Bug fixes
* [Ecto.Changeset] Do not run `unsafe_validate_unique` query unless relevant fields were changed
* [Ecto.Changeset] Raise if an unknown field is given on [`Ecto.Changeset.change/2`](ecto.changeset#change/2)
* [Ecto.Changeset] Expose the type that was validated in errors generated by `validate_length/3`
* [Ecto.Query] Add support for `field/2` as first element of `type/2` and alias as second element of `type/2`
* [Ecto.Query] Do not attempt to assert types of named bindings that are not known at compile time
* [Ecto.Query] Properly cast boolean expressions in select
* [Mix.Ecto] Load applications during repo lookup so their app environment is available
### Deprecations
* [Ecto.LogEntry] Fully deprecate previously soft deprecated API
v3.0.7 (2019-02-06)
--------------------
### Bug fixes
* [Ecto.Query] `reverse_order` reverses by primary key if no order is given
v3.0.6 (2018-12-31)
--------------------
### Enhancements
* [Ecto.Query] Add `reverse_order/1`
### Bug fixes
* [Ecto.Multi] Raise better error message on accidental rollback inside [`Ecto.Multi`](ecto.multi)
* [Ecto.Query] Properly merge deeply nested preloaded joins
* [Ecto.Query] Raise better error message on missing select on schemaless queries
* [Ecto.Schema] Fix parameter ordering in assoc `:where`
v3.0.5 (2018-12-08)
--------------------
### Backwards incompatible changes
* [Ecto.Schema] The `:where` option added in Ecto 3.0.0 had a major flaw and it has been reworked in this version. This means a tuple of three elements can no longer be passed to `:where`, instead a keyword list must be given. Check the "Filtering associations" section in `has_many/3` docs for more information
### Bug fixes
* [Ecto.Query] Do not raise on lists of tuples that are not keywords. Instead, let custom Ecto.Type handle them
* [Ecto.Query] Allow `prefix: nil` to be given to subqueries
* [Ecto.Query] Use different cache keys for unions/intersections/excepts
* [Ecto.Repo] Fix support for upserts with `:replace` without a schema
* [Ecto.Type] Do not lose precision when casting `utc_datetime_usec` with a time zone different than Etc/UTC
v3.0.4 (2018-11-29)
--------------------
### Enhancements
* [Decimal] Bump decimal dependency
* [Ecto.Repo] Remove unused `:pool_timeout`
v3.0.3 (2018-11-20)
--------------------
### Enhancements
* [Ecto.Changeset] Add `count: :bytes` option in `validate_length/3`
* [Ecto.Query] Support passing [`Ecto.Query`](ecto.query) in `Ecto.Repo.insert_all`
### Bug fixes
* [Ecto.Type] Respect adapter types when loading/dumping arrays and maps
* [Ecto.Query] Ensure no bindings in order\_by when using combinations in [`Ecto.Query`](ecto.query)
* [Ecto.Repo] Ensure adapter is compiled (instead of only loaded) before invoking it
* [Ecto.Repo] Support new style child spec from adapters
v3.0.2 (2018-11-17)
--------------------
### Bug fixes
* [Ecto.LogEntry] Bring old Ecto.LogEntry APIs back for compatibility
* [Ecto.Repo] Consider non-joined fields when merging preloaded assocs only at root
* [Ecto.Repo] Take field sources into account in :replace\_all\_fields upsert option
* [Ecto.Type] Convert `:utc_datetime` to [`DateTime`](https://hexdocs.pm/elixir/DateTime.html) when sending it to adapters
v3.0.1 (2018-11-03)
--------------------
### Bug fixes
* [Ecto.Query] Ensure parameter order is preserved when using more than 32 parameters
* [Ecto.Query] Consider query prefix when planning association joins
* [Ecto.Repo] Consider non-joined fields as unique parameters when merging preloaded query assocs
v3.0.0 (2018-10-29)
--------------------
Note this version includes changes from `ecto` and `ecto_sql` but in future releases all `ecto_sql` entries will be listed in their own CHANGELOG.
### Enhancements
* [Ecto.Adapters.MySQL] Add ability to specify cli\_protocol for `ecto.create` and `ecto.drop` commands
* [Ecto.Adapters.PostgreSQL] Add ability to specify maintenance database name for PostgreSQL adapter for `ecto.create` and `ecto.drop` commands
* [Ecto.Changeset] Store constraint name in error metadata for constraints
* [Ecto.Changeset] Add `validations/1` and `constraints/1` instead of allowing direct access on the struct fields
* [Ecto.Changeset] Add `:force_update` option when casting relations, to force an update even if there are no changes
* [Ecto.Migration] Migrations now lock the migrations table in order to avoid concurrent migrations in a cluster. The type of lock can be configured via the `:migration_lock` repository configuration and defaults to "FOR UPDATE" or disabled if set to nil
* [Ecto.Migration] Add `:migration_default_prefix` repository configuration
* [Ecto.Migration] Add reversible version of `remove/2` subcommand
* [Ecto.Migration] Add support for non-empty arrays as defaults in migrations
* [Ecto.Migration] Add support for logging notices/alerts/warnings when running migrations (only supported by Postgres currently)
* [Ecto.Migrator] Warn when migrating and there is a higher version already migrated in the database
* [Ecto.Multi] Add support for anonymous functions in `insert/4`, `update/4`, `insert_or_update/4`, and `delete/4`
* [Ecto.Query] Support tuples in `where` and `having`, allowing queries such as `where: {p.foo, p.bar} > {^foo, ^bar}`
* [Ecto.Query] Support arithmetic operators in queries as a thin layer around the DB functionality
* [Ecto.Query] Allow joins in queries to be named via `:as` and allow named bindings
* [Ecto.Query] Support excluding specific join types in `exclude/2`
* [Ecto.Query] Allow virtual field update in subqueries
* [Ecto.Query] Support `coalesce/2` in queries, such as `select: coalesce(p.title, p.old_title)`
* [Ecto.Query] Support `filter/2` in queries, such as `select: filter(count(p.id), p.public == true)`
* [Ecto.Query] The `:prefix` and `:hints` options are now supported on both `from` and `join` expressions
* [Ecto.Query] Support `:asc_nulls_last`, `:asc_nulls_first`, `:desc_nulls_last`, and `:desc_nulls_first` in `order_by`
* [Ecto.Query] Allow variables (sources) to be given in queries, for example, useful for invoking functions, such as `fragment("some_function(?)", p)`
* [Ecto.Query] Add support for `union`, `union_all`, `intersection`, `intersection_all`, `except` and `except_all`
* [Ecto.Query] Add support for `windows` and `over`
* [Ecto.Query] Raise when comparing a string with a charlist during planning
* [Ecto.Repo] Only start transactions if an association or embed has changed, this reduces the overhead during repository operations
* [Ecto.Repo] Support `:replace_all_except_primary_key` as `:on_conflict` strategy
* [Ecto.Repo] Support `{:replace, fields}` as `:on_conflict` strategy
* [Ecto.Repo] Support `:unsafe_fragment` as `:conflict_target`
* [Ecto.Repo] Support `select` in queries given to `update_all` and `delete_all`
* [Ecto.Repo] Add `Repo.exists?/2`
* [Ecto.Repo] Add `Repo.checkout/2` - useful when performing multiple operations in short-time to interval, allowing the pool to be bypassed
* [Ecto.Repo] Add `:stale_error_field` to `Repo.insert/update/delete` that converts [`Ecto.StaleEntryError`](ecto.staleentryerror) into a changeset error. The message can also be set with `:stale_error_message`
* [Ecto.Repo] Preloading now only sorts results by the relationship key instead of sorting by the whole struct
* [Ecto.Schema] Allow `:where` option to be given to `has_many`/`has_one`/`belongs_to`/`many_to_many`
### Bug fixes
* [Ecto.Inspect] Do not fail when inspecting query expressions which have a number of bindings more than bindings available
* [Ecto.Migration] Keep double underscores on autogenerated index names to be consistent with changesets
* [Ecto.Query] Fix [`Ecto.Query.API.map/2`](ecto.query.api#map/2) for single nil column with join
* [Ecto.Migration] Ensure `create_if_not_exists` is properly reversible
* [Ecto.Repo] Allow many\_to\_many associations to be preloaded via a function (before the behaviour was erratic)
* [Ecto.Schema] Make autogen ID loading work with custom type
* [Ecto.Schema] Make `updated_at` have the same value as `inserted_at`
* [Ecto.Schema] Ensure all fields are replaced with `on_conflict: :replace_all/:replace_all_except_primary_key` and not only the fields sent as changes
* [Ecto.Type] Return `:error` when casting NaN or infinite decimals
* [mix ecto.migrate] Properly run migrations after ECTO\_EDITOR changes
* [mix ecto.migrations] List migrated versions even if the migration file is deleted
* [mix ecto.load] The task now fails on SQL errors on Postgres
### Deprecations
Although Ecto 3.0 is a major bump version, the functionality below emits deprecation warnings to ease the migration process. The functionality below will be removed in future Ecto 3.1+ releases.
* [Ecto.Changeset] Passing a list of binaries to `cast/3` is deprecated, please pass a list of atoms instead
* [Ecto.Multi] [`Ecto.Multi.run/3`](ecto.multi#run/3) now receives the repo in which the transaction is executing as the first argument to functions, and the changes so far as the second argument
* [Ecto.Query] `join/5` now expects `on: expr` as last argument instead of simply `expr`. This was done in order to properly support the `:as`, `:hints` and `:prefix` options
* [Ecto.Repo] The `:returning` option for `update_all` and `delete_all` has been deprecated as those statements now support `select` clauses
* [Ecto.Repo] Passing `:adapter` via config is deprecated in favor of passing it on `use Ecto.Repo`
* [Ecto.Repo] The `:loggers` configuration is deprecated in favor of "Telemetry Events"
### Backwards incompatible changes
* [Ecto.DateTime] `Ecto.Date`, `Ecto.Time` and `Ecto.DateTime` were previously deprecated and have now been removed
* [Ecto.DataType] `Ecto.DataType` protocol has been removed
* [Ecto.Migration] Automatically inferred index names may differ in Ecto v3.0 for indexes on complex column names
* [Ecto.Multi] [`Ecto.Multi.run/5`](ecto.multi#run/5) now receives the repo in which the transaction is executing as the first argument to functions, and the changes so far as the second argument
* [Ecto.Query] A `join` no longer wraps `fragment` in parentheses. In some cases, such as common table expressions, you will have to explicitly wrap the fragment in parens.
* [Ecto.Repo] The `on_conflict: :replace_all` option now will also send fields with default values to the database. If you prefer the old behaviour that only sends the changes in the changeset, you can set it to `on_conflict: {:replace, Map.keys(changeset.changes)}` (this change is also listed as a bug fix)
* [Ecto.Repo] The repository operations are no longer called from association callbacks - this behaviour was not guaranteed in previous versions but we are listing as backwards incompatible changes to help with users relying on this behaviour
* [Ecto.Repo] `:pool_timeout` is no longer supported in favor of a new queue system described in `DBConnection.start_link/2` under "Queue config". For most users, configuring `:timeout` is enough, as it now includes both queue and query time
* [Ecto.Schema] `:time`, `:naive_datetime` and `:utc_datetime` no longer keep microseconds information. If you want to keep microseconds, use `:time_usec`, `:naive_datetime_usec`, `:utc_datetime_usec`
* [Ecto.Schema] The `@schema_prefix` option now only affects the `from`/`join` of where the schema is used and no longer the whole query
* [Ecto.Schema.Metadata] The `source` key no longer returns a tuple of the schema\_prefix and the table/collection name. It now returns just the table/collection string. You can now access the schema\_prefix via the `prefix` key.
* [Mix.Ecto] `Mix.Ecto.ensure_started/2` has been removed. However, in Ecto 2.2 the [`Mix.Ecto`](mix.ecto) module was not considered part of the public API and should not have been used but we are listing this for guidance.
### Adapter changes
* [Ecto.Adapter] Split [`Ecto.Adapter`](ecto.adapter) into [`Ecto.Adapter.Queryable`](ecto.adapter.queryable) and [`Ecto.Adapter.Schema`](ecto.adapter.schema) to provide more granular repository APIs
* [Ecto.Adapter] The `:sources` field in `query_meta` now contains three elements tuples with `{source, schema, prefix}` in order to support `from`/`join` prefixes (#2572)
* [Ecto.Adapter] The database types `time`, `utc_datetime` and `naive_datetime` should translate to types with seconds precision while the database types `time_usec`, `utc_datetime_usec` and `naive_datetime_usec` should have microseconds precision (#2291)
* [Ecto.Adapter] The `on_conflict` argument for `insert` and `insert_all` no longer receives a `{:replace_all, list(), atom()}` tuple. Instead, it receives a `{fields :: [atom()], list(), atom()}` where `fields` is a list of atoms of the fields to be replaced (#2181)
* [Ecto.Adapter] `insert`/`update`/`delete` now receive both `:source` and `:prefix` fields instead of a single `:source` field with both `source` and `prefix` in it (#2490)
* [Ecto.Adapter.Migration] A new `lock_for_migration/4` callback has been added. It is implemented by default by `Ecto.Adapters.SQL` (#2215)
* [Ecto.Adapter.Migration] The `execute_ddl` should now return `{:ok, []}` to make space for returning notices/hints/warnings in the future (adapters leveraging `Ecto.Adapters.SQL` do not have to perform any change)
* [Ecto.Query] The `from` field in [`Ecto.Query`](ecto.query) now returns a `Ecto.Query.FromExpr` with the `:source` field, unifying the behaviour in `from` and `join` expressions (#2497)
* [Ecto.Query] Tuple expressions are now supported in queries. For example, `where: {p.foo, p.bar} > {p.bar, p.baz}` should translate to `WHERE (p.foo, p.bar) > (p.bar, p.baz)` in SQL databases. Adapters should be changed to handle `{:{}, meta, exprs}` in the query AST (#2344)
* [Ecto.Query] Adapters should support the following arithmetic operators in queries `+`, `-`, `*` and `/` (#2400)
* [Ecto.Query] Adapters should support `filter/2` in queries, as in `select: filter(count(p.id), p.public == true)` (#2487)
Previous versions
------------------
* See the CHANGELOG.md [in the v2.2 branch](https://github.com/elixir-ecto/ecto/blob/v2.2/CHANGELOG.md)
[← Previous Page API Reference](api-reference) [Next Page → Getting Started](getting-started)
| programming_docs |
phoenix Ecto.SubQuery Ecto.SubQuery
==============
A struct representing subqueries.
See [`Ecto.Query.subquery/2`](ecto.query#subquery/2) for more information.
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L9)
```
@type t() :: %Ecto.SubQuery{
cache: term(),
params: term(),
query: term(),
select: term()
}
```
phoenix Self-referencing many to many Self-referencing many to many
==============================
[`Ecto.Schema.many_to_many/3`](ecto.schema#many_to_many/3) is used to establish the association between two schemas with a join table (or a join schema) tracking the relationship between them. But, what if we want the same table to reference itself? This is commonly used for symmetric relationships and is often referred to as a self-referencing `many_to_many` association.
People relationships
---------------------
Let's imagine we are building a system that supports a model for relationships between people.
```
defmodule MyApp.Accounts.Person do
use Ecto.Schema
alias MyApp.Accounts.Person
alias MyApp.Relationships.Relationship
schema "people" do
field :name, :string
many_to_many :relationships,
Person,
join_through: Relationship,
join_keys: [person_id: :id, relation_id: :id]
many_to_many :reverse_relationships,
Person,
join_through: Relationship,
join_keys: [relation_id: :id, person_id: :id]
timestamps()
end
end
defmodule MyApp.Relationships.Relationship do
use Ecto.Schema
schema "relationships" do
field :person_id, :id
field :relation_id, :id
timestamps()
end
end
```
In our example, we implement an intermediate schema, `MyApp.Relationships.Relationship`, on our `:join_through` option and pass in a pair of ids that we will be creating a unique index on in our database migration. By implementing an intermediate schema, we make it easy to add additional attributes and functionality to relationships in the future.
We had to create an additional `many_to_many` `:reverse_relationships` call with an inverse of the `:join_keys` in order to finish the other half of the association. This ensures that both sides of the relationship will get added in the database when either side completes a successful relationship request.
The person who is the inverse of the relationship will have the relationship struct stored in a list under the "reverse\_relationships" key. We can then construct queries for both `:relationships` and `:reverse_relationships` with the proper `:preload`:
```
iex> preloads = [:relationships, :reverse_relationships]
iex> people = Repo.all from p in Person, preload: preloads
[
MyApp.Accounts.Person<
...
relationships: [
MyApp.Accounts.Person<
id: ...,
...
>
]
>,
MyApp.Accounts.Person<
...
reverse_relationships: [
MyApp.Accounts.Person<
id: ...,
...
>
]
>
]
```
In the example query above, we are assuming that we have two "people" that have entered into a relationship. Our query illustrates how one person is added on the `:relationships` side and the other on the `:reverse_relationships` side.
It is also worth noticing that we are implementing separate parent modules for both our `Person` and `Relationship` modules. This separation of concerns helps improve code organization and maintainability by allowing us to isolate core functions for relationships in the `MyApp.Relationships` context and vice-versa.
Let's take a look at our Ecto migration:
```
def change do
create table(:relationships) do
add :person_id, references(:people)
add :relation_id, references(:people)
timestamps()
end
create index(:relationships, [:person_id])
create index(:relationships, [:relation_id])
create unique_index(
:relationships,
[:person_id, :relation_id],
name: :relationships_person_id_relation_id_index
)
create unique_index(
:relationships,
[:relation_id, :person_id],
name: :relationships_relation_id_person_id_index
)
end
```
We create indexes on both the `:person_id` and `:relation_id` for quicker access in the future. Then, we create one unique index on the `:relationships` and another unique index on the inverse of `:relationships` to ensure that people cannot have duplicate relationships. Lastly, we pass a name to the `:name` option to help clarify the unique constraint when working with our changeset.
```
# In MyApp.Relationships.Relationship
@attrs [:person_id, :relation_id]
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, @attrs)
|> Ecto.Changeset.unique_constraint(
[:person_id, :relation_id],
name: :relationships_person_id_relation_id_index
)
|> Ecto.Changeset.unique_constraint(
[:relation_id, :person_id],
name: :relationships_relation_id_person_id_index
)
end
```
Due to the self-referential nature, we will only need to cast the `:join_keys` in order for Ecto to correctly associate the two records in the database. When considering production applications, we will most likely want to add additional attributes and validations. This is where our isolation of modules will help us maintain and organize the increasing complexity.
Summary
--------
In this guide we used `many_to_many` associations to implement a self-referencing symmetric relationship.
Our goal was to allow "people" to associate to different "people". Further, we wanted to lay a strong foundation for code organization and maintainability into the future. We have done this by creating intermediate tables, two separate functional core modules, a clear naming strategy, an inverse association, and by using `many_to_many` `:join_keys` to automatically manage those join tables.
Overall, our code contains a small structural modification, when compared with a typical `many_to_many`, in order to implement an inverse join between our self-referenced table and schema.
Where we go from here will depend greatly on the specific needs of our application. If we remember to adhere to our clear naming strategy with a strong separation of concerns, we will go a long way in keeping our self-referencing `many_to_many` association organized and easier to maintain.
[← Previous Page Multi tenancy with foreign keys](multi-tenancy-with-foreign-keys) [Next Page → Polymorphic associations with many to many](polymorphic-associations-with-many-to-many)
phoenix Ecto.Schema.Metadata Ecto.Schema.Metadata
=====================
Stores metadata of a struct.
State
------
The state of the schema is stored in the `:state` field and allows following values:
* `:built` - the struct was constructed in memory and is not persisted to database yet;
* `:loaded` - the struct was loaded from database and represents persisted data;
* `:deleted` - the struct was deleted and no longer represents persisted data.
Source
-------
The `:source` tracks the (table or collection) where the struct is or should be persisted to.
Prefix
-------
Tracks the source prefix in the data storage.
Context
--------
The `:context` field represents additional state some databases require for proper updates of data. It is not used by the built-in adapters of `Ecto.Adapters.Postgres` and `Ecto.Adapters.MySQL`.
Schema
-------
The `:schema` field refers the module name for the schema this metadata belongs to.
Summary
========
Types
------
[context()](#t:context/0) [state()](#t:state/0) [t()](#t:t/0) [t(schema)](#t:t/1) Types
======
### context()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema/metadata.ex#L40)
```
@type context() :: any()
```
### state()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema/metadata.ex#L38)
```
@type state() :: :built | :loaded | :deleted
```
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema/metadata.ex#L50)
```
@type t() :: t(module())
```
### t(schema)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema/metadata.ex#L42)
```
@type t(schema) :: %Ecto.Schema.Metadata{
context: context(),
prefix: Ecto.Schema.prefix(),
schema: schema,
source: Ecto.Schema.source(),
state: state()
}
```
phoenix Ecto.Adapter.Transaction behaviour Ecto.Adapter.Transaction behaviour
===================================
Specifies the adapter transactions API.
Summary
========
Types
------
[adapter\_meta()](#t:adapter_meta/0) Callbacks
----------
[in\_transaction?(adapter\_meta)](#c:in_transaction?/1) Returns true if the given process is inside a transaction.
[rollback(adapter\_meta, value)](#c:rollback/2) Rolls back the current transaction.
[transaction(adapter\_meta, options, function)](#c:transaction/3) Runs the given function inside a transaction.
Types
======
### adapter\_meta()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/transaction.ex#L6)
```
@type adapter_meta() :: Ecto.Adapter.adapter_meta()
```
Callbacks
==========
### in\_transaction?(adapter\_meta)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/transaction.ex#L21)
```
@callback in_transaction?(adapter_meta()) :: boolean()
```
Returns true if the given process is inside a transaction.
### rollback(adapter\_meta, value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/transaction.ex#L30)
```
@callback rollback(adapter_meta(), value :: any()) :: no_return()
```
Rolls back the current transaction.
The transaction will return the value given as `{:error, value}`.
See [`Ecto.Repo.rollback/1`](ecto.repo#c:rollback/1).
### transaction(adapter\_meta, options, function)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/transaction.ex#L15)
```
@callback transaction(adapter_meta(), options :: Keyword.t(), function :: (... -> any())) ::
{:ok, any()} | {:error, any()}
```
Runs the given function inside a transaction.
Returns `{:ok, value}` if the transaction was successful where `value` is the value return by the function or `{:error, value}` if the transaction was rolled back where `value` is the value given to `rollback/1`.
phoenix Mix.Ecto Mix.Ecto
=========
Conveniences for writing Ecto related Mix tasks.
Summary
========
Functions
----------
[ensure\_implements(module, behaviour, message)](#ensure_implements/3) Returns `true` if module implements behaviour.
[ensure\_repo(repo, args)](#ensure_repo/2) Ensures the given module is an Ecto.Repo.
[no\_umbrella!(task)](#no_umbrella!/1) Gets a path relative to the application path.
[open?(file, line \\ 1)](#open?/2) Asks if the user wants to open a file based on ECTO\_EDITOR.
[parse\_repo(args)](#parse_repo/1) Parses the repository option from the given command line args list.
Functions
==========
### ensure\_implements(module, behaviour, message)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/mix/ecto.ex#L150)
Returns `true` if module implements behaviour.
### ensure\_repo(repo, args)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/mix/ecto.ex#L64)
```
@spec ensure_repo(module(), list()) :: Ecto.Repo.t()
```
Ensures the given module is an Ecto.Repo.
### no\_umbrella!(task)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/mix/ecto.ex#L140)
Gets a path relative to the application path.
Raises on umbrella application.
### open?(file, line \\ 1)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/mix/ecto.ex#L115)
```
@spec open?(binary(), non_neg_integer()) :: boolean()
```
Asks if the user wants to open a file based on ECTO\_EDITOR.
By default, it attempts to open the file and line using the `file:line` notation. For example, if your editor is called `subl`, it will open the file as:
```
subl path/to/file:line
```
It is important that you choose an editor command that does not block nor that attempts to run an editor directly in the terminal. Command-line based editors likely need extra configuration so they open up the given file and line in a separate window.
Custom editors are supported by using the `__FILE__` and `__LINE__` notations, for example:
```
ECTO_EDITOR="my_editor +__LINE__ __FILE__"
```
and Elixir will properly interpolate values.
### parse\_repo(args)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/mix/ecto.ex#L12)
```
@spec parse_repo([term()]) :: [Ecto.Repo.t()]
```
Parses the repository option from the given command line args list.
If no repo option is given, it is retrieved from the application environment.
phoenix Composable transactions with Multi Composable transactions with Multi
===================================
Ecto relies on database transactions when multiple operations must be performed atomically. The most common example used for transactions are bank transfers between two people:
```
Repo.transaction(fn ->
mary_update =
from Account,
where: [id: ^mary.id],
update: [inc: [balance: +10]]
{1, _} = Repo.update_all(mary_update)
john_update =
from Account,
where: [id: ^john.id],
update: [inc: [balance: -10]]
{1, _} = Repo.update_all(john_update)
end)
```
In Ecto, transactions can be performed via the `Repo.transaction` function. When we expect both operations to succeed, as above, transactions are quite straight-forward. However, transactions get more complicated if we need to check the status of each operation along the way:
```
Repo.transaction(fn ->
mary_update =
from Account,
where: [id: ^mary.id],
update: [inc: [balance: +10]]
case Repo.update_all mary_update do
{1, _} ->
john_update =
from Account,
where: [id: ^john.id],
update: [inc: [balance: -10]]
case Repo.update_all john_update do
{1, _} -> {mary, john}
{_, _} -> Repo.rollback({:failed_transfer, john})
end
{_, _} ->
Repo.rollback({:failed_transfer, mary})
end
end)
```
Transactions in Ecto can also be nested arbitrarily. For example, imagine the transaction above is moved into its own function that receives both accounts, defined as `transfer_money(mary, john, 10)`, and besides transferring money we also want to log the transfer:
```
Repo.transaction(fn ->
case transfer_money(mary, john, 10) do
{:ok, {mary, john}} ->
transfer = %Transfer{
from: mary.id,
to: john.id,
amount: 10
}
Repo.insert!(transfer)
{:error, error} ->
Repo.rollback(error)
end
end)
```
The snippet above starts a transaction and then calls `transfer_money/3` that also runs in a transaction. In the case of multiple transactions, they are all flattened, which means a failure in an inner transaction causes the outer transaction to also fail. That's why matching and rolling back on `{:error, error}` is important.
While nesting transactions can improve the code readability by breaking large transactions into multiple smaller transactions, there is still a lot of boilerplate involved in handling the success and failure scenarios. Furthermore, composition is quite limited, as all operations must still be performed inside transaction blocks.
A more declarative approach when working with transactions would be to define all operations we want to perform in a transaction decoupled from the transaction execution. This way we would be able to compose transactions operations without worrying about its execution context or about each individual success/failure scenario. That's exactly what [`Ecto.Multi`](ecto.multi) allows us to do.
Composing with data structures
-------------------------------
Let's rewrite the snippets above using [`Ecto.Multi`](ecto.multi). The first snippet that transfers money between Mary and John can be rewritten to:
```
mary_update =
from Account,
where: [id: ^mary.id],
update: [inc: [balance: +10]]
john_update =
from Account,
where: [id: ^john.id],
update: [inc: [balance: -10]]
Ecto.Multi.new()
|> Ecto.Multi.update_all(:mary, mary_update)
|> Ecto.Multi.update_all(:john, john_update)
```
[`Ecto.Multi`](ecto.multi) is a data structure that defines multiple operations that must be performed together, without worrying about when they will be executed. [`Ecto.Multi`](ecto.multi) mirrors most of the [`Ecto.Repo`](ecto.repo) API, with the difference that each operation must be explicitly named. In the example above, we have defined two update operations, named `:mary` and `:john`. As we will see later, the names are important when handling the transaction results.
Since [`Ecto.Multi`](ecto.multi) is just a data structure, we can pass it as argument to other functions, as well as return it. Assuming the multi above is moved into its own function, defined as `transfer_money(mary, john, value)`, we can add a new operation to the multi that logs the transfer as follows:
```
transfer = %Transfer{
from: mary.id,
to: john.id,
amount: 10
}
transfer_money(mary, john, 10)
|> Ecto.Multi.insert(:transfer, transfer)
```
This is considerably simpler than the nested transaction approach we have seen earlier. Once all operations are defined in the multi, we can finally call `Repo.transaction`, this time passing the multi:
```
transfer = %Transfer{
from: mary.id,
to: john.id,
amount: 10
}
transfer_money(mary, john, 10)
|> Ecto.Multi.insert(:transfer, transfer)
|> Repo.transaction()
|> case do
{:ok, %{transfer: transfer}} ->
# Handle success case
{:error, name, value, changes_so_far} ->
# Handle failure case
end
```
If all operations in the multi succeed, it returns `{:ok, map}` where the map contains the name of all operations as keys and their success value. If any operation in the multi fails, the transaction is rolled back and `Repo.transaction` returns `{:error, name, value, changes_so_far}`, where `name` is the name of the failed operation, `value` is the failure value and `changes_so_far` is a map of the previously successful multi operations that have been rolled back due to the failure.
In other words, [`Ecto.Multi`](ecto.multi) takes care of all the flow control boilerplate while decoupling the transaction definition from its execution, allowing us to compose operations as needed.
Dependent values
-----------------
Besides operations such as `insert`, `update` and `delete`, [`Ecto.Multi`](ecto.multi) also provides functions for handling more complex scenarios. For example, `prepend` and `append` can be used to merge multis together. And more generally, the functions [`Ecto.Multi.run/3`](ecto.multi#run/3) and [`Ecto.Multi.run/5`](ecto.multi#run/5) can be used to define any operation that depends on the results of a previous multi operation. In addition, [`Ecto.Multi`](ecto.multi) also gives us `put` and `inspect`, which allow us to dynamically update and inspect changes.
Let's study a more practical example. In [Constraints and Upserts](constraints-and-upserts), we want to modify a post while possibly giving it a list of tags as a string separated by commas. At the end of the guide, we present a solution that inserts any missing tag and then fetches all of them using only two queries:
```
defmodule MyApp.Post do
use Ecto.Schema
# Schema is the same
schema "posts" do
field :title
field :body
many_to_many :tags, MyApp.Tag,
join_through: "posts_tags",
on_replace: :delete
timestamps()
end
# Changeset is the same
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title, :body])
|> Ecto.Changeset.put_assoc(:tags, parse_tags(params))
end
# Parse tags has slightly changed
defp parse_tags(params) do
(params["tags"] || "")
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(& &1 == "")
|> insert_and_get_all()
end
defp insert_and_get_all([]) do
[]
end
defp insert_and_get_all(names) do
timestamp =
NaiveDateTime.utc_now()
|> NaiveDateTime.truncate(:second)
maps =
Enum.map(names, &%{
name: &1,
inserted_at: timestamp,
updated_at: timestamp
})
Repo.insert_all(MyApp.Tag, maps, on_conflict: :nothing)
Repo.all(from t in MyApp.Tag, where: t.name in ^names)
end
end
```
While `insert_and_get_all/1` is idempotent, allowing us to run it multiple times and get the same result back, it does not run inside a transaction, so any failure while attempting to modify the parent post struct would end-up creating tags that have no posts associated to them.
Let's fix the problem above by introducing using [`Ecto.Multi`](ecto.multi). Let's start by splitting the logic into both `Post` and `Tag` modules and keeping it free from side-effects such as database operations:
```
defmodule MyApp.Post do
use Ecto.Schema
schema "posts" do
field :title
field :body
many_to_many :tags, MyApp.Tag,
join_through: "posts_tags",
on_replace: :delete
timestamps()
end
def changeset(struct, tags, params) do
struct
|> Ecto.Changeset.cast(params, [:title, :body])
|> Ecto.Changeset.put_assoc(:tags, tags)
end
end
defmodule MyApp.Tag do
use Ecto.Schema
schema "tags" do
field :name
timestamps()
end
def parse(tags) do
(tags || "")
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(& &1 == "")
end
end
```
Now, whenever we need to introduce a post with tags, we can create a multi that wraps all operations and the repository access:
```
alias MyApp.Tag
def insert_or_update_post_with_tags(post, params) do
Ecto.Multi.new()
|> Ecto.Multi.run(:tags, fn _repo, changes ->
insert_and_get_all_tags(changes, params)
end)
|> Ecto.Multi.run(:post, fn _repo, changes ->
insert_or_update_post(changes, post, params)
end)
|> Repo.transaction()
end
defp insert_and_get_all_tags(_changes, params) do
case MyApp.Tag.parse(params["tags"]) do
[] ->
{:ok, []}
names ->
timestamp =
NaiveDateTime.utc_now()
|> NaiveDateTime.truncate(:second)
maps =
Enum.map(names, &%{
name: &1,
inserted_at: timestamp,
updated_at: timestamp
})
Repo.insert_all(Tag, maps, on_conflict: :nothing)
query = from t in Tag, where: t.name in ^names
{:ok, Repo.all(query)}
end
end
defp insert_or_update_post(%{tags: tags}, post, params) do
post
|> MyApp.Post.changeset(tags, params)
|> Repo.insert_or_update()
end
```
In the example above we have used [`Ecto.Multi.run/3`](ecto.multi#run/3) twice, albeit for two different reasons.
1. In `Ecto.Multi.run(:tags, ...)`, we used `run/3` because we need to perform both `insert_all` and `all` operations, and while the multi exposes [`Ecto.Multi.insert_all/4`](ecto.multi#insert_all/4), it does not have an equivalent to `Ecto.Repo.all`. Whenever we need to perform a repository operation that is not supported by [`Ecto.Multi`](ecto.multi), we can always fallback to `run/3` or `run/5`.
2. In `Ecto.Multi.run(:post, ...)`, we used `run/3` because we need to access the value of a previous multi operation. The function given to `run/3` receives, as second argument, a map with the results of the operations performed so far. To grab the tags returned in the previous step, we simply pattern match on `%{tags: tags}` on `insert_or_update_post`.
> Note: The first argument received by the function given to `run/3` is the repo in which the transaction is executing.
>
>
While `run/3` is very handy when we need to go beyond the functionalities provided natively by [`Ecto.Multi`](ecto.multi), it has the downside that operations defined with [`Ecto.Multi.run/3`](ecto.multi#run/3) are opaque and therefore they cannot be inspected by functions such as [`Ecto.Multi.to_list/1`](ecto.multi#to_list/1). Still, [`Ecto.Multi`](ecto.multi) allows us to greatly simplify control flow logic and remove boilerplate when working with transactions.
[← Previous Page Aggregates and subqueries](aggregates-and-subqueries) [Next Page → Constraints and Upserts](constraints-and-upserts)
| programming_docs |
phoenix Ecto.Multi Ecto.Multi
===========
[`Ecto.Multi`](ecto.multi#content) is a data structure for grouping multiple Repo operations.
[`Ecto.Multi`](ecto.multi#content) makes it possible to pack operations that should be performed in a single database transaction and gives a way to introspect the queued operations without actually performing them. Each operation is given a name that is unique and will identify its result in case of success or failure.
If a multi is valid (i.e. all the changesets in it are valid), all operations will be executed in the order they were added.
The [`Ecto.Multi`](ecto.multi#content) structure should be considered opaque. You can use `%Ecto.Multi{}` to pattern match the type, but accessing fields or directly modifying them is not advised.
[`Ecto.Multi.to_list/1`](#to_list/1) returns a canonical representation of the structure that can be used for introspection.
Changesets
-----------
If multi contains operations that accept changesets (like [`insert/4`](#insert/4), [`update/4`](#update/4) or [`delete/4`](#delete/4)) they will be checked before starting the transaction. If any changeset has errors, the transaction won't even be started and the error will be immediately returned.
Note: [`insert/4`](#insert/4), [`update/4`](#update/4), [`insert_or_update/4`](#insert_or_update/4), and [`delete/4`](#delete/4) variants that accept a function are not performing such checks since the functions are executed after the transaction has started.
Run
----
Multi allows you to run arbitrary functions as part of your transaction via [`run/3`](#run/3) and [`run/5`](#run/5). This is especially useful when an operation depends on the value of a previous operation. For this reason, the function given as a callback to [`run/3`](#run/3) and [`run/5`](#run/5) will receive the repo as the first argument, and all changes performed by the multi so far as a map for the second argument.
The function given to `run` must return `{:ok, value}` or `{:error, value}` as its result. Returning an error will abort any further operations and make the whole multi fail.
Example
--------
Let's look at an example definition and usage. The use case we'll be looking into is resetting a password. We need to update the account with proper information, log the request and remove all current sessions:
```
defmodule PasswordManager do
alias Ecto.Multi
def reset(account, params) do
Multi.new()
|> Multi.update(:account, Account.password_reset_changeset(account, params))
|> Multi.insert(:log, Log.password_reset_changeset(account, params))
|> Multi.delete_all(:sessions, Ecto.assoc(account, :sessions))
end
end
```
We can later execute it in the integration layer using Repo:
```
Repo.transaction(PasswordManager.reset(account, params))
```
By pattern matching on the result we can differentiate different conditions:
```
case result do
{:ok, %{account: account, log: log, sessions: sessions}} ->
# Operation was successful, we can access results (exactly the same
# we would get from running corresponding Repo functions) under keys
# we used for naming the operations.
{:error, failed_operation, failed_value, changes_so_far} ->
# One of the operations failed. We can access the operation's failure
# value (like changeset for operations on changesets) to prepare a
# proper response. We also get access to the results of any operations
# that succeeded before the indicated operation failed. However, any
# successful operations would have been rolled back.
end
```
We can also easily unit test our transaction without actually running it. Since changesets can use in-memory-data, we can use an account that is constructed in memory as well (without persisting it to the database):
```
test "dry run password reset" do
account = %Account{password: "letmein"}
multi = PasswordManager.reset(account, params)
assert [
{:account, {:update, account_changeset, []}},
{:log, {:insert, log_changeset, []}},
{:sessions, {:delete_all, query, []}}
] = Ecto.Multi.to_list(multi)
# We can introspect changesets and query to see if everything
# is as expected, for example:
assert account_changeset.valid?
assert log_changeset.valid?
assert inspect(query) == "#Ecto.Query<from a in Session>"
end
```
The name of each operation does not have to be an atom. This can be particularly useful when you wish to update a collection of changesets at once, and track their errors individually:
```
accounts = [%Account{id: 1}, %Account{id: 2}]
Enum.reduce(accounts, Multi.new(), fn account, multi ->
Multi.update(
multi,
{:account, account.id},
Account.password_reset_changeset(account, params)
)
end)
```
Summary
========
Types
------
[changes()](#t:changes/0) [fun(result)](#t:fun/1) [merge()](#t:merge/0) [name()](#t:name/0) [run()](#t:run/0) [t()](#t:t/0) Functions
----------
[all(multi, name, queryable\_or\_fun, opts \\ [])](#all/4) Runs a query and stores all entries in the multi.
[append(lhs, rhs)](#append/2) Appends the second multi to the first one.
[delete(multi, name, changeset\_or\_struct\_fun, opts \\ [])](#delete/4) Adds a delete operation to the multi.
[delete\_all(multi, name, queryable\_or\_fun, opts \\ [])](#delete_all/4) Adds a delete\_all operation to the multi.
[error(multi, name, value)](#error/3) Causes the multi to fail with the given value.
[insert(multi, name, changeset\_or\_struct\_or\_fun, opts \\ [])](#insert/4) Adds an insert operation to the multi.
[insert\_all(multi, name, schema\_or\_source, entries\_or\_query\_or\_fun, opts \\ [])](#insert_all/5) Adds an insert\_all operation to the multi.
[insert\_or\_update(multi, name, changeset\_or\_fun, opts \\ [])](#insert_or_update/4) Inserts or updates a changeset depending on whether the changeset was persisted or not.
[inspect(multi, opts \\ [])](#inspect/2) Inspects results from a Multi
[merge(multi, merge)](#merge/2) Merges a multi returned dynamically by an anonymous function.
[merge(multi, mod, fun, args)](#merge/4) Merges a multi returned dynamically by calling `module` and `function` with `args`.
[new()](#new/0) Returns an empty [`Ecto.Multi`](ecto.multi#content) struct.
[one(multi, name, queryable\_or\_fun, opts \\ [])](#one/4) Runs a query expecting one result and stores it in the multi.
[prepend(lhs, rhs)](#prepend/2) Prepends the second multi to the first one.
[put(multi, name, value)](#put/3) Adds a value to the changes so far under the given name.
[run(multi, name, run)](#run/3) Adds a function to run as part of the multi.
[run(multi, name, mod, fun, args)](#run/5) Adds a function to run as part of the multi.
[to\_list(multi)](#to_list/1) Returns the list of operations stored in `multi`.
[update(multi, name, changeset\_or\_fun, opts \\ [])](#update/4) Adds an update operation to the multi.
[update\_all(multi, name, queryable\_or\_fun, updates, opts \\ [])](#update_all/5) Adds an update\_all operation to the multi.
Types
======
### changes()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L122)
```
@type changes() :: map()
```
### fun(result)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L124)
```
@type fun(result) :: (changes() -> result)
```
### merge()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L125)
```
@type merge() :: (changes() -> t()) | {module(), atom(), [any()]}
```
### name()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L137)
```
@type name() :: any()
```
### run()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L123)
```
@type run() ::
(Ecto.Repo.t(), changes() -> {:ok | :error, any()})
| {module(), atom(), [any()]}
```
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L138)
```
@type t() :: %Ecto.Multi{names: names(), operations: operations()}
```
Functions
==========
### all(multi, name, queryable\_or\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L444)
```
@spec all(
t(),
name(),
queryable :: Ecto.Queryable.t() | (any() -> Ecto.Queryable.t()),
opts :: Keyword.t()
) :: t()
```
Runs a query and stores all entries in the multi.
Accepts the same arguments and options as [`Ecto.Repo.all/2`](ecto.repo#c:all/2) does.
#### Example
```
Ecto.Multi.new()
|> Ecto.Multi.all(:all, Post)
|> MyApp.Repo.transaction()
```
### append(lhs, rhs)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L168)
```
@spec append(t(), t()) :: t()
```
Appends the second multi to the first one.
All names must be unique between both structures.
#### Example
```
iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end)
iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end)
iex> Ecto.Multi.append(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
[:left, :right]
```
### delete(multi, name, changeset\_or\_struct\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L386)
```
@spec delete(
t(),
name(),
Ecto.Changeset.t()
| Ecto.Schema.t()
| fun(Ecto.Changeset.t() | Ecto.Schema.t()),
Keyword.t()
) :: t()
```
Adds a delete operation to the multi.
Accepts the same arguments and options as [`Ecto.Repo.delete/2`](ecto.repo#c:delete/2) does.
#### Example
```
post = MyApp.Repo.get!(Post, 1)
Ecto.Multi.new()
|> Ecto.Multi.delete(:delete, post)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.delete(:delete, fn %{post: post} ->
# Others validations
post
end)
|> MyApp.Repo.transaction()
```
### delete\_all(multi, name, queryable\_or\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L629)
```
@spec delete_all(
t(),
name(),
Ecto.Queryable.t() | fun(Ecto.Queryable.t()),
Keyword.t()
) :: t()
```
Adds a delete\_all operation to the multi.
Accepts the same arguments and options as [`Ecto.Repo.delete_all/2`](ecto.repo#c:delete_all/2) does.
#### Example
```
queryable = from(p in Post, where: p.id < 5)
Ecto.Multi.new()
|> Ecto.Multi.delete_all(:delete_all, queryable)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.delete_all(:delete_all, fn %{post: post} ->
# Others validations
from(c in Comment, where: c.post_id == ^post.id)
end)
|> MyApp.Repo.transaction()
```
### error(multi, name, value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L479)
```
@spec error(t(), name(), error :: term()) :: t()
```
Causes the multi to fail with the given value.
Running the multi in a transaction will execute no previous steps and returns the value of the first error added.
### insert(multi, name, changeset\_or\_struct\_or\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L276)
```
@spec insert(
t(),
name(),
Ecto.Changeset.t()
| Ecto.Schema.t()
| fun(Ecto.Changeset.t() | Ecto.Schema.t()),
Keyword.t()
) :: t()
```
Adds an insert operation to the multi.
Accepts the same arguments and options as [`Ecto.Repo.insert/2`](ecto.repo#c:insert/2) does.
#### Example
```
Ecto.Multi.new()
|> Ecto.Multi.insert(:insert, %Post{title: "first"})
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.insert(:post, %Post{title: "first"})
|> Ecto.Multi.insert(:comment, fn %{post: post} ->
Ecto.build_assoc(post, :comments)
end)
|> MyApp.Repo.transaction()
```
### insert\_all(multi, name, schema\_or\_source, entries\_or\_query\_or\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L554)
```
@spec insert_all(
t(),
name(),
schema_or_source(),
entries_or_query_or_fun ::
[map() | Keyword.t()] | fun([map() | Keyword.t()]) | Ecto.Query.t(),
Keyword.t()
) :: t()
```
Adds an insert\_all operation to the multi.
Accepts the same arguments and options as [`Ecto.Repo.insert_all/3`](ecto.repo#c:insert_all/3) does.
#### Example
```
posts = [%{title: "My first post"}, %{title: "My second post"}]
Ecto.Multi.new()
|> Ecto.Multi.insert_all(:insert_all, Post, posts)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.insert_all(:insert_all, Comment, fn %{post: post} ->
# Others validations
entries
|> Enum.map(fn comment ->
Map.put(comment, :post_id, post.id)
end)
end)
|> MyApp.Repo.transaction()
```
### insert\_or\_update(multi, name, changeset\_or\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L345)
```
@spec insert_or_update(
t(),
name(),
Ecto.Changeset.t() | fun(Ecto.Changeset.t()),
Keyword.t()
) :: t()
```
Inserts or updates a changeset depending on whether the changeset was persisted or not.
Accepts the same arguments and options as [`Ecto.Repo.insert_or_update/2`](ecto.repo#c:insert_or_update/2) does.
#### Example
```
changeset = Post.changeset(%Post{}, %{title: "New title"})
Ecto.Multi.new()
|> Ecto.Multi.insert_or_update(:insert_or_update, changeset)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
{:ok, repo.get(Post, 1) || %Post{}}
end)
|> Ecto.Multi.insert_or_update(:update, fn %{post: post} ->
Ecto.Changeset.change(post, title: "New title")
end)
|> MyApp.Repo.transaction()
```
### inspect(multi, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L739)
```
@spec inspect(t(), Keyword.t()) :: t()
```
Inspects results from a Multi
By default, the name is shown as a label to the inspect, custom labels are supported through the [`IO.inspect/2`](https://hexdocs.pm/elixir/IO.html#inspect/2) `label` option.
#### Options
All options for IO.inspect/2 are supported, it also support the following ones:
* `:only` - A field or a list of fields to inspect, will print the entire map by default.
#### Examples
```
Ecto.Multi.new()
|> Ecto.Multi.insert(:person_a, changeset)
|> Ecto.Multi.insert(:person_b, changeset)
|> Ecto.Multi.inspect()
|> MyApp.Repo.transaction()
```
Prints:
```
%{person_a: %Person{...}, person_b: %Person{...}}
```
We can use the `:only` option to limit which fields will be printed:
```
Ecto.Multi.new()
|> Ecto.Multi.insert(:person_a, changeset)
|> Ecto.Multi.insert(:person_b, changeset)
|> Ecto.Multi.inspect(only: :person_a)
|> MyApp.Repo.transaction()
```
Prints:
```
%{person_a: %Person{...}}
```
### merge(multi, merge)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L237)
```
@spec merge(t(), (changes() -> t())) :: t()
```
Merges a multi returned dynamically by an anonymous function.
This function is useful when the multi to be merged requires information from the original multi. Hence the second argument is an anonymous function that receives the multi changes so far. The anonymous function must return another multi.
If you would prefer to simply merge two multis together, see [`append/2`](#append/2) or [`prepend/2`](#prepend/2).
Duplicated operations are not allowed.
#### Example
```
multi =
Ecto.Multi.new()
|> Ecto.Multi.insert(:post, %Post{title: "first"})
multi
|> Ecto.Multi.merge(fn %{post: post} ->
Ecto.Multi.new()
|> Ecto.Multi.insert(:comment, Ecto.build_assoc(post, :comments))
end)
|> MyApp.Repo.transaction()
```
### merge(multi, mod, fun, args)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L251)
```
@spec merge(t(), module(), function, args) :: t() when function: atom(), args: [any()]
```
Merges a multi returned dynamically by calling `module` and `function` with `args`.
Similar to [`merge/2`](#merge/2), but allows to pass module name, function and arguments. The function should return an [`Ecto.Multi`](ecto.multi#content), and receives changes so far as the first argument (prepended to those passed in the call to the function).
Duplicated operations are not allowed.
### new()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L150)
```
@spec new() :: t()
```
Returns an empty [`Ecto.Multi`](ecto.multi#content) struct.
#### Example
```
iex> Ecto.Multi.new() |> Ecto.Multi.to_list()
[]
```
### one(multi, name, queryable\_or\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L417)
```
@spec one(
t(),
name(),
queryable :: Ecto.Queryable.t() | (any() -> Ecto.Queryable.t()),
opts :: Keyword.t()
) :: t()
```
Runs a query expecting one result and stores it in the multi.
Accepts the same arguments and options as [`Ecto.Repo.one/2`](ecto.repo#c:one/2).
#### Example
```
Ecto.Multi.new()
|> Ecto.Multi.one(:post, Post)
|> MyApp.Repo.transaction()
```
### prepend(lhs, rhs)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L186)
```
@spec prepend(t(), t()) :: t()
```
Prepends the second multi to the first one.
All names must be unique between both structures.
#### Example
```
iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end)
iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end)
iex> Ecto.Multi.prepend(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
[:right, :left]
```
### put(multi, name, value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L698)
```
@spec put(t(), name(), any()) :: t()
```
Adds a value to the changes so far under the given name.
The given `value` is added to the multi before the transaction starts. If you would like to run arbitrary functions as part of your transaction, see [`run/3`](#run/3) or [`run/5`](#run/5).
#### Example
Imagine there is an existing company schema that you retrieved from the database. You can insert it as a change in the multi using [`put/3`](#put/3):
```
Ecto.Multi.new()
|> Ecto.Multi.put(:company, company)
|> Ecto.Multi.insert(:user, fn changes -> User.changeset(changes.company) end)
|> Ecto.Multi.insert(:person, fn changes -> Person.changeset(changes.user, changes.company) end)
|> MyApp.Repo.transaction()
```
In the example above there isn't a large benefit in putting the `company` in the multi, because you could also access the `company` variable directly inside the anonymous function.
However, the benefit of [`put/3`](#put/3) is when composing [`Ecto.Multi`](ecto.multi#content)s. If the insert operations above were defined in another module, you could use `put(:company, company)` to inject changes that will be accessed by other functions down the chain, removing the need to pass both `multi` and `company` values around.
### run(multi, name, run)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L499)
```
@spec run(t(), name(), run()) :: t()
```
Adds a function to run as part of the multi.
The function should return either `{:ok, value}` or `{:error, value}`, and receives the repo as the first argument, and the changes so far as the second argument.
#### Example
```
Ecto.Multi.run(multi, :write, fn _repo, %{image: image} ->
with :ok <- File.write(image.name, image.contents) do
{:ok, nil}
end
end)
```
### run(multi, name, mod, fun, args)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L512)
```
@spec run(t(), name(), module(), function, args) :: t()
when function: atom(), args: [any()]
```
Adds a function to run as part of the multi.
Similar to [`run/3`](#run/3), but allows to pass module name, function and arguments. The function should return either `{:ok, value}` or `{:error, value}`, and receives the repo as the first argument, and the changes so far as the second argument (prepended to those passed in the call to the function).
### to\_list(multi)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L658)
```
@spec to_list(t()) :: [{name(), term()}]
```
Returns the list of operations stored in `multi`.
Always use this function when you need to access the operations you have defined in [`Ecto.Multi`](ecto.multi#content). Inspecting the [`Ecto.Multi`](ecto.multi#content) struct internals directly is discouraged.
### update(multi, name, changeset\_or\_fun, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L312)
```
@spec update(t(), name(), Ecto.Changeset.t() | fun(Ecto.Changeset.t()), Keyword.t()) ::
t()
```
Adds an update operation to the multi.
Accepts the same arguments and options as [`Ecto.Repo.update/2`](ecto.repo#c:update/2) does.
#### Example
```
post = MyApp.Repo.get!(Post, 1)
changeset = Ecto.Changeset.change(post, title: "New title")
Ecto.Multi.new()
|> Ecto.Multi.update(:update, changeset)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.insert(:post, %Post{title: "first"})
|> Ecto.Multi.update(:fun, fn %{post: post} ->
Ecto.Changeset.change(post, title: "New title")
end)
|> MyApp.Repo.transaction()
```
### update\_all(multi, name, queryable\_or\_fun, updates, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/multi.ex#L591)
```
@spec update_all(
t(),
name(),
Ecto.Queryable.t() | fun(Ecto.Queryable.t()),
Keyword.t(),
Keyword.t()
) ::
t()
```
Adds an update\_all operation to the multi.
Accepts the same arguments and options as [`Ecto.Repo.update_all/3`](ecto.repo#c:update_all/3) does.
#### Example
```
Ecto.Multi.new()
|> Ecto.Multi.update_all(:update_all, Post, set: [title: "New title"])
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.update_all(:update_all, fn %{post: post} ->
# Others validations
from(c in Comment, where: c.post_id == ^post.id, update: [set: [title: "New title"]])
end, [])
|> MyApp.Repo.transaction()
```
| programming_docs |
phoenix Ecto.SubQueryError exception Ecto.SubQueryError exception
=============================
Raised at runtime when a subquery is invalid.
phoenix Aggregates and subqueries Aggregates and subqueries
==========================
Now it's time to discuss aggregates and subqueries. As we will learn, one builds directly on the other.
Aggregates
-----------
Ecto includes a convenience function in repositories to calculate aggregates.
For example, if we assume every post has an integer column named visits, we can find the average number of visits across all posts with:
```
MyApp.Repo.aggregate(MyApp.Post, :avg, :visits)
#=> #Decimal<1743>
```
Behind the scenes, the query above translates to:
```
MyApp.Repo.one(from p in MyApp.Post, select: avg(p.visits))
```
The [`Ecto.Repo.aggregate/4`](ecto.repo#c:aggregate/4) function supports any of the aggregate operations listed in the [`Ecto.Query.API`](ecto.query.api) module.
At first, it looks like the implementation of `aggregate/4` is quite straight-forward. You could even start to wonder why it was added to Ecto in the first place. However, complexities start to arise on queries that rely on `limit`, `offset` or `distinct` clauses.
Imagine that instead of calculating the average of all posts, you want the average of only the top 10. Your first try may be:
```
MyApp.Repo.one(
from p in MyApp.Post,
order_by: [desc: :visits],
limit: 10,
select: avg(p.visits)
)
#=> #Decimal<1743>
```
Oops. The query above returned the same value as the queries before. The option `limit: 10` has no effect here since it is limiting the aggregated result and queries with aggregates return only a single row anyway. In order to retrieve the correct result, we would need to first find the top 10 posts and only then aggregate. That's exactly what `aggregate/4` does:
```
query =
from MyApp.Post,
order_by: [desc: :visits],
limit: 10
MyApp.Repo.aggregate(query, :avg, :visits)
#=> #Decimal<4682>
```
When `limit`, `offset` or `distinct` is specified in the query, `aggregate/4` automatically wraps the given query in a subquery. Therefore the query executed by `aggregate/4` above is rather equivalent to:
```
inner_query =
from MyApp.Post,
order_by: [desc: :visits],
limit: 10
query =
from q in subquery(inner_query),
select: avg(q.visits)
MyApp.Repo.one(query)
```
Let's take a closer look at subqueries.
Subqueries
-----------
In the previous section we have already learned some queries that would be hard to express without support for subqueries. That's one of many examples that caused subqueries to be added to Ecto.
Subqueries in Ecto are created by calling [`Ecto.Query.subquery/1`](ecto.query#subquery/1). This function receives any data structure that can be converted to a query, via the [`Ecto.Queryable`](ecto.queryable) protocol, and returns a subquery construct (which is also queryable).
In Ecto, it is allowed for a subquery to select a whole table (`p`) or a field (`p.field`). All fields selected in a subquery can be accessed from the parent query. Let's revisit the aggregate query we saw in the previous section:
```
inner_query =
from MyApp.Post,
order_by: [desc: :visits],
limit: 10
query =
from q in subquery(inner_query),
select: avg(q.visits)
MyApp.Repo.one(query)
```
Because the query does not specify a `:select` clause, it will return `select: p` where `p` is controlled by `MyApp.Post` schema. Since the query will return all fields in `MyApp.Post`, when we convert it to a subquery, all of the fields from `MyApp.Post` will be available on the parent query, such as `q.visits`. In fact, Ecto will keep the schema properties across queries. For example, if you write `q.field_that_does_not_exist`, your Ecto query won't compile.
Ecto also allows an Elixir map to be returned from a subquery, making the map keys directly available to the parent query.
Let's see one last example. Imagine you manage a library (as in an actual library in the real world) and there is a table that logs every time the library lends a book. The "lendings" table uses an auto-incrementing primary key and can be backed by the following schema:
```
defmodule Library.Lending do
use Ecto.Schema
schema "lendings" do
belongs_to :book, MyApp.Book # defines book_id
belongs_to :visitor, MyApp.Visitor # defines visitor_id
end
end
```
Now consider we want to retrieve the name of every book alongside the name of the last person the library has lent it to. To do so, we need to find the last lending ID of every book, and then join on the book and visitor tables. With subqueries, that's straight-forward:
```
last_lendings =
from l in MyApp.Lending,
group_by: l.book_id,
select: %{
book_id: l.book_id,
last_lending_id: max(l.id)
}
from l in Lending,
join: last in subquery(last_lendings),
on: last.last_lending_id == l.id,
join: b in assoc(l, :book),
join: v in assoc(l, :visitor),
select: {b.name, v.name}
```
[← Previous Page Testing with Ecto](testing-with-ecto) [Next Page → Composable transactions with Multi](composable-transactions-with-multi)
phoenix mix ecto.drop mix ecto.drop
==============
Drop the storage for the given repository.
The repositories to drop are the ones specified under the `:ecto_repos` option in the current app configuration. However, if the `-r` option is given, it replaces the `:ecto_repos` config.
Since Ecto tasks can only be executed once, if you need to drop multiple repositories, set `:ecto_repos` accordingly or pass the `-r` flag multiple times.
Examples
---------
```
$ mix ecto.drop
$ mix ecto.drop -r Custom.Repo
```
Command line options
---------------------
* `-r`, `--repo` - the repo to drop
* `-q`, `--quiet` - run the command quietly
* `-f`, `--force` - do not ask for confirmation when dropping the database. Configuration is asked only when `:start_permanent` is set to true (typically in production)
* `--force-drop` - force the database to be dropped even if it has connections to it (requires PostgreSQL 13+)
* `--no-compile` - do not compile before dropping
* `--no-deps-check` - do not compile before dropping
phoenix Ecto.UUID Ecto.UUID
==========
An Ecto type for UUID strings.
Summary
========
Types
------
[raw()](#t:raw/0) A raw binary representation of a UUID.
[t()](#t:t/0) A hex-encoded UUID string.
Functions
----------
[bingenerate()](#bingenerate/0) Generates a random, version 4 UUID in the binary format.
[cast!(value)](#cast!/1) Same as [`cast/1`](#cast/1) but raises [`Ecto.CastError`](ecto.casterror) on invalid arguments.
[cast(raw\_uuid)](#cast/1) Casts to a UUID.
[dump!(value)](#dump!/1) Same as [`dump/1`](#dump/1) but raises `Ecto.ArgumentError` on invalid arguments.
[dump(arg1)](#dump/1) Converts a string representing a UUID into a raw binary.
[embed\_as(\_)](#embed_as/1) Callback implementation for [`Ecto.Type.embed_as/1`](ecto.type#c:embed_as/1).
[equal?(term1, term2)](#equal?/2) Callback implementation for [`Ecto.Type.equal?/2`](ecto.type#c:equal?/2).
[generate()](#generate/0) Generates a random, version 4 UUID.
[load!(value)](#load!/1) Same as [`load/1`](#load/1) but raises `Ecto.ArgumentError` on invalid arguments.
[load(raw\_uuid)](#load/1) Converts a binary UUID into a string.
Types
======
### raw()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L16)
```
@type raw() :: <<_::128>>
```
A raw binary representation of a UUID.
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L11)
```
@type t() :: <<_::288>>
```
A hex-encoded UUID string.
Functions
==========
### bingenerate()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L180)
```
@spec bingenerate() :: raw()
```
Generates a random, version 4 UUID in the binary format.
### cast!(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L51)
```
@spec cast!(t() | raw() | any()) :: t()
```
Same as [`cast/1`](#cast/1) but raises [`Ecto.CastError`](ecto.casterror) on invalid arguments.
### cast(raw\_uuid)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L25)
```
@spec cast(t() | raw() | any()) :: {:ok, t()} | :error
```
Casts to a UUID.
### dump!(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L139)
```
@spec dump!(t() | any()) :: raw()
```
Same as [`dump/1`](#dump/1) but raises `Ecto.ArgumentError` on invalid arguments.
### dump(arg1)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L88)
```
@spec dump(t() | any()) :: {:ok, raw()} | :error
```
Converts a string representing a UUID into a raw binary.
### embed\_as(\_)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L6)
Callback implementation for [`Ecto.Type.embed_as/1`](ecto.type#c:embed_as/1).
### equal?(term1, term2)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L6)
Callback implementation for [`Ecto.Type.equal?/2`](ecto.type#c:equal?/2).
### generate()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L174)
```
@spec generate() :: t()
```
Generates a random, version 4 UUID.
### load!(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L163)
```
@spec load!(raw() | any()) :: t()
```
Same as [`load/1`](#load/1) but raises `Ecto.ArgumentError` on invalid arguments.
### load(raw\_uuid)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/uuid.ex#L150)
```
@spec load(raw() | any()) :: {:ok, t()} | :error
```
Converts a binary UUID into a string.
phoenix Ecto.Adapter.Queryable behaviour Ecto.Adapter.Queryable behaviour
=================================
Specifies the query API required from adapters.
If your adapter is only able to respond to one or a couple of the query functions, add custom implementations of those functions directly to the Repo by using [`Ecto.Adapter.__before_compile__/1`](ecto.adapter#c:__before_compile__/1) instead.
Summary
========
Types
------
[adapter\_meta()](#t:adapter_meta/0) Proxy type to the adapter meta
[cached()](#t:cached/0) [options()](#t:options/0) [prepared()](#t:prepared/0) [query\_cache()](#t:query_cache/0) Cache query metadata that is passed to [`execute/5`](#c:execute/5).
[query\_meta()](#t:query_meta/0) Ecto.Query metadata fields (stored in cache)
[selected()](#t:selected/0) Callbacks
----------
[execute(adapter\_meta, query\_meta, query\_cache, params, options)](#c:execute/5) Executes a previously prepared query.
[prepare(atom, query)](#c:prepare/2) Commands invoked to prepare a query.
[stream(adapter\_meta, query\_meta, query\_cache, params, options)](#c:stream/5) Streams a previously prepared query.
Functions
----------
[plan\_query(operation, adapter, queryable)](#plan_query/3) Plans a query using the given adapter.
[prepare\_query(operation, repo\_name\_or\_pid, queryable)](#prepare_query/3) Plans and prepares a query for the given repo, leveraging its query cache.
Types
======
### adapter\_meta()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L11)
```
@type adapter_meta() :: Ecto.Adapter.adapter_meta()
```
Proxy type to the adapter meta
### cached()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L45)
```
@type cached() :: term()
```
### options()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L46)
```
@type options() :: Keyword.t()
```
### prepared()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L44)
```
@type prepared() :: term()
```
### query\_cache()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L40)
```
@type query_cache() ::
{:nocache, prepared()}
| {:cache, cache_function :: (cached() -> :ok), prepared()}
| {:cached, update_function :: (cached() -> :ok),
reset_function :: (prepared() -> :ok), cached()}
```
Cache query metadata that is passed to [`execute/5`](#c:execute/5).
The cache can be in 3 states, documented below.
If `{:nocache, prepared}` is given, it means the query was not and cannot be cached. The `prepared` value is the value returned by [`prepare/2`](#c:prepare/2).
If `{:cache, cache_function, prepared}` is given, it means the query can be cached and it must be cached by calling the `cache_function` function with the cache entry of your choice. Once `cache_function` is called, the next time the same query is given to [`execute/5`](#c:execute/5), it will receive the `:cached` tuple.
If `{:cached, update_function, reset_function, cached}` is given, it means the query has been cached. You may call `update_function/1` if you want to update the cached result. Or you may call `reset_function/1`, with a new prepared query, to force the query to be cached again. If `reset_function/1` is called, the next time the same query is given to [`execute/5`](#c:execute/5), it will receive the `:cache` tuple.
### query\_meta()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L14)
```
@type query_meta() :: %{sources: tuple(), preloads: term(), select: map()}
```
Ecto.Query metadata fields (stored in cache)
### selected()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L47)
```
@type selected() :: term()
```
Callbacks
==========
### execute(adapter\_meta, query\_meta, query\_cache, params, options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L85)
```
@callback execute(
adapter_meta(),
query_meta(),
query_cache(),
params :: list(),
options()
) ::
{non_neg_integer(), [[selected()]] | nil}
```
Executes a previously prepared query.
The `query_meta` field is a map containing some of the fields found in the [`Ecto.Query`](ecto.query) struct, after they have been normalized. For example, the values `selected` by the query, which then have to be returned, can be found in `query_meta`.
The `query_cache` and its state is documented in [`query_cache/0`](#t:query_cache/0).
The `params` is the list of query parameters. For example, for a query such as `from Post, where: [id: ^123]`, `params` will be `[123]`.
Finally, `options` is a keyword list of options given to the `Repo` operation that triggered the adapter call. Any option is allowed, as this is a mechanism to allow users of Ecto to customize how the adapter behaves per operation.
It must return a tuple containing the number of entries and the result set as a list of lists. The entries in the actual list will depend on what has been selected by the query. The result set may also be `nil`, if no value is being selected.
### prepare(atom, query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L58)
```
@callback prepare(atom :: :all | :update_all | :delete_all, query :: Ecto.Query.t()) ::
{:cache, prepared()} | {:nocache, prepared()}
```
Commands invoked to prepare a query.
It is used on [`Ecto.Repo.all/2`](ecto.repo#c:all/2), [`Ecto.Repo.update_all/3`](ecto.repo#c:update_all/3), and [`Ecto.Repo.delete_all/2`](ecto.repo#c:delete_all/2). If returns a tuple, saying if this query can be cached or not, and the `prepared` query. The `prepared` query is any term that will be passed to the adapter's [`execute/5`](#c:execute/5).
### stream(adapter\_meta, query\_meta, query\_cache, params, options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L95)
```
@callback stream(adapter_meta(), query_meta(), query_cache(), params :: list(), options()) ::
Enumerable.t()
```
Streams a previously prepared query.
See [`execute/5`](#c:execute/5) for a description of arguments.
It returns a stream of values.
Functions
==========
### plan\_query(operation, adapter, queryable)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L120)
Plans a query using the given adapter.
This does not expect the repository and therefore does not leverage the cache.
### prepare\_query(operation, repo\_name\_or\_pid, queryable)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/queryable.ex#L103)
Plans and prepares a query for the given repo, leveraging its query cache.
This operation uses the query cache if one is available.
phoenix Ecto.Changeset Ecto.Changeset
===============
Changesets allow filtering, casting, validation and definition of constraints when manipulating structs.
There is an example of working with changesets in the introductory documentation in the [`Ecto`](ecto) module. The functions [`cast/4`](#cast/4) and [`change/2`](#change/2) are the usual entry points for creating changesets. The first one is used to cast and validate external parameters, such as parameters sent through a form, API, command line, etc. The second one is used to change data directly from your application.
The remaining functions in this module, such as validations, constraints, association handling, are about manipulating changesets. Let's discuss some of this extra functionality.
External vs internal data
--------------------------
Changesets allow working with both kinds of data:
* internal to the application - for example programmatically generated, or coming from other subsystems. This use case is primarily covered by the [`change/2`](#change/2) and [`put_change/3`](#put_change/3) functions.
* external to the application - for example data provided by the user in a form that needs to be type-converted and properly validated. This use case is primarily covered by the [`cast/4`](#cast/4) function.
Validations and constraints
----------------------------
Ecto changesets provide both validations and constraints which are ultimately turned into errors in case something goes wrong.
The difference between them is that most validations can be executed without a need to interact with the database and, therefore, are always executed before attempting to insert or update the entry in the database. Validations run immediately when a validation function is called on the data that is contained in the changeset at that time.
Some validations may happen against the database but they are inherently unsafe. Those validations start with a `unsafe_` prefix, such as [`unsafe_validate_unique/3`](#unsafe_validate_unique/3).
On the other hand, constraints rely on the database and are always safe. As a consequence, validations are always checked before constraints. Constraints won't even be checked in case validations failed.
Let's see an example:
```
defmodule User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name
field :email
field :age, :integer
end
def changeset(user, params \\ %{}) do
user
|> cast(params, [:name, :email, :age])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> validate_inclusion(:age, 18..100)
|> unique_constraint(:email)
end
end
```
In the `changeset/2` function above, we define three validations. They check that `name` and `email` fields are present in the changeset, the e-mail is of the specified format, and the age is between 18 and 100 - as well as a unique constraint in the email field.
Let's suppose the e-mail is given but the age is invalid. The changeset would have the following errors:
```
changeset = User.changeset(%User{}, %{age: 0, email: "[email protected]"})
{:error, changeset} = Repo.insert(changeset)
changeset.errors #=> [age: {"is invalid", []}, name: {"can't be blank", []}]
```
In this case, we haven't checked the unique constraint in the e-mail field because the data did not validate. Let's fix the age and the name, and assume that the e-mail already exists in the database:
```
changeset = User.changeset(%User{}, %{age: 42, name: "Mary", email: "[email protected]"})
{:error, changeset} = Repo.insert(changeset)
changeset.errors #=> [email: {"has already been taken", []}]
```
Validations and constraints define an explicit boundary when the check happens. By moving constraints to the database, we also provide a safe, correct and data-race free means of checking the user input.
### Deferred constraints
Some databases support deferred constraints, i.e., constraints which are checked at the end of the transaction rather than at the end of each statement.
Changesets do not support this type of constraints. When working with deferred constraints, a violation while invoking [`Ecto.Repo.insert/2`](ecto.repo#c:insert/2) or [`Ecto.Repo.update/2`](ecto.repo#c:update/2) won't return `{:error, changeset}`, but rather raise an error at the end of the transaction.
Empty values
-------------
Many times, the data given on cast needs to be further pruned, specially regarding empty values. For example, if you are gathering data to be cast from the command line or through an HTML form or any other text-based format, it is likely those means cannot express nil values. For those reasons, changesets include the concept of empty values, which are values that will be automatically converted to the field's default value on [`cast/4`](#cast/4). Those values are stored in the changeset `empty_values` field and default to `[""]`. You can also pass the `:empty_values` option to [`cast/4`](#cast/4) in case you want to change how a particular [`cast/4`](#cast/4) work.
Associations, embeds and on replace
------------------------------------
Using changesets you can work with associations as well as with embedded structs. There are two primary APIs:
* [`cast_assoc/3`](#cast_assoc/3) and [`cast_embed/3`](#cast_embed/3) - those functions are used when working with external data. In particular, they allow you to change associations and embeds alongside the parent struct, all at once.
* [`put_assoc/4`](#put_assoc/4) and [`put_embed/4`](#put_embed/4) - it allows you to replace the association or embed as a whole. This can be used to move associated data from one entry to another, to completely remove or replace existing entries.
See the documentation for those functions for more information.
### The `:on_replace` option
When using any of those APIs, you may run into situations where Ecto sees data is being replaced. For example, imagine a Post has many Comments where the comments have IDs 1, 2 and 3. If you call [`cast_assoc/3`](#cast_assoc/3) passing only the IDs 1 and 2, Ecto will consider 3 is being "replaced" and it will raise by default. Such behaviour can be changed when defining the relation by setting `:on_replace` option when defining your association/embed according to the values below:
* `:raise` (default) - do not allow removing association or embedded data via parent changesets
* `:mark_as_invalid` - if attempting to remove the association or embedded data via parent changeset - an error will be added to the parent changeset, and it will be marked as invalid
* `:nilify` - sets owner reference column to `nil` (available only for associations). Use this on a `belongs_to` column to allow the association to be cleared out so that it can be set to a new value. Will set `action` on associated changesets to `:replace`
* `:update` - updates the association, available only for `has_one`, `belongs_to` and `embeds_one`. This option will update all the fields given to the changeset including the id for the association
* `:delete` - removes the association or related data from the database. This option has to be used carefully (see below). Will set `action` on associated changesets to `:replace`
* `:delete_if_exists` - like `:delete` except that it ignores any stale entry error. For instance, if you set `on_replace: :delete` but the replaced resource was already deleted by a separate request, it will raise a [`Ecto.StaleEntryError`](ecto.staleentryerror). `:delete_if_exists` makes it so it will only delete if the entry still exists
The `:delete` and `:delete_if_exists` options must be used carefully as they allow users to delete any associated data by simply not sending the associated data. If you need deletion, it is often preferred to add a separate boolean virtual field in the schema and manually mark the changeset for deletion if the `:delete` field is set in the params, as in the example below. Note that we don't call [`cast/4`](#cast/4) in this case because we don't want to prevent deletion if a change is invalid (changes are irrelevant if the entity needs to be deleted).
```
defmodule Comment do
use Ecto.Schema
import Ecto.Changeset
schema "comments" do
field :body, :string
field :delete, :boolean, virtual: true
end
def changeset(comment, %{"delete" => "true"}) do
%{Ecto.Changeset.change(comment, delete: true) | action: :delete}
end
def changeset(comment, params) do
cast(comment, params, [:body])
end
end
```
Schemaless changesets
----------------------
In the changeset examples so far, we have always used changesets to validate and cast data contained in a struct defined by an Ecto schema, such as the `%User{}` struct defined by the `User` module.
However, changesets can also be used with "regular" structs too by passing a tuple with the data and its types:
```
user = %User{}
types = %{first_name: :string, last_name: :string, email: :string}
changeset =
{user, types}
|> Ecto.Changeset.cast(params, Map.keys(types))
|> Ecto.Changeset.validate_required(...)
|> Ecto.Changeset.validate_length(...)
```
where the user struct refers to the definition in the following module:
```
defmodule User do
defstruct [:name, :age]
end
```
Changesets can also be used with data in a plain map, by following the same API:
```
data = %{}
types = %{name: :string}
params = %{name: "Callum"}
changeset =
{data, types}
|> Ecto.Changeset.cast(params, Map.keys(types))
|> Ecto.Changeset.validate_required(...)
|> Ecto.Changeset.validate_length(...)
```
Such functionality makes Ecto extremely useful to cast, validate and prune data even if it is not meant to be persisted to the database.
### Changeset actions
Changesets have an action field which is usually set by [`Ecto.Repo`](ecto.repo) whenever one of the operations such as `insert` or `update` is called:
```
changeset = User.changeset(%User{}, %{age: 42, email: "[email protected]"})
{:error, changeset} = Repo.insert(changeset)
changeset.action
#=> :insert
```
This means that when working with changesets that are not meant to be persisted to the database, such as schemaless changesets, you may need to explicitly set the action to one specific value. Frameworks such as Phoenix use the action value to define how HTML forms should act.
Instead of setting the action manually, you may use [`apply_action/2`](#apply_action/2) that emulates operations such as `c:Ecto.Repo.insert`. [`apply_action/2`](#apply_action/2) will return `{:ok, changes}` if the changeset is valid or `{:error, changeset}`, with the given `action` set in the changeset in case of errors.
The Ecto.Changeset struct
--------------------------
The public fields are:
* `valid?` - Stores if the changeset is valid
* `data` - The changeset source data, for example, a struct
* `params` - The parameters as given on changeset creation
* `changes` - The `changes` from parameters that were approved in casting
* `errors` - All errors from validations
* `required` - All required fields as a list of atoms
* `action` - The action to be performed with the changeset
* `types` - Cache of the data's field types
* `empty_values` - A list of values to be considered empty
* `repo` - The repository applying the changeset (only set after a Repo function is called)
* `repo_opts` - A keyword list of options given to the underlying repository operation
The following fields are private and must not be accessed directly.
* `validations`
* `constraints`
* `filters`
* `prepare`
### Redacting fields in inspect
To hide a field's value from the inspect protocol of [`Ecto.Changeset`](ecto.changeset#content), mark the field as `redact: true` in the schema, and it will display with the value `**redacted**`.
Summary
========
Types
------
[action()](#t:action/0) [constraint()](#t:constraint/0) [data()](#t:data/0) [error()](#t:error/0) [t()](#t:t/0) [t(data\_type)](#t:t/1) [types()](#t:types/0) Functions
----------
[add\_error(changeset, key, message, keys \\ [])](#add_error/4) Adds an error to the changeset.
[apply\_action!(changeset, action)](#apply_action!/2) Applies the changeset action if the changes are valid or raises an error.
[apply\_action(changeset, action)](#apply_action/2) Applies the changeset action only if the changes are valid.
[apply\_changes(changeset)](#apply_changes/1) Applies the changeset changes to the changeset data.
[assoc\_constraint(changeset, assoc, opts \\ [])](#assoc_constraint/3) Checks the associated field exists.
[cast(data, params, permitted, opts \\ [])](#cast/4) Applies the given `params` as changes on the `data` according to the set of `permitted` keys. Returns a changeset.
[cast\_assoc(changeset, name, opts \\ [])](#cast_assoc/3) Casts the given association with the changeset parameters.
[cast\_embed(changeset, name, opts \\ [])](#cast_embed/3) Casts the given embed with the changeset parameters.
[change(data, changes \\ %{})](#change/2) Wraps the given data in a changeset or adds changes to a changeset.
[check\_constraint(changeset, field, opts \\ [])](#check_constraint/3) Checks for a check constraint in the given field.
[constraints(changeset)](#constraints/1) Returns all constraints in a changeset.
[delete\_change(changeset, key)](#delete_change/2) Deletes a change with the given key.
[exclusion\_constraint(changeset, field, opts \\ [])](#exclusion_constraint/3) Checks for an exclusion constraint in the given field.
[fetch\_change!(changeset, key)](#fetch_change!/2) Same as [`fetch_change/2`](#fetch_change/2) but returns the value or raises if the given key was not found.
[fetch\_change(changeset, key)](#fetch_change/2) Fetches a change from the given changeset.
[fetch\_field!(changeset, key)](#fetch_field!/2) Same as [`fetch_field/2`](#fetch_field/2) but returns the value or raises if the given key was not found.
[fetch\_field(changeset, key)](#fetch_field/2) Fetches the given field from changes or from the data.
[force\_change(changeset, key, value)](#force_change/3) Forces a change on the given `key` with `value`.
[foreign\_key\_constraint(changeset, field, opts \\ [])](#foreign_key_constraint/3) Checks for foreign key constraint in the given field.
[get\_change(changeset, key, default \\ nil)](#get_change/3) Gets a change or returns a default value.
[get\_field(changeset, key, default \\ nil)](#get_field/3) Gets a field from changes or from the data.
[merge(changeset1, changeset2)](#merge/2) Merges two changesets.
[no\_assoc\_constraint(changeset, assoc, opts \\ [])](#no_assoc_constraint/3) Checks the associated field does not exist.
[optimistic\_lock(data\_or\_changeset, field, incrementer \\ &increment\_with\_rollover/1)](#optimistic_lock/3) Applies optimistic locking to the changeset.
[prepare\_changes(changeset, function)](#prepare_changes/2) Provides a function executed by the repository on insert/update/delete.
[put\_assoc(changeset, name, value, opts \\ [])](#put_assoc/4) Puts the given association entry or entries as a change in the changeset.
[put\_change(changeset, key, value)](#put_change/3) Puts a change on the given `key` with `value`.
[put\_embed(changeset, name, value, opts \\ [])](#put_embed/4) Puts the given embed entry or entries as a change in the changeset.
[traverse\_errors(changeset, msg\_func)](#traverse_errors/2) Traverses changeset errors and applies the given function to error messages.
[traverse\_validations(changeset, msg\_func)](#traverse_validations/2) Traverses changeset validations and applies the given function to validations.
[unique\_constraint(changeset, field\_or\_fields, opts \\ [])](#unique_constraint/3) Checks for a unique constraint in the given field or list of fields.
[unsafe\_validate\_unique(changeset, fields, repo, opts \\ [])](#unsafe_validate_unique/4) Validates that no existing record with a different primary key has the same values for these fields.
[update\_change(changeset, key, function)](#update_change/3) Updates a change.
[validate\_acceptance(changeset, field, opts \\ [])](#validate_acceptance/3) Validates the given parameter is true.
[validate\_change(changeset, field, validator)](#validate_change/3) Validates the given `field` change.
[validate\_change(changeset, field, metadata, validator)](#validate_change/4) Stores the validation `metadata` and validates the given `field` change.
[validate\_confirmation(changeset, field, opts \\ [])](#validate_confirmation/3) Validates that the given parameter matches its confirmation.
[validate\_exclusion(changeset, field, data, opts \\ [])](#validate_exclusion/4) Validates a change is not included in the given enumerable.
[validate\_format(changeset, field, format, opts \\ [])](#validate_format/4) Validates a change has the given format.
[validate\_inclusion(changeset, field, data, opts \\ [])](#validate_inclusion/4) Validates a change is included in the given enumerable.
[validate\_length(changeset, field, opts)](#validate_length/3) Validates a change is a string or list of the given length.
[validate\_number(changeset, field, opts)](#validate_number/3) Validates the properties of a number.
[validate\_required(changeset, fields, opts \\ [])](#validate_required/3) Validates that one or more fields are present in the changeset.
[validate\_subset(changeset, field, data, opts \\ [])](#validate_subset/4) Validates a change, of type enum, is a subset of the given enumerable.
[validations(changeset)](#validations/1) Returns a keyword list of the validations for this changeset.
Types
======
### action()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L309)
```
@type action() :: nil | :insert | :update | :delete | :replace | :ignore | atom()
```
### constraint()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L310)
```
@type constraint() :: %{
type: :check | :exclusion | :foreign_key | :unique,
constraint: String.t(),
match: :exact | :suffix | :prefix,
field: atom(),
error_message: String.t(),
error_type: atom()
}
```
### data()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L313)
```
@type data() :: map()
```
### error()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L308)
```
@type error() :: {String.t(), Keyword.t()}
```
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L307)
```
@type t() :: t(Ecto.Schema.t() | map() | nil)
```
### t(data\_type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L290)
```
@type t(data_type) :: %Ecto.Changeset{
action: action(),
changes: %{optional(atom()) => term()},
constraints: [constraint()],
data: data_type,
empty_values: term(),
errors: [{atom(), error()}],
filters: %{optional(atom()) => term()},
params: %{optional(String.t()) => term()} | nil,
prepare: [(t() -> t())],
repo: atom() | nil,
repo_opts: Keyword.t(),
required: [atom()],
types:
nil
| %{required(atom()) => Ecto.Type.t() | {:assoc, term()} | {:embed, term()}},
valid?: boolean(),
validations: [{atom(), term()}]
}
```
### types()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L314)
```
@type types() :: map()
```
Functions
==========
### add\_error(changeset, key, message, keys \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1674)
```
@spec add_error(t(), atom(), String.t(), Keyword.t()) :: t()
```
Adds an error to the changeset.
An additional keyword list `keys` can be passed to provide additional contextual information for the error. This is useful when using [`traverse_errors/2`](#traverse_errors/2) and when translating errors with `Gettext`
#### Examples
```
iex> changeset = change(%Post{}, %{title: ""})
iex> changeset = add_error(changeset, :title, "empty")
iex> changeset.errors
[title: {"empty", []}]
iex> changeset.valid?
false
iex> changeset = change(%Post{}, %{title: ""})
iex> changeset = add_error(changeset, :title, "empty", additional: "info")
iex> changeset.errors
[title: {"empty", [additional: "info"]}]
iex> changeset.valid?
false
iex> changeset = change(%Post{}, %{tags: ["ecto", "elixir", "x"]})
iex> changeset = add_error(changeset, :tags, "tag '%{val}' is too short", val: "x")
iex> changeset.errors
[tags: {"tag '%{val}' is too short", [val: "x"]}]
iex> changeset.valid?
false
```
### apply\_action!(changeset, action)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1574)
```
@spec apply_action!(t(), atom()) :: Ecto.Schema.t() | data()
```
Applies the changeset action if the changes are valid or raises an error.
#### Examples
```
iex> changeset = change(%Post{author: "bar"}, %{title: "foo"})
iex> apply_action!(changeset, :update)
%Post{author: "bar", title: "foo"}
iex> changeset = change(%Post{author: "bar"}, %{title: :bad})
iex> apply_action!(changeset, :update)
** (Ecto.InvalidChangesetError) could not perform update because changeset is invalid.
```
See [`apply_action/2`](#apply_action/2) for more information.
### apply\_action(changeset, action)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1546)
```
@spec apply_action(t(), atom()) :: {:ok, Ecto.Schema.t() | data()} | {:error, t()}
```
Applies the changeset action only if the changes are valid.
If the changes are valid, all changes are applied to the changeset data. If the changes are invalid, no changes are applied, and an error tuple is returned with the changeset containing the action that was attempted to be applied.
The action may be any atom.
#### Examples
```
iex> {:ok, data} = apply_action(changeset, :update)
iex> {:error, changeset} = apply_action(changeset, :update)
%Ecto.Changeset{action: :update}
```
### apply\_changes(changeset)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1510)
```
@spec apply_changes(t()) :: Ecto.Schema.t() | data()
```
Applies the changeset changes to the changeset data.
This operation will return the underlying data with changes regardless if the changeset is valid or not. See [`apply_action/2`](#apply_action/2) for a similar function that ensures the changeset is valid.
#### Examples
```
iex> changeset = change(%Post{author: "bar"}, %{title: "foo"})
iex> apply_changes(changeset)
%Post{author: "bar", title: "foo"}
```
### assoc\_constraint(changeset, assoc, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2852)
```
@spec assoc_constraint(t(), atom(), Keyword.t()) :: t()
```
Checks the associated field exists.
This is similar to [`foreign_key_constraint/3`](#foreign_key_constraint/3) except that the field is inferred from the association definition. This is useful to guarantee that a child will only be created if the parent exists in the database too. Therefore, it only applies to `belongs_to` associations.
As the name says, a constraint is required in the database for this function to work. Such constraint is often added as a reference to the child table:
```
create table(:comments) do
add :post_id, references(:posts)
end
```
Now, when inserting a comment, it is possible to forbid any comment to be added if the associated post does not exist:
```
comment
|> Ecto.Changeset.cast(params, [:post_id])
|> Ecto.Changeset.assoc_constraint(:post)
|> Repo.insert
```
#### Options
* `:message` - the message in case the constraint check fails, defaults to "does not exist"
* `:name` - the constraint name. By default, the constraint name is inferred from the table + association field. May be required explicitly for complex cases
* `:match` - how the changeset constraint name is matched against the repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` to this changeset constraint. `:prefix` matches any repo constraint which `starts_with?` `:name` to this changeset constraint.
### cast(data, params, permitted, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L478)
```
@spec cast(
Ecto.Schema.t() | t() | {data(), types()},
%{required(binary()) => term()} | %{required(atom()) => term()} | :invalid,
[atom()],
Keyword.t()
) :: t()
```
Applies the given `params` as changes on the `data` according to the set of `permitted` keys. Returns a changeset.
`data` may be either a changeset, a schema struct or a `{data, types}` tuple. The second argument is a map of `params` that are cast according to the type information from `data`. `params` is a map with string keys or a map with atom keys, containing potentially invalid data. Mixed keys are not allowed.
During casting, all `permitted` parameters whose values match the specified type information will have their key name converted to an atom and stored together with the value as a change in the `:changes` field of the changeset. All parameters that are not explicitly permitted are ignored.
If casting of all fields is successful, the changeset is returned as valid.
Note that [`cast/4`](#cast/4) validates the types in the `params`, but not in the given `data`.
#### Options
* `:empty_values` - a list of values to be considered as empty when casting. Empty values are always replaced by the default value of the respective key. Defaults to `[""]`
#### Examples
```
iex> changeset = cast(post, params, [:title])
iex> if changeset.valid? do
...> Repo.update!(changeset)
...> end
```
Passing a changeset as the first argument:
```
iex> changeset = cast(post, %{title: "Hello"}, [:title])
iex> new_changeset = cast(changeset, %{title: "Foo", body: "World"}, [:body])
iex> new_changeset.params
%{"title" => "Hello", "body" => "World"}
```
Or creating a changeset from a simple map with types:
```
iex> data = %{title: "hello"}
iex> types = %{title: :string}
iex> changeset = cast({data, types}, %{title: "world"}, [:title])
iex> apply_changes(changeset)
%{title: "world"}
```
#### Composing casts
[`cast/4`](#cast/4) also accepts a changeset as its first argument. In such cases, all the effects caused by the call to [`cast/4`](#cast/4) (additional errors and changes) are simply added to the ones already present in the argument changeset. Parameters are merged (**not deep-merged**) and the ones passed to [`cast/4`](#cast/4) take precedence over the ones already in the changeset.
### cast\_assoc(changeset, name, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L748)
Casts the given association with the changeset parameters.
This function should be used when working with the entire association at once (and not a single element of a many-style association) and receiving data external to the application.
[`cast_assoc/3`](#cast_assoc/3) works matching the records extracted from the database and compares it with the parameters received from an external source. Therefore, it is expected that the data in the changeset has explicitly preloaded the association being cast and that all of the IDs exist and are unique.
For example, imagine a user has many addresses relationship where post data is sent as follows
```
%{"name" => "john doe", "addresses" => [
%{"street" => "somewhere", "country" => "brazil", "id" => 1},
%{"street" => "elsewhere", "country" => "poland"},
]}
```
and then
```
User
|> Repo.get!(id)
|> Repo.preload(:addresses) # Only required when updating data
|> Ecto.Changeset.cast(params, [])
|> Ecto.Changeset.cast_assoc(:addresses, with: &MyApp.Address.changeset/2)
```
The parameters for the given association will be retrieved from `changeset.params`. Those parameters are expected to be a map with attributes, similar to the ones passed to [`cast/4`](#cast/4). Once parameters are retrieved, [`cast_assoc/3`](#cast_assoc/3) will match those parameters with the associations already in the changeset record.
Once [`cast_assoc/3`](#cast_assoc/3) is called, Ecto will compare each parameter with the user's already preloaded addresses and act as follows:
* If the parameter does not contain an ID, the parameter data will be passed to `MyApp.Address.changeset/2` with a new struct and become an insert operation
* If the parameter contains an ID and there is no associated child with such ID, the parameter data will be passed to `MyApp.Address.changeset/2` with a new struct and become an insert operation
* If the parameter contains an ID and there is an associated child with such ID, the parameter data will be passed to `MyApp.Address.changeset/2` with the existing struct and become an update operation
* If there is an associated child with an ID and its ID is not given as parameter, the `:on_replace` callback for that association will be invoked (see the "On replace" section on the module documentation)
Every time the `MyApp.Address.changeset/2` function is invoked, it must return a changeset. Once the parent changeset is given to an [`Ecto.Repo`](ecto.repo) function, all entries will be inserted/updated/deleted within the same transaction.
Note developers are allowed to explicitly set the `:action` field of a changeset to instruct Ecto how to act in certain situations. Let's suppose that, if one of the associations has only empty fields, you want to ignore the entry altogether instead of showing an error. The changeset function could be written like this:
```
def changeset(struct, params) do
struct
|> cast(params, [:title, :body])
|> validate_required([:title, :body])
|> case do
%{valid?: false, changes: changes} = changeset when changes == %{} ->
# If the changeset is invalid and has no changes, it is
# because all required fields are missing, so we ignore it.
%{changeset | action: :ignore}
changeset ->
changeset
end
end
```
#### Partial changes for many-style associations
By preloading an association using a custom query you can confine the behavior of [`cast_assoc/3`](#cast_assoc/3). This opens up the possibility to work on a subset of the data, instead of all associations in the database.
Taking the initial example of users having addresses imagine those addresses are set up to belong to a country. If you want to allow users to bulk edit all addresses that belong to a single country, you can do so by changing the preload query:
```
query = from MyApp.Address, where: [country: ^edit_country]
User
|> Repo.get!(id)
|> Repo.preload(addresses: query)
|> Ecto.Changeset.cast(params, [])
|> Ecto.Changeset.cast_assoc(:addresses)
```
This will allow you to cast and update only the association for the given country. The important point for partial changes is that any addresses, which were not preloaded won't be changed.
#### Options
* `:required` - if the association is a required field
* `:required_message` - the message on failure, defaults to "can't be blank"
* `:invalid_message` - the message on failure, defaults to "is invalid"
* `:force_update_on_change` - force the parent record to be updated in the repository if there is a change, defaults to `true`
* `:with` - the function to build the changeset from params. Defaults to the `changeset/2` function of the associated module. It can be changed by passing an anonymous function or an MFA tuple. If using an MFA, the default changeset and parameters arguments will be prepended to the given args. For example, using `with: {Author, :special_changeset, ["hello"]}` will be invoked as `Author.special_changeset(changeset, params, "hello")`
### cast\_embed(changeset, name, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L780)
Casts the given embed with the changeset parameters.
The parameters for the given embed will be retrieved from `changeset.params`. Those parameters are expected to be a map with attributes, similar to the ones passed to [`cast/4`](#cast/4). Once parameters are retrieved, [`cast_embed/3`](#cast_embed/3) will match those parameters with the embeds already in the changeset record. See [`cast_assoc/3`](#cast_assoc/3) for an example of working with casts and associations which would also apply for embeds.
The changeset must have been previously `cast` using [`cast/4`](#cast/4) before this function is invoked.
#### Options
* `:required` - if the embed is a required field
* `:required_message` - the message on failure, defaults to "can't be blank"
* `:invalid_message` - the message on failure, defaults to "is invalid"
* `:force_update_on_change` - force the parent record to be updated in the repository if there is a change, defaults to `true`
* `:with` - the function to build the changeset from params. Defaults to the `changeset/2` function of the embedded module. It can be changed by passing an anonymous function or an MFA tuple. If using an MFA, the default changeset and parameters arguments will be prepended to the given args. For example, using `with: {Author, :special_changeset, ["hello"]}` will be invoked as `Author.special_changeset(changeset, params, "hello")`
### change(data, changes \\ %{})[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L383)
```
@spec change(
Ecto.Schema.t() | t() | {data(), types()},
%{required(atom()) => term()} | Keyword.t()
) ::
t()
```
Wraps the given data in a changeset or adds changes to a changeset.
`changes` is a map or keyword where the key is an atom representing a field, association or embed and the value is a term. Note the `value` is directly stored in the changeset with no validation whatsoever. For this reason, this function is meant for working with data internal to the application.
When changing embeds and associations, see [`put_assoc/4`](#put_assoc/4) for a complete reference on the accepted values.
This function is useful for:
* wrapping a struct inside a changeset
* directly changing a struct without performing castings nor validations
* directly bulk-adding changes to a changeset
Changed attributes will only be added if the change does not have the same value as the field in the data.
When a changeset is passed as the first argument, the changes passed as the second argument are merged over the changes already in the changeset if they differ from the values in the struct.
When a `{data, types}` is passed as the first argument, a changeset is created with the given data and types and marked as valid.
See [`cast/4`](#cast/4) if you'd prefer to cast and validate external parameters.
#### Examples
```
iex> changeset = change(%Post{})
%Ecto.Changeset{...}
iex> changeset.valid?
true
iex> changeset.changes
%{}
iex> changeset = change(%Post{author: "bar"}, title: "title")
iex> changeset.changes
%{title: "title"}
iex> changeset = change(%Post{title: "title"}, title: "title")
iex> changeset.changes
%{}
iex> changeset = change(changeset, %{title: "new title", body: "body"})
iex> changeset.changes.title
"new title"
iex> changeset.changes.body
"body"
```
### check\_constraint(changeset, field, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2619)
Checks for a check constraint in the given field.
The check constraint works by relying on the database to check if the check constraint has been violated or not and, if so, Ecto converts it into a changeset error.
In order to use the check constraint, the first step is to define the check constraint in a migration:
```
create constraint("users", :age_must_be_positive, check: "age > 0")
```
Now that a constraint exists, when modifying users, we could annotate the changeset with a check constraint so Ecto knows how to convert it into an error message:
```
cast(user, params, [:age])
|> check_constraint(:age, name: :age_must_be_positive)
```
Now, when invoking [`Ecto.Repo.insert/2`](ecto.repo#c:insert/2) or [`Ecto.Repo.update/2`](ecto.repo#c:update/2), if the age is not positive, it will be converted into an error and `{:error, changeset}` returned by the repository. Note that the error will occur only after hitting the database so it will not be visible until all other validations pass.
#### Options
* `:message` - the message in case the constraint check fails. Defaults to "is invalid"
* `:name` - the name of the constraint. Required.
* `:match` - how the changeset constraint name is matched against the repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` to this changeset constraint. `:prefix` matches any repo constraint which `starts_with?` `:name` to this changeset constraint.
### constraints(changeset)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2578)
```
@spec constraints(t()) :: [constraint()]
```
Returns all constraints in a changeset.
A constraint is a map with the following fields:
* `:type` - the type of the constraint that will be checked in the database, such as `:check`, `:unique`, etc
* `:constraint` - the database constraint name as a string
* `:match` - the type of match Ecto will perform on a violated constraint against the `:constraint` value. It is `:exact`, `:suffix` or `:prefix`
* `:field` - the field a violated constraint will apply the error to
* `:error_message` - the error message in case of violated constraints
* `:error_type` - the type of error that identifies the error message
### delete\_change(changeset, key)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1490)
```
@spec delete_change(t(), atom()) :: t()
```
Deletes a change with the given key.
#### Examples
```
iex> changeset = change(%Post{}, %{title: "foo"})
iex> changeset = delete_change(changeset, :title)
iex> get_change(changeset, :title)
nil
```
### exclusion\_constraint(changeset, field, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2945)
Checks for an exclusion constraint in the given field.
The exclusion constraint works by relying on the database to check if the exclusion constraint has been violated or not and, if so, Ecto converts it into a changeset error.
#### Options
* `:message` - the message in case the constraint check fails, defaults to "violates an exclusion constraint"
* `:name` - the constraint name. By default, the constraint name is inferred from the table + field. May be required explicitly for complex cases
* `:match` - how the changeset constraint name is matched against the repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` to this changeset constraint. `:prefix` matches any repo constraint which `starts_with?` `:name` to this changeset constraint.
### fetch\_change!(changeset, key)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1113)
```
@spec fetch_change!(t(), atom()) :: term()
```
Same as [`fetch_change/2`](#fetch_change/2) but returns the value or raises if the given key was not found.
#### Examples
```
iex> changeset = change(%Post{body: "foo"}, %{title: "bar"})
iex> fetch_change!(changeset, :title)
"bar"
iex> fetch_change!(changeset, :body)
** (KeyError) key :body not found in: %{title: "bar"}
```
### fetch\_change(changeset, key)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1097)
```
@spec fetch_change(t(), atom()) :: {:ok, term()} | :error
```
Fetches a change from the given changeset.
This function only looks at the `:changes` field of the given `changeset` and returns `{:ok, value}` if the change is present or `:error` if it's not.
#### Examples
```
iex> changeset = change(%Post{body: "foo"}, %{title: "bar"})
iex> fetch_change(changeset, :title)
{:ok, "bar"}
iex> fetch_change(changeset, :body)
:error
```
### fetch\_field!(changeset, key)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1021)
```
@spec fetch_field!(t(), atom()) :: term()
```
Same as [`fetch_field/2`](#fetch_field/2) but returns the value or raises if the given key was not found.
#### Examples
```
iex> post = %Post{title: "Foo", body: "Bar baz bong"}
iex> changeset = change(post, %{title: "New title"})
iex> fetch_field!(changeset, :title)
"New title"
iex> fetch_field!(changeset, :other)
** (KeyError) key :other not found in: %Post{...}
```
### fetch\_field(changeset, key)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L996)
```
@spec fetch_field(t(), atom()) :: {:changes, term()} | {:data, term()} | :error
```
Fetches the given field from changes or from the data.
While [`fetch_change/2`](#fetch_change/2) only looks at the current `changes` to retrieve a value, this function looks at the changes and then falls back on the data, finally returning `:error` if no value is available.
For relations, these functions will return the changeset original data with changes applied. To retrieve raw changesets, please use [`fetch_change/2`](#fetch_change/2).
#### Examples
```
iex> post = %Post{title: "Foo", body: "Bar baz bong"}
iex> changeset = change(post, %{title: "New title"})
iex> fetch_field(changeset, :title)
{:changes, "New title"}
iex> fetch_field(changeset, :body)
{:data, "Bar baz bong"}
iex> fetch_field(changeset, :not_a_field)
:error
```
### force\_change(changeset, key, value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1462)
```
@spec force_change(t(), atom(), term()) :: t()
```
Forces a change on the given `key` with `value`.
If the change is already present, it is overridden with the new value.
#### Examples
```
iex> changeset = change(%Post{author: "bar"}, %{title: "foo"})
iex> changeset = force_change(changeset, :title, "bar")
iex> changeset.changes
%{title: "bar"}
iex> changeset = force_change(changeset, :author, "bar")
iex> changeset.changes
%{title: "bar", author: "bar"}
```
### foreign\_key\_constraint(changeset, field, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2806)
```
@spec foreign_key_constraint(t(), atom(), Keyword.t()) :: t()
```
Checks for foreign key constraint in the given field.
The foreign key constraint works by relying on the database to check if the associated data exists or not. This is useful to guarantee that a child will only be created if the parent exists in the database too.
In order to use the foreign key constraint the first step is to define the foreign key in a migration. This is often done with references. For example, imagine you are creating a comments table that belongs to posts. One would have:
```
create table(:comments) do
add :post_id, references(:posts)
end
```
By default, Ecto will generate a foreign key constraint with name "comments\_post\_id\_fkey" (the name is configurable).
Now that a constraint exists, when creating comments, we could annotate the changeset with foreign key constraint so Ecto knows how to convert it into an error message:
```
cast(comment, params, [:post_id])
|> foreign_key_constraint(:post_id)
```
Now, when invoking [`Ecto.Repo.insert/2`](ecto.repo#c:insert/2) or [`Ecto.Repo.update/2`](ecto.repo#c:update/2), if the associated post does not exist, it will be converted into an error and `{:error, changeset}` returned by the repository.
#### Options
* `:message` - the message in case the constraint check fails, defaults to "does not exist"
* `:name` - the constraint name. By default, the constraint name is inferred from the table + field. May be required explicitly for complex cases
* `:match` - how the changeset constraint name is matched against the repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` to this changeset constraint. `:prefix` matches any repo constraint which `starts_with?` `:name` to this changeset constraint.
### get\_change(changeset, key, default \\ nil)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1136)
```
@spec get_change(t(), atom(), term()) :: term()
```
Gets a change or returns a default value.
#### Examples
```
iex> changeset = change(%Post{body: "foo"}, %{title: "bar"})
iex> get_change(changeset, :title)
"bar"
iex> get_change(changeset, :body)
nil
```
### get\_field(changeset, key, default \\ nil)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1051)
```
@spec get_field(t(), atom(), term()) :: term()
```
Gets a field from changes or from the data.
While [`get_change/3`](#get_change/3) only looks at the current `changes` to retrieve a value, this function looks at the changes and then falls back on the data, finally returning `default` if no value is available.
For relations, these functions will return the changeset data with changes applied. To retrieve raw changesets, please use [`get_change/3`](#get_change/3).
```
iex> post = %Post{title: "A title", body: "My body is a cage"}
iex> changeset = change(post, %{title: "A new title"})
iex> get_field(changeset, :title)
"A new title"
iex> get_field(changeset, :not_a_field, "Told you, not a field!")
"Told you, not a field!"
```
### merge(changeset1, changeset2)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L932)
```
@spec merge(t(), t()) :: t()
```
Merges two changesets.
This function merges two changesets provided they have been applied to the same data (their `:data` field is equal); if the data differs, an [`ArgumentError`](https://hexdocs.pm/elixir/ArgumentError.html) exception is raised. If one of the changesets has a `:repo` field which is not `nil`, then the value of that field is used as the `:repo` field of the resulting changeset; if both changesets have a non-`nil` and different `:repo` field, an [`ArgumentError`](https://hexdocs.pm/elixir/ArgumentError.html) exception is raised.
The other fields are merged with the following criteria:
* `params` - params are merged (not deep-merged) giving precedence to the params of `changeset2` in case of a conflict. If both changesets have their `:params` fields set to `nil`, the resulting changeset will have its params set to `nil` too.
* `changes` - changes are merged giving precedence to the `changeset2` changes.
* `errors` and `validations` - they are simply concatenated.
* `required` - required fields are merged; all the fields that appear in the required list of both changesets are moved to the required list of the resulting changeset.
#### Examples
```
iex> changeset1 = cast(%Post{}, %{title: "Title"}, [:title])
iex> changeset2 = cast(%Post{}, %{title: "New title", body: "Body"}, [:title, :body])
iex> changeset = merge(changeset1, changeset2)
iex> changeset.changes
%{body: "Body", title: "New title"}
iex> changeset1 = cast(%Post{body: "Body"}, %{title: "Title"}, [:title])
iex> changeset2 = cast(%Post{}, %{title: "New title"}, [:title])
iex> merge(changeset1, changeset2)
** (ArgumentError) different :data when merging changesets
```
### no\_assoc\_constraint(changeset, assoc, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2908)
```
@spec no_assoc_constraint(t(), atom(), Keyword.t()) :: t()
```
Checks the associated field does not exist.
This is similar to [`foreign_key_constraint/3`](#foreign_key_constraint/3) except that the field is inferred from the association definition. This is useful to guarantee that parent can only be deleted (or have its primary key changed) if no child exists in the database. Therefore, it only applies to `has_*` associations.
As the name says, a constraint is required in the database for this function to work. Such constraint is often added as a reference to the child table:
```
create table(:comments) do
add :post_id, references(:posts)
end
```
Now, when deleting the post, it is possible to forbid any post to be deleted if they still have comments attached to it:
```
post
|> Ecto.Changeset.change
|> Ecto.Changeset.no_assoc_constraint(:comments)
|> Repo.delete
```
#### Options
* `:message` - the message in case the constraint check fails, defaults to "is still associated with this entry" (for `has_one`) and "are still associated with this entry" (for `has_many`)
* `:name` - the constraint name. By default, the constraint name is inferred from the association table + association field. May be required explicitly for complex cases
* `:match` - how the changeset constraint name is matched against the repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` to this changeset constraint. `:prefix` matches any repo constraint which `starts_with?` `:name` to this changeset constraint.
### optimistic\_lock(data\_or\_changeset, field, incrementer \\ &increment\_with\_rollover/1)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2496)
```
@spec optimistic_lock(Ecto.Schema.t() | t(), atom(), (term() -> term())) :: t()
```
Applies optimistic locking to the changeset.
[Optimistic locking](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) (or *optimistic concurrency control*) is a technique that allows concurrent edits on a single record. While pessimistic locking works by locking a resource for an entire transaction, optimistic locking only checks if the resource changed before updating it.
This is done by regularly fetching the record from the database, then checking whether another user has made changes to the record *only when updating the record*. This behaviour is ideal in situations where the chances of concurrent updates to the same record are low; if they're not, pessimistic locking or other concurrency patterns may be more suited.
#### Usage
Optimistic locking works by keeping a "version" counter for each record; this counter gets incremented each time a modification is made to a record. Hence, in order to use optimistic locking, a field must exist in your schema for versioning purpose. Such field is usually an integer but other types are supported.
#### Examples
Assuming we have a `Post` schema (stored in the `posts` table), the first step is to add a version column to the `posts` table:
```
alter table(:posts) do
add :lock_version, :integer, default: 1
end
```
The column name is arbitrary and doesn't need to be `:lock_version`. Now add a field to the schema too:
```
defmodule Post do
use Ecto.Schema
schema "posts" do
field :title, :string
field :lock_version, :integer, default: 1
end
def changeset(:update, struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title])
|> Ecto.Changeset.optimistic_lock(:lock_version)
end
end
```
Now let's take optimistic locking for a spin:
```
iex> post = Repo.insert!(%Post{title: "foo"})
%Post{id: 1, title: "foo", lock_version: 1}
iex> valid_change = Post.changeset(:update, post, %{title: "bar"})
iex> stale_change = Post.changeset(:update, post, %{title: "baz"})
iex> Repo.update!(valid_change)
%Post{id: 1, title: "bar", lock_version: 2}
iex> Repo.update!(stale_change)
** (Ecto.StaleEntryError) attempted to update a stale entry:
%Post{id: 1, title: "baz", lock_version: 1}
```
When a conflict happens (a record which has been previously fetched is being updated, but that same record has been modified since it was fetched), an [`Ecto.StaleEntryError`](ecto.staleentryerror) exception is raised.
Optimistic locking also works with delete operations. Just call the [`optimistic_lock/3`](#optimistic_lock/3) function with the data before delete:
```
iex> changeset = Ecto.Changeset.optimistic_lock(post, :lock_version)
iex> Repo.delete(changeset)
```
[`optimistic_lock/3`](#optimistic_lock/3) by default assumes the field being used as a lock is an integer. If you want to use another type, you need to pass the third argument customizing how the next value is generated:
```
iex> Ecto.Changeset.optimistic_lock(post, :lock_uuid, fn _ -> Ecto.UUID.generate end)
```
### prepare\_changes(changeset, function)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2556)
```
@spec prepare_changes(t(), (t() -> t())) :: t()
```
Provides a function executed by the repository on insert/update/delete.
If the changeset given to the repository is valid, the function given to [`prepare_changes/2`](#prepare_changes/2) will be called with the changeset and must return a changeset, allowing developers to do final adjustments to the changeset or to issue data consistency commands. The repository itself can be accessed inside the function under the `repo` field in the changeset. If the changeset given to the repository is invalid, the function will not be invoked.
The given function is guaranteed to run inside the same transaction as the changeset operation for databases that do support transactions.
#### Example
A common use case is updating a counter cache, in this case updating a post's comment count when a comment is created:
```
def create_comment(comment, params) do
comment
|> cast(params, [:body, :post_id])
|> prepare_changes(fn changeset ->
if post_id = get_change(changeset, :post_id) do
query = from Post, where: [id: ^post_id]
changeset.repo.update_all(query, inc: [comment_count: 1])
end
changeset
end)
end
```
We retrieve the repo from the comment changeset itself and use update\_all to update the counter cache in one query. Finally, the original changeset must be returned.
### put\_assoc(changeset, name, value, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1406)
Puts the given association entry or entries as a change in the changeset.
This function is used to work with associations as a whole. For example, if a Post has many Comments, it allows you to add, remove or change all comments at once. If your goal is to simply add a new comment to a post, then it is preferred to do so manually, as we will describe later in the "Example: Adding a comment to a post" section.
This function requires the associated data to have been preloaded, except when the parent changeset has been newly built and not yet persisted. Missing data will invoke the `:on_replace` behaviour defined on the association.
For associations with cardinality one, `nil` can be used to remove the existing entry. For associations with many entries, an empty list may be given instead.
If the association has no changes, it will be skipped. If the association is invalid, the changeset will be marked as invalid. If the given value is not any of values below, it will raise.
The associated data may be given in different formats:
* a map or a keyword list representing changes to be applied to the associated data. A map or keyword list can be given to update the associated data as long as they have matching primary keys. For example, `put_assoc(changeset, :comments, [%{id: 1, title: "changed"}])` will locate the comment with `:id` of 1 and update its title. If no comment with such id exists, one is created on the fly. Since only a single comment was given, any other associated comment will be replaced. On all cases, it is expected the keys to be atoms. Opposite to `cast_assoc` and `embed_assoc`, the given map (or struct) is not validated in any way and will be inserted as is. This API is mostly used in scripts and tests, to make it straight- forward to create schemas with associations at once, such as:
```
Ecto.Changeset.change(
%Post{},
title: "foo",
comments: [
%{body: "first"},
%{body: "second"}
]
)
```
* changesets - when changesets are given, they are treated as the canonical data and the associated data currently stored in the association is either updated or replaced. For example, if you call `put_assoc(post_changeset, :comments, [list_of_comments_changesets])`, all comments with matching IDs will be updated according to the changesets. New comments or comments not associated to any post will be correctly associated. Currently associated comments that do not have a matching ID in the list of changesets will act according to the `:on_replace` association configuration (you can chose to raise, ignore the operation, update or delete them). If there are changes in any of the changesets, they will be persisted too.
* structs - when structs are given, they are treated as the canonical data and the associated data currently stored in the association is replaced. For example, if you call `put_assoc(post_changeset, :comments, [list_of_comments_structs])`, all comments with matching IDs will be replaced by the new structs. New comments or comments not associated to any post will be correctly associated. Currently associated comments that do not have a matching ID in the list of changesets will act according to the `:on_replace` association configuration (you can chose to raise, ignore the operation, update or delete them). Different to passing changesets, structs are not change tracked in any fashion. In other words, if you change a comment struct and give it to [`put_assoc/4`](#put_assoc/4), the updates in the struct won't be persisted. You must use changesets instead. [`put_assoc/4`](#put_assoc/4) with structs only takes care of guaranteeing that the comments and the parent data are associated. This is extremely useful when associating existing data, as we will see in the "Example: Adding tags to a post" section.
Once the parent changeset is given to an [`Ecto.Repo`](ecto.repo) function, all entries will be inserted/updated/deleted within the same transaction.
#### Example: Adding a comment to a post
Imagine a relationship where Post has many comments and you want to add a new comment to an existing post. While it is possible to use [`put_assoc/4`](#put_assoc/4) for this, it would be unnecessarily complex. Let's see an example.
First, let's fetch the post with all existing comments:
```
post = Post |> Repo.get!(1) |> Repo.preload(:comments)
```
The following approach is **wrong**:
```
post
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:comments, [%Comment{body: "bad example!"}])
|> Repo.update!()
```
The reason why the example above is wrong is because [`put_assoc/4`](#put_assoc/4) always works with the **full data**. So the example above will effectively **erase all previous comments** and only keep the comment you are currently adding. Instead, you could try:
```
post
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:comments, [%Comment{body: "so-so example!"} | post.comments])
|> Repo.update!()
```
In this example, we prepend the new comment to the list of existing comments. Ecto will diff the list of comments currently in `post` with the list of comments given, and correctly insert the new comment to the database. Note, however, Ecto is doing a lot of work just to figure out something we knew since the beginning, which is that there is only one new comment.
In cases like above, when you want to work only on a single entry, it is much easier to simply work on the associated directly. For example, we could instead set the `post` association in the comment:
```
%Comment{body: "better example"}
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:post, post)
|> Repo.insert!()
```
Alternatively, we can make sure that when we create a comment, it is already associated to the post:
```
Ecto.build_assoc(post, :comments)
|> Ecto.Changeset.change(body: "great example!")
|> Repo.insert!()
```
Or we can simply set the post\_id in the comment itself:
```
%Comment{body: "better example", post_id: post.id}
|> Repo.insert!()
```
In other words, when you find yourself wanting to work only with a subset of the data, then using [`put_assoc/4`](#put_assoc/4) is most likely unnecessary. Instead, you want to work on the other side of the association.
Let's see an example where using [`put_assoc/4`](#put_assoc/4) is a good fit.
#### Example: Adding tags to a post
Imagine you are receiving a set of tags you want to associate to a post. Let's imagine that those tags exist upfront and are all persisted to the database. Imagine we get the data in this format:
```
params = %{"title" => "new post", "tags" => ["learner"]}
```
Now, since the tags already exist, we will bring all of them from the database and put them directly in the post:
```
tags = Repo.all(from t in Tag, where: t.name in ^params["tags"])
post
|> Repo.preload(:tags)
|> Ecto.Changeset.cast(params, [:title]) # No need to allow :tags as we put them directly
|> Ecto.Changeset.put_assoc(:tags, tags) # Explicitly set the tags
```
Since in this case we always require the user to pass all tags directly, using [`put_assoc/4`](#put_assoc/4) is a great fit. It will automatically remove any tag not given and properly associate all of the given tags with the post.
Furthermore, since the tag information is given as structs read directly from the database, Ecto will treat the data as correct and only do the minimum necessary to guarantee that posts and tags are associated, without trying to update or diff any of the fields in the tag struct.
Although it accepts an `opts` argument, there are no options currently supported by [`put_assoc/4`](#put_assoc/4).
### put\_change(changeset, key, value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1195)
```
@spec put_change(t(), atom(), term()) :: t()
```
Puts a change on the given `key` with `value`.
`key` is an atom that represents any field, embed or association in the changeset. Note the `value` is directly stored in the changeset with no validation whatsoever. For this reason, this function is meant for working with data internal to the application.
If the change is already present, it is overridden with the new value. If the change has the same value as in the changeset data, it is not added to the list of changes.
When changing embeds and associations, see [`put_assoc/4`](#put_assoc/4) for a complete reference on the accepted values.
#### Examples
```
iex> changeset = change(%Post{}, %{title: "foo"})
iex> changeset = put_change(changeset, :title, "bar")
iex> changeset.changes
%{title: "bar"}
iex> changeset = change(%Post{title: "foo"})
iex> changeset = put_change(changeset, :title, "foo")
iex> changeset.changes
%{}
```
### put\_embed(changeset, name, value, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1427)
Puts the given embed entry or entries as a change in the changeset.
This function is used to work with embeds as a whole. For embeds with cardinality one, `nil` can be used to remove the existing entry. For embeds with many entries, an empty list may be given instead.
If the embed has no changes, it will be skipped. If the embed is invalid, the changeset will be marked as invalid.
The list of supported values and their behaviour is described in [`put_assoc/4`](#put_assoc/4). If the given value is not any of values listed there, it will raise.
Although this function accepts an `opts` argument, there are no options currently supported by [`put_embed/4`](#put_embed/4).
### traverse\_errors(changeset, msg\_func)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L3036)
```
@spec traverse_errors(
t(),
(error() -> String.t()) | (t(), atom(), error() -> String.t())
) :: %{
required(atom()) => [term()]
}
```
Traverses changeset errors and applies the given function to error messages.
This function is particularly useful when associations and embeds are cast in the changeset as it will traverse all associations and embeds and place all errors in a series of nested maps.
A changeset is supplied along with a function to apply to each error message as the changeset is traversed. The error message function receives an error tuple `{msg, opts}`, for example:
```
{"should be at least %{count} characters", [count: 3, validation: :length, min: 3]}
```
#### Examples
```
iex> traverse_errors(changeset, fn {msg, opts} ->
...> Regex.replace(~r"%{(\w+)}", msg, fn _, key ->
...> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
...> end)
...> end)
%{title: ["should be at least 3 characters"]}
```
Optionally function can accept three arguments: `changeset`, `field` and error tuple `{msg, opts}`. It is useful whenever you want to extract validations rules from `changeset.validations` to build detailed error description.
### traverse\_validations(changeset, msg\_func)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L3125)
```
@spec traverse_validations(
t(),
(error() -> String.t()) | (t(), atom(), error() -> String.t())
) :: %{
required(atom()) => [term()]
}
```
Traverses changeset validations and applies the given function to validations.
This behaves the same as [`traverse_errors/2`](#traverse_errors/2), but operates on changeset validations instead of errors.
#### Examples
```
iex> traverse_validations(changeset, &(&1))
%{title: [format: ~r/pattern/, length: [min: 1, max: 20]]}
iex> traverse_validations(changeset, fn
...> {:length, opts} -> {:length, "#{Keyword.get(opts, :min, 0)}-#{Keyword.get(opts, :max, 32)}"}
...> {:format, %Regex{source: source}} -> {:format, "/#{source}/"}
...> {other, opts} -> {other, inspect(opts)}
...> end)
%{title: [format: "/pattern/", length: "1-20"]}
```
### unique\_constraint(changeset, field\_or\_fields, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2741)
```
@spec unique_constraint(t(), atom() | [atom(), ...], Keyword.t()) :: t()
```
Checks for a unique constraint in the given field or list of fields.
The unique constraint works by relying on the database to check if the unique constraint has been violated or not and, if so, Ecto converts it into a changeset error.
In order to use the uniqueness constraint, the first step is to define the unique index in a migration:
```
create unique_index(:users, [:email])
```
Now that a constraint exists, when modifying users, we could annotate the changeset with a unique constraint so Ecto knows how to convert it into an error message:
```
cast(user, params, [:email])
|> unique_constraint(:email)
```
Now, when invoking [`Ecto.Repo.insert/2`](ecto.repo#c:insert/2) or [`Ecto.Repo.update/2`](ecto.repo#c:update/2), if the email already exists, it will be converted into an error and `{:error, changeset}` returned by the repository. Note that the error will occur only after hitting the database so it will not be visible until all other validations pass.
#### Options
* `:message` - the message in case the constraint check fails, defaults to "has already been taken"
* `:name` - the constraint name. By default, the constraint name is inferred from the table + field(s). May be required explicitly for complex cases
* `:match` - how the changeset constraint name is matched against the repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` to this changeset constraint. `:prefix` matches any repo constraint which `starts_with?` `:name` to this changeset constraint.
* `:error_key` - the key to which changeset error will be added when check fails, defaults to the first field name of the given list of fields.
#### Complex constraints
Because the constraint logic is in the database, we can leverage all the database functionality when defining them. For example, let's suppose the e-mails are scoped by company id:
```
# In migration
create unique_index(:users, [:email, :company_id])
# In the changeset function
cast(user, params, [:email])
|> unique_constraint([:email, :company_id])
```
The first field name, `:email` in this case, will be used as the error key to the changeset errors keyword list. For example, the above [`unique_constraint/3`](#unique_constraint/3) would generate something like:
```
Repo.insert!(%User{email: "[email protected]", company_id: 1})
changeset = User.changeset(%User{}, %{email: "[email protected]", company_id: 1})
{:error, changeset} = Repo.insert(changeset)
changeset.errors #=> [email: {"has already been taken", []}]
```
In complex cases, instead of relying on name inference, it may be best to set the constraint name explicitly:
```
# In the migration
create unique_index(:users, [:email, :company_id], name: :users_email_company_id_index)
# In the changeset function
cast(user, params, [:email])
|> unique_constraint(:email, name: :users_email_company_id_index)
```
### Partitioning
If your table is partitioned, then your unique index might look different per partition, e.g. Postgres adds p<number> to the middle of your key, like:
```
users_p0_email_key
users_p1_email_key
...
users_p99_email_key
```
In this case you can use the name and suffix options together to match on these dynamic indexes, like:
```
cast(user, params, [:email])
|> unique_constraint(:email, name: :email_key, match: :suffix)
```
#### Case sensitivity
Unfortunately, different databases provide different guarantees when it comes to case-sensitiveness. For example, in MySQL, comparisons are case-insensitive by default. In Postgres, users can define case insensitive column by using the `:citext` type/extension. In your migration:
```
execute "CREATE EXTENSION IF NOT EXISTS citext"
create table(:users) do
...
add :email, :citext
...
end
```
If for some reason your database does not support case insensitive columns, you can explicitly downcase values before inserting/updating them:
```
cast(data, params, [:email])
|> update_change(:email, &String.downcase/1)
|> unique_constraint(:email)
```
### unsafe\_validate\_unique(changeset, fields, repo, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1870)
```
@spec unsafe_validate_unique(t(), atom() | [atom(), ...], Ecto.Repo.t(), Keyword.t()) ::
t()
```
Validates that no existing record with a different primary key has the same values for these fields.
This function exists to provide quick feedback to users of your application. It should not be relied on for any data guarantee as it has race conditions and is inherently unsafe. For example, if this check happens twice in the same time interval (because the user submitted a form twice), both checks may pass and you may end-up with duplicate entries in the database. Therefore, a [`unique_constraint/3`](#unique_constraint/3) should also be used to ensure your data won't get corrupted.
However, because constraints are only checked if all validations succeed, this function can be used as an early check to provide early feedback to users, since most conflicting data will have been inserted prior to the current validation phase.
#### Options
* `:message` - the message in case the constraint check fails, defaults to "has already been taken".
* `:match` - how the changeset constraint name is matched against the repo constraint, may be `:exact` or `:suffix`. Defaults to `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` to this changeset constraint.
* `:error_key` - the key to which changeset error will be added when check fails, defaults to the first field name of the given list of fields.
* `:prefix` - the prefix to run the query on (such as the schema path in Postgres or the database in MySQL). See [`Ecto.Repo`](ecto.repo) documentation for more information.
* `:repo_opts` - the options to pass to the [`Ecto.Repo`](ecto.repo) call.
* `:query` - the base query to use for the check. Defaults to the schema of the changeset. If the primary key is set, a clause will be added to exclude the changeset row itself from the check.
#### Examples
```
unsafe_validate_unique(changeset, :city_name, repo)
unsafe_validate_unique(changeset, [:city_name, :state_name], repo)
unsafe_validate_unique(changeset, [:city_name, :state_name], repo, message: "city must be unique within state")
unsafe_validate_unique(changeset, [:city_name, :state_name], repo, prefix: "public")
unsafe_validate_unique(changeset, [:city_name, :state_name], repo, query: from(c in City, where: is_nil(c.deleted_at)))
```
### update\_change(changeset, key, function)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1156)
```
@spec update_change(t(), atom(), (term() -> term())) :: t()
```
Updates a change.
The given `function` is invoked with the change value only if there is a change for `key`. Note that the value of the change can still be `nil` (unless the field was marked as required on [`validate_required/3`](#validate_required/3)).
#### Examples
```
iex> changeset = change(%Post{}, %{impressions: 1})
iex> changeset = update_change(changeset, :impressions, &(&1 + 1))
iex> changeset.changes.impressions
2
```
### validate\_acceptance(changeset, field, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2390)
```
@spec validate_acceptance(t(), atom(), Keyword.t()) :: t()
```
Validates the given parameter is true.
Note this validation only checks the parameter itself is true, never the field in the schema. That's because acceptance parameters do not need to be persisted, as by definition they would always be stored as `true`.
#### Options
* `:message` - the message on failure, defaults to "must be accepted"
#### Examples
```
validate_acceptance(changeset, :terms_of_service)
validate_acceptance(changeset, :rules, message: "please accept rules")
```
### validate\_change(changeset, field, validator)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1706)
```
@spec validate_change(
t(),
atom(),
(atom(), term() ->
[{atom(), String.t()} | {atom(), {String.t(), Keyword.t()}}])
) :: t()
```
Validates the given `field` change.
It invokes the `validator` function to perform the validation only if a change for the given `field` exists and the change value is not `nil`. The function must return a list of errors (with an empty list meaning no errors).
In case there's at least one error, the list of errors will be appended to the `:errors` field of the changeset and the `:valid?` flag will be set to `false`.
#### Examples
```
iex> changeset = change(%Post{}, %{title: "foo"})
iex> changeset = validate_change changeset, :title, fn :title, title ->
...> # Value must not be "foo"!
...> if title == "foo" do
...> [title: "cannot be foo"]
...> else
...> []
...> end
...> end
iex> changeset.errors
[title: {"cannot be foo", []}]
```
### validate\_change(changeset, field, metadata, validator)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1745)
```
@spec validate_change(
t(),
atom(),
term(),
(atom(), term() ->
[{atom(), String.t()} | {atom(), {String.t(), Keyword.t()}}])
) :: t()
```
Stores the validation `metadata` and validates the given `field` change.
Similar to [`validate_change/3`](#validate_change/3) but stores the validation metadata into the changeset validators. The validator metadata is often used as a reflection mechanism, to automatically generate code based on the available validations.
#### Examples
```
iex> changeset = change(%Post{}, %{title: "foo"})
iex> changeset = validate_change changeset, :title, :useless_validator, fn
...> _, _ -> []
...> end
iex> changeset.validations
[title: :useless_validator]
```
### validate\_confirmation(changeset, field, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2337)
```
@spec validate_confirmation(t(), atom(), Keyword.t()) :: t()
```
Validates that the given parameter matches its confirmation.
By calling `validate_confirmation(changeset, :email)`, this validation will check if both "email" and "email\_confirmation" in the parameter map matches. Note this validation only looks at the parameters themselves, never the fields in the schema. As such as, the "email\_confirmation" field does not need to be added as a virtual field in your schema.
Note that if the confirmation field is nil or missing, this does not add a validation error. You can specify that the confirmation parameter is required in the options (see below).
#### Options
* `:message` - the message on failure, defaults to "does not match confirmation"
* `:required` - boolean, sets whether existence of confirmation parameter is required for addition of error. Defaults to false
#### Examples
```
validate_confirmation(changeset, :email)
validate_confirmation(changeset, :password, message: "does not match password")
cast(data, params, [:password])
|> validate_confirmation(:password, message: "does not match password")
```
### validate\_exclusion(changeset, field, data, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2093)
```
@spec validate_exclusion(t(), atom(), Enum.t(), Keyword.t()) :: t()
```
Validates a change is not included in the given enumerable.
#### Options
* `:message` - the message on failure, defaults to "is reserved"
#### Examples
```
validate_exclusion(changeset, :name, ~w(admin superadmin))
```
### validate\_format(changeset, field, format, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2010)
```
@spec validate_format(t(), atom(), Regex.t(), Keyword.t()) :: t()
```
Validates a change has the given format.
The format has to be expressed as a regular expression.
#### Options
* `:message` - the message on failure, defaults to "has invalid format"
#### Examples
```
validate_format(changeset, :email, ~r/@/)
```
### validate\_inclusion(changeset, field, data, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2030)
```
@spec validate_inclusion(t(), atom(), Enum.t(), Keyword.t()) :: t()
```
Validates a change is included in the given enumerable.
#### Options
* `:message` - the message on failure, defaults to "is invalid"
#### Examples
```
validate_inclusion(changeset, :cardinal_direction, ["north", "east", "south", "west"])
validate_inclusion(changeset, :age, 0..99)
```
### validate\_length(changeset, field, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2142)
```
@spec validate_length(t(), atom(), Keyword.t()) :: t()
```
Validates a change is a string or list of the given length.
Note that the length of a string is counted in graphemes by default. If using this validation to match a character limit of a database backend, it's likely that the limit ignores graphemes and limits the number of unicode characters. Then consider using the `:count` option to limit the number of codepoints (`:codepoints`), or limit the number of bytes (`:bytes`).
#### Options
* `:is` - the length must be exactly this value
* `:min` - the length must be greater than or equal to this value
* `:max` - the length must be less than or equal to this value
* `:count` - what length to count for string, `:graphemes` (default), `:codepoints` or `:bytes`
* `:message` - the message on failure, depending on the validation, is one of:
+ for strings:
- "should be %{count} character(s)"
- "should be at least %{count} character(s)"
- "should be at most %{count} character(s)"
+ for binary:
- "should be %{count} byte(s)"
- "should be at least %{count} byte(s)"
- "should be at most %{count} byte(s)"
+ for lists:
- "should have %{count} item(s)"
- "should have at least %{count} item(s)"
- "should have at most %{count} item(s)"
#### Examples
```
validate_length(changeset, :title, min: 3)
validate_length(changeset, :title, max: 100)
validate_length(changeset, :title, min: 3, max: 100)
validate_length(changeset, :code, is: 9)
validate_length(changeset, :topics, is: 2)
validate_length(changeset, :icon, count: :bytes, max: 1024 * 16)
```
### validate\_number(changeset, field, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2229)
```
@spec validate_number(t(), atom(), Keyword.t()) :: t()
```
Validates the properties of a number.
#### Options
* `:less_than`
* `:greater_than`
* `:less_than_or_equal_to`
* `:greater_than_or_equal_to`
* `:equal_to`
* `:not_equal_to`
* `:message` - the message on failure, defaults to one of:
+ "must be less than %{number}"
+ "must be greater than %{number}"
+ "must be less than or equal to %{number}"
+ "must be greater than or equal to %{number}"
+ "must be equal to %{number}"
+ "must be not equal to %{number}"
#### Examples
```
validate_number(changeset, :count, less_than: 3)
validate_number(changeset, :pi, greater_than: 3, less_than: 4)
validate_number(changeset, :the_answer_to_life_the_universe_and_everything, equal_to: 42)
```
### validate\_required(changeset, fields, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1794)
```
@spec validate_required(t(), list() | atom(), Keyword.t()) :: t()
```
Validates that one or more fields are present in the changeset.
You can pass a single field name or a list of field names that are required.
If the value of a field is `nil` or a string made only of whitespace, the changeset is marked as invalid, the field is removed from the changeset's changes, and an error is added. An error won't be added if the field already has an error.
If a field is given to [`validate_required/3`](#validate_required/3) but it has not been passed as parameter during [`cast/3`](#cast/3) (i.e. it has not been changed), then [`validate_required/3`](#validate_required/3) will check for its current value in the data. If the data contains an non-empty value for the field, then no error is added. This allows developers to use [`validate_required/3`](#validate_required/3) to perform partial updates. For example, on `insert` all fields would be required, because their default values on the data are all `nil`, but on `update`, if you don't want to change a field that has been previously set, you are not required to pass it as a parameter, since [`validate_required/3`](#validate_required/3) won't add an error for missing changes as long as the value in the data given to the `changeset` is not empty.
Do not use this function to validate associations that are required, instead pass the `:required` option to [`cast_assoc/3`](#cast_assoc/3) or [`cast_embed/3`](#cast_embed/3).
Opposite to other validations, calling this function does not store the validation under the `changeset.validations` key. Instead, it stores all required fields under `changeset.required`.
#### Options
* `:message` - the message on failure, defaults to "can't be blank"
* `:trim` - a boolean that sets whether whitespaces are removed before running the validation on binaries/strings, defaults to true
#### Examples
```
validate_required(changeset, :title)
validate_required(changeset, [:title, :body])
```
### validate\_subset(changeset, field, data, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L2060)
```
@spec validate_subset(t(), atom(), Enum.t(), Keyword.t()) :: t()
```
Validates a change, of type enum, is a subset of the given enumerable.
This validates if a list of values belongs to the given enumerable. If you need to validate if a single value is inside the given enumerable, you should use [`validate_inclusion/4`](#validate_inclusion/4) instead.
Type of the field must be array.
#### Options
* `:message` - the message on failure, defaults to "has an invalid entry"
#### Examples
```
validate_subset(changeset, :pets, ["cat", "dog", "parrot"])
validate_subset(changeset, :lottery_numbers, 0..99)
```
### validations(changeset)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/changeset.ex#L1639)
```
@spec validations(t()) :: [{atom(), term()}]
```
Returns a keyword list of the validations for this changeset.
The keys in the list are the names of fields, and the values are a validation associated with the field. A field may occur multiple times in the list.
#### Example
```
%Post{}
|> change()
|> validate_format(:title, ~r/^\w+:\s/, message: "must start with a topic")
|> validate_length(:title, max: 100)
|> validations()
#=> [
title: {:length, [ max: 100 ]},
title: {:format, ~r/^\w+:\s/}
]
```
The following validations may be included in the result. The list is not necessarily exhaustive. For example, custom validations written by the developer will also appear in our return value.
This first group contains validations that hold a keyword list of validators. This list may also include a `:message` key.
* `{:length, [option]}`
+ `min: n`
+ `max: n`
+ `is: n`
+ `count: :graphemes | :codepoints`
* `{:number, [option]}`
+ `equal_to: n`
+ `greater_than: n`
+ `greater_than_or_equal_to: n`
+ `less_than: n`
+ `less_than_or_equal_to: n`
The other validators simply take a value:
* `{:exclusion, Enum.t}`
* `{:format, ~r/pattern/}`
* `{:inclusion, Enum.t}`
* `{:subset, Enum.t}`
Note that calling [`validate_required/3`](#validate_required/3) does not store the validation under the `changeset.validations` key (and so won't be included in the result of this function). The required fields are stored under the `changeset.required` key.
| programming_docs |
phoenix Ecto.Query.API Ecto.Query.API
===============
Lists all functions allowed in the query API.
* Comparison operators: `==`, `!=`, `<=`, `>=`, `<`, `>`
* Arithmetic operators: `+`, `-`, `*`, `/`
* Boolean operators: `and`, `or`, `not`
* Inclusion operator: [`in/2`](#in/2)
* Subquery operators: `any`, `all` and `exists`
* Search functions: [`like/2`](#like/2) and [`ilike/2`](#ilike/2)
* Null check functions: [`is_nil/1`](#is_nil/1)
* Aggregates: [`count/0`](#count/0), [`count/1`](#count/1), [`avg/1`](#avg/1), [`sum/1`](#sum/1), [`min/1`](#min/1), [`max/1`](#max/1)
* Date/time intervals: [`datetime_add/3`](#datetime_add/3), [`date_add/3`](#date_add/3), [`from_now/2`](#from_now/2), [`ago/2`](#ago/2)
* Inside select: [`struct/2`](#struct/2), [`map/2`](#map/2), [`merge/2`](#merge/2) and literals (map, tuples, lists, etc)
* General: [`fragment/1`](#fragment/1), [`field/2`](#field/2), [`type/2`](#type/2), [`as/1`](#as/1), [`parent_as/1`](#parent_as/1)
Note the functions in this module exist for documentation purposes and one should never need to invoke them directly. Furthermore, it is possible to define your own macros and use them in Ecto queries (see docs for [`fragment/1`](#fragment/1)).
Intervals
----------
Ecto supports following values for `interval` option: `"year"`, `"month"`, `"week"`, `"day"`, `"hour"`, `"minute"`, `"second"`, `"millisecond"`, and `"microsecond"`.
[`Date`](https://hexdocs.pm/elixir/Date.html)/[`Time`](https://hexdocs.pm/elixir/Time.html) functions like [`datetime_add/3`](#datetime_add/3), [`date_add/3`](#date_add/3), [`from_now/2`](#from_now/2), [`ago/2`](#ago/2) take `interval` as an argument.
Window API
-----------
Ecto also supports many of the windows functions found in SQL databases. See [`Ecto.Query.WindowAPI`](ecto.query.windowapi) for more information.
About the arithmetic operators
-------------------------------
The Ecto implementation of these operators provide only a thin layer above the adapters. So if your adapter allows you to use them in a certain way (like adding a date and an interval in PostgreSQL), it should work just fine in Ecto queries.
Summary
========
Functions
----------
[left != right](#!=/2) Binary `!=` operation.
[left \* right](#*/2) Binary `*` operation.
[left + right](#+/2) Binary `+` operation.
[left - right](#-/2) Binary `-` operation.
[left / right](#//2) Binary `/` operation.
[left < right](#%3C/2) Binary `<` operation.
[left <= right](#%3C=/2) Binary `<=` operation.
[left == right](#==/2) Binary `==` operation.
[left > right](#%3E/2) Binary `>` operation.
[left >= right](#%3E=/2) Binary `>=` operation.
[ago(count, interval)](#ago/2) Subtracts the given interval from the current time in UTC.
[all(subquery)](#all/1) Evaluates whether all values returned from the provided subquery match in a comparison operation.
[left and right](#and/2) Binary `and` operation.
[any(subquery)](#any/1) Tests whether one or more values returned from the provided subquery match in a comparison operation.
[as(binding)](#as/1) Refer to a named atom binding.
[avg(value)](#avg/1) Calculates the average for the given entry.
[coalesce(value, expr)](#coalesce/2) Takes whichever value is not null, or null if they both are.
[count()](#count/0) Counts the entries in the table.
[count(value)](#count/1) Counts the given entry.
[count(value, atom)](#count/2) Counts the distinct values in given entry.
[date\_add(date, count, interval)](#date_add/3) Adds a given interval to a date.
[datetime\_add(datetime, count, interval)](#datetime_add/3) Adds a given interval to a datetime.
[exists(subquery)](#exists/1) Evaluates to true if the provided subquery returns 1 or more rows.
[field(source, field)](#field/2) Allows a field to be dynamically accessed.
[filter(value, filter)](#filter/2) Applies the given expression as a FILTER clause against an aggregate. This is currently only supported by Postgres.
[fragment(fragments)](#fragment/1) Send fragments directly to the database.
[from\_now(count, interval)](#from_now/2) Adds the given interval to the current time in UTC.
[ilike(string, search)](#ilike/2) Searches for `search` in `string` in a case insensitive fashion.
[left in right](#in/2) Checks if the left-value is included in the right one.
[is\_nil(value)](#is_nil/1) Checks if the given value is nil.
[json\_extract\_path(json\_field, path)](#json_extract_path/2) Returns value from the `json_field` pointed to by `path`.
[like(string, search)](#like/2) Searches for `search` in `string`.
[map(source, fields)](#map/2) Used in `select` to specify which fields should be returned as a map.
[max(value)](#max/1) Calculates the maximum for the given entry.
[merge(left\_map, right\_map)](#merge/2) Merges the map on the right over the map on the left.
[min(value)](#min/1) Calculates the minimum for the given entry.
[not value](#not/1) Unary `not` operation.
[left or right](#or/2) Binary `or` operation.
[parent\_as(binding)](#parent_as/1) Refer to a named atom binding in the parent query.
[struct(source, fields)](#struct/2) Used in `select` to specify which struct fields should be returned.
[sum(value)](#sum/1) Calculates the sum for the given entry.
[type(interpolated\_value, type)](#type/2) Casts the given value to the given type at the database level.
Functions
==========
### left != right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L56)
Binary `!=` operation.
### left \* right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L91)
Binary `*` operation.
### left + right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L81)
Binary `+` operation.
### left - right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L86)
Binary `-` operation.
### left / right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L96)
Binary `/` operation.
### left < right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L71)
Binary `<` operation.
### left <= right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L61)
Binary `<=` operation.
### left == right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L51)
Binary `==` operation.
### left > right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L76)
Binary `>` operation.
### left >= right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L66)
Binary `>=` operation.
### ago(count, interval)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L370)
Subtracts the given interval from the current time in UTC.
The current time in UTC is retrieved from Elixir and not from the database.
See [Intervals](#module-intervals) for supported `interval` values.
#### Examples
```
from p in Post, where: p.published_at > ago(3, "month")
```
### all(subquery)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L205)
Evaluates whether all values returned from the provided subquery match in a comparison operation.
```
from p in Post, where: p.visits >= all(
from(p in Post, select: avg(p.visits), group_by: [p.category_id])
)
```
For a post to match in the above example it must be visited at least as much as the average post in all categories.
```
from p in Post, where: p.visits == all(
from(p in Post, select: max(p.visits))
)
```
The above example matches all the posts which are tied for being the most visited.
Both `any` and `all` must be given a subquery as an argument, and they must be used on the right hand side of a comparison. Both can be used with every comparison operator: `==`, `!=`, `>`, `>=`, `<`, `<=`.
### left and right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L101)
Binary `and` operation.
### any(subquery)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L185)
Tests whether one or more values returned from the provided subquery match in a comparison operation.
```
from p in Product, where: p.id == any(
from(li in LineItem, select: [li.product_id], where: li.created_at > ^since and li.qty >= 10)
)
```
A product matches in the above example if a line item was created since the provided date where the customer purchased at least 10 units.
Both `any` and `all` must be given a subquery as an argument, and they must be used on the right hand side of a comparison. Both can be used with every comparison operator: `==`, `!=`, `>`, `>=`, `<`, `<=`.
### as(binding)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L674)
Refer to a named atom binding.
See the "Named binding" section in [`Ecto.Query`](ecto.query) for more information.
### avg(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L292)
Calculates the average for the given entry.
```
from p in Payment, select: avg(p.value)
```
### coalesce(value, expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L275)
Takes whichever value is not null, or null if they both are.
In SQL, COALESCE takes any number of arguments, but in ecto it only takes two, so it must be chained to achieve the same effect.
```
from p in Payment, select: p.value |> coalesce(p.backup_value) |> coalesce(0)
```
### count()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L250)
Counts the entries in the table.
```
from p in Post, select: count()
```
### count(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L257)
Counts the given entry.
```
from p in Post, select: count(p.id)
```
### count(value, atom)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L264)
Counts the distinct values in given entry.
```
from p in Post, select: count(p.id, :distinct)
```
### date\_add(date, count, interval)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L341)
Adds a given interval to a date.
See [`datetime_add/3`](#datetime_add/3) for more information.
See [Intervals](#module-intervals) for supported `interval` values.
### datetime\_add(datetime, count, interval)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L332)
Adds a given interval to a datetime.
The first argument is a `datetime`, the second one is the count for the interval, which may be either positive or negative and the interval value:
```
# Get all items published since the last month
from p in Post, where: p.published_at >
datetime_add(^NaiveDateTime.utc_now(), -1, "month")
```
In the example above, we used [`datetime_add/3`](#datetime_add/3) to subtract one month from the current datetime and compared it with the `p.published_at`. If you want to perform operations on date, [`date_add/3`](#date_add/3) could be used.
See [Intervals](#module-intervals) for supported `interval` values.
### exists(subquery)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L170)
Evaluates to true if the provided subquery returns 1 or more rows.
```
from p in Post,
as: :post,
where:
exists(
from(
c in Comment,
where: parent_as(:post).id == c.post_id and c.replies_count > 5,
select: 1
)
)
```
This is best used in conjunction with `parent_as` to correlate the subquery with the parent query to test some condition on related rows in a different table. In the above example the query returns posts which have at least one comment that has more than 5 replies.
### field(source, field)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L466)
Allows a field to be dynamically accessed.
```
def at_least_four(doors_or_tires) do
from c in Car,
where: field(c, ^doors_or_tires) >= 4
end
```
In the example above, both `at_least_four(:doors)` and `at_least_four(:tires)` would be valid calls as the field is dynamically generated.
### filter(value, filter)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L285)
Applies the given expression as a FILTER clause against an aggregate. This is currently only supported by Postgres.
```
from p in Payment, select: filter(avg(p.value), p.value > 0 and p.value < 100)
from p in Payment, select: avg(p.value) |> filter(p.value < 0)
```
### fragment(fragments)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L453)
Send fragments directly to the database.
It is not possible to represent all possible database queries using Ecto's query syntax. When such is required, it is possible to use fragments to send any expression to the database:
```
def unpublished_by_title(title) do
from p in Post,
where: is_nil(p.published_at) and
fragment("lower(?)", p.title) == ^title
end
```
Every occurrence of the `?` character will be interpreted as a place for parameters, which must be given as additional arguments to `fragment`. If the literal character `?` is required as part of the fragment, it can be escaped with `\\?` (one escape for strings, another for fragment).
In the example above, we are using the lower procedure in the database to downcase the title column.
It is very important to keep in mind that Ecto is unable to do any type casting when fragments are used. Therefore it may be necessary to explicitly cast parameters via [`type/2`](#type/2):
```
fragment("lower(?)", p.title) == type(^title, :string)
```
#### Literals
Sometimes you need to interpolate a literal value into a fragment, instead of a parameter. For example, you may need to pass a table name or a collation, such as:
```
collation = "es_ES"
fragment("? COLLATE ?", ^name, ^collation)
```
The example above won't work because `collation` will be passed as a parameter, while it has to be a literal part of the query.
You can address this by telling Ecto that variable is a literal:
```
fragment("? COLLATE ?", ^name, literal(^collation))
```
Ecto will then escape it and make it part of the query.
>
> #### Literals and query caching
>
>
> Because literals are made part of the query, each interpolated literal will generate a separate query, with its own cache.
>
>
>
#### Defining custom functions using macros and fragment
You can add a custom Ecto query function using macros. For example to expose SQL's coalesce function you can define this macro:
```
defmodule CustomFunctions do
defmacro coalesce(left, right) do
quote do
fragment("coalesce(?, ?)", unquote(left), unquote(right))
end
end
end
```
To have coalesce/2 available, just import the module that defines it.
```
import CustomFunctions
```
The only downside is that it will show up as a fragment when inspecting the Elixir query. Other than that, it should be equivalent to a built-in Ecto query function.
#### Keyword fragments
In order to support databases that do not have string-based queries, like MongoDB, fragments also allow keywords to be given:
```
from p in Post,
where: fragment(title: ["$eq": ^some_value])
```
### from\_now(count, interval)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L356)
Adds the given interval to the current time in UTC.
The current time in UTC is retrieved from Elixir and not from the database.
See [Intervals](#module-intervals) for supported `interval` values.
#### Examples
```
from a in Account, where: a.expires_at < from_now(3, "month")
```
### ilike(string, search)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L232)
Searches for `search` in `string` in a case insensitive fashion.
```
from p in Post, where: ilike(p.body, "Chapter%")
```
Translates to the underlying SQL ILIKE query. This operation is only available on PostgreSQL.
### left in right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L149)
Checks if the left-value is included in the right one.
```
from p in Post, where: p.id in [1, 2, 3]
```
The right side may either be a list, a literal list or even a column in the database with array type:
```
from p in Post, where: "elixir" in p.tags
```
Additionally, the right side may also be a subquery:
```
from c in Comment, where: c.post_id in subquery(
from(p in Post, where: p.created_at > ^since)
)
```
### is\_nil(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L243)
Checks if the given value is nil.
```
from p in Post, where: is_nil(p.published_at)
```
To check if a given value is not nil use:
```
from p in Post, where: not is_nil(p.published_at)
```
### json\_extract\_path(json\_field, path)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L617)
Returns value from the `json_field` pointed to by `path`.
```
from(post in Post, select: json_extract_path(post.meta, ["author", "name"]))
```
The query can be also rewritten as:
```
from(post in Post, select: post.meta["author"]["name"])
```
Path elements can be integers to access values in JSON arrays:
```
from(post in Post, select: post.meta["tags"][0]["name"])
```
Any element of the path can be dynamic:
```
field = "name"
from(post in Post, select: post.meta["author"][^field])
```
#### Warning: indexes on PostgreSQL
PostgreSQL supports indexing on jsonb columns via GIN indexes. Whenever comparing the value of a jsonb field against a string or integer, Ecto will use the containement operator @> which is optimized. You can even use the more efficient `jsonb_path_ops` GIN index variant. For more information, consult PostgreSQL's docs on [JSON indexing](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING).
#### Warning: return types
The underlying data in the JSON column is returned without any additional decoding. This means "null" JSON values are not the same as SQL's "null". For example, the `Repo.all` operation below returns an empty list because `p.meta["author"]` returns JSON's null and therefore `is_nil` does not succeed:
```
Repo.insert!(%Post{meta: %{author: nil}})
Repo.all(from(post in Post, where: is_nil(p.meta["author"])))
```
Similarly, other types, such as datetimes, are returned as strings. This means conditions like `post.meta["published_at"] > from_now(-1, "day")` may return incorrect results or fail as the underlying database tries to compare incompatible types. You can, however, use [`type/2`](#type/2) to force the types on the database level.
### like(string, search)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L222)
Searches for `search` in `string`.
```
from p in Post, where: like(p.body, "Chapter%")
```
Translates to the underlying SQL LIKE query, therefore its behaviour is dependent on the database. In particular, PostgreSQL will do a case-sensitive operation, while the majority of other databases will be case-insensitive. For performing a case-insensitive `like` in PostgreSQL, see [`ilike/2`](#ilike/2).
You should be very careful when allowing user sent data to be used as part of LIKE query, since they allow to perform [LIKE-injections](https://githubengineering.com/like-injection/).
### map(source, fields)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L557)
Used in `select` to specify which fields should be returned as a map.
For example, if you don't need all fields to be returned or neither need a struct, you can use [`map/2`](#map/2) to achieve both:
```
from p in Post,
select: map(p, [:title, :body])
```
[`map/2`](#map/2) can also be used to dynamically select fields:
```
fields = [:title, :body]
from p in Post, select: map(p, ^fields)
```
If the same source is selected multiple times with a `map`, the fields are merged in order to avoid fetching multiple copies from the database. In other words, the expression below:
```
from(city in City, preload: :country,
select: {map(city, [:country_id]), map(city, [:name])})
```
is expanded to:
```
from(city in City, preload: :country,
select: {map(city, [:country_id, :name]), map(city, [:country_id, :name])})
```
For preloads, the selected fields may be specified from the parent:
```
from(city in City, preload: :country,
select: map(city, [:country_id, :name, country: [:id, :population]]))
```
It's also possible to select a struct from one source but only a subset of fields from one of its associations:
```
from(city in City, preload: :country,
select: %{city | country: map(country: [:id, :population])})
```
**IMPORTANT**: When filtering fields for associations, you MUST include the foreign keys used in the relationship, otherwise Ecto will be unable to find associated records.
### max(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L313)
Calculates the maximum for the given entry.
```
from p in Payment, select: max(p.value)
```
### merge(left\_map, right\_map)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L571)
Merges the map on the right over the map on the left.
If the map on the left side is a struct, Ecto will check all of the field on the right previously exist on the left before merging.
```
from(city in City, select: merge(city, %{virtual_field: "some_value"}))
```
This function is primarily used by [`Ecto.Query.select_merge/3`](ecto.query#select_merge/3) to merge different select clauses.
### min(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L306)
Calculates the minimum for the given entry.
```
from p in Payment, select: min(p.value)
```
### not value[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L131)
Unary `not` operation.
It is used to negate values in `:where`. It is also used to match the assert the opposite of [`in/2`](#in/2), [`is_nil/1`](#is_nil/1), and [`exists/1`](#exists/1). For example:
```
from p in Post, where: p.id not in [1, 2, 3]
from p in Post, where: not is_nil(p.title)
# Retrieve all the posts that doesn't have comments.
from p in Post,
as: :post,
where:
not exists(
from(
c in Comment,
where: parent_as(:post).id == c.post_id
)
)
```
### left or right[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L106)
Binary `or` operation.
### parent\_as(binding)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L683)
Refer to a named atom binding in the parent query.
This is available only inside subqueries.
See the "Named binding" section in [`Ecto.Query`](ecto.query) for more information.
### struct(source, fields)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L514)
Used in `select` to specify which struct fields should be returned.
For example, if you don't need all fields to be returned as part of a struct, you can filter it to include only certain fields by using [`struct/2`](#struct/2):
```
from p in Post,
select: struct(p, [:title, :body])
```
[`struct/2`](#struct/2) can also be used to dynamically select fields:
```
fields = [:title, :body]
from p in Post, select: struct(p, ^fields)
```
As a convenience, `select` allows developers to take fields without an explicit call to [`struct/2`](#struct/2):
```
from p in Post, select: [:title, :body]
```
Or even dynamically:
```
fields = [:title, :body]
from p in Post, select: ^fields
```
For preloads, the selected fields may be specified from the parent:
```
from(city in City, preload: :country,
select: struct(city, [:country_id, :name, country: [:id, :population]]))
```
If the same source is selected multiple times with a `struct`, the fields are merged in order to avoid fetching multiple copies from the database. In other words, the expression below:
```
from(city in City, preload: :country,
select: {struct(city, [:country_id]), struct(city, [:name])})
```
is expanded to:
```
from(city in City, preload: :country,
select: {struct(city, [:country_id, :name]), struct(city, [:country_id, :name])})
```
**IMPORTANT**: When filtering fields for associations, you MUST include the foreign keys used in the relationship, otherwise Ecto will be unable to find associated records.
### sum(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L299)
Calculates the sum for the given entry.
```
from p in Payment, select: sum(p.value)
```
### type(interpolated\_value, type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/api.ex#L667)
Casts the given value to the given type at the database level.
Most of the times, Ecto is able to proper cast interpolated values due to its type checking mechanism. In some situations though, you may want to tell Ecto that a parameter has some particular type:
```
type(^title, :string)
```
It is also possible to say the type must match the same of a column:
```
type(^title, p.title)
```
Or a parameterized type, which must be previously initialized with [`Ecto.ParameterizedType.init/2`](ecto.parameterizedtype#init/2):
```
@my_enum Ecto.ParameterizedType.init(Ecto.Enum, values: [:foo, :bar, :baz])
type(^title, ^@my_enum)
```
Ecto will ensure `^title` is cast to the given type and enforce such type at the database level. If the value is returned in a `select`, Ecto will also enforce the proper type throughout.
When performing arithmetic operations, [`type/2`](#type/2) can be used to cast all the parameters in the operation to the same type:
```
from p in Post,
select: type(p.visits + ^a_float + ^a_integer, :decimal)
```
Inside `select`, [`type/2`](#type/2) can also be used to cast fragments:
```
type(fragment("NOW"), :naive_datetime)
```
Or to type fields from schemaless queries:
```
from p in "posts", select: type(p.cost, :decimal)
```
Or to type aggregation results:
```
from p in Post, select: type(avg(p.cost), :integer)
from p in Post, select: type(filter(avg(p.cost), p.cost > 0), :integer)
```
Or to type comparison expression results:
```
from p in Post, select: type(coalesce(p.cost, 0), :integer)
```
| programming_docs |
phoenix Ecto.Adapter.Storage behaviour Ecto.Adapter.Storage behaviour
===============================
Specifies the adapter storage API.
Summary
========
Callbacks
----------
[storage\_down(options)](#c:storage_down/1) Drops the storage given by options.
[storage\_status(options)](#c:storage_status/1) Returns the status of a storage given by options.
[storage\_up(options)](#c:storage_up/1) Creates the storage given by options.
Callbacks
==========
### storage\_down(options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/storage.ex#L38)
```
@callback storage_down(options :: Keyword.t()) ::
:ok | {:error, :already_down} | {:error, term()}
```
Drops the storage given by options.
Returns `:ok` if it was dropped successfully.
Returns `{:error, :already_down}` if the storage has already been dropped or `{:error, term}` in case anything else goes wrong.
#### Examples
```
storage_down(username: "postgres",
database: "ecto_test",
hostname: "localhost")
```
### storage\_status(options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/storage.ex#L52)
```
@callback storage_status(options :: Keyword.t()) :: :up | :down | {:error, term()}
```
Returns the status of a storage given by options.
Can return `:up`, `:down` or `{:error, term}` in case anything goes wrong.
#### Examples
```
storage_status(username: "postgres",
database: "ecto_test",
hostname: "localhost")
```
### storage\_up(options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/storage.ex#L21)
```
@callback storage_up(options :: Keyword.t()) ::
:ok | {:error, :already_up} | {:error, term()}
```
Creates the storage given by options.
Returns `:ok` if it was created successfully.
Returns `{:error, :already_up}` if the storage has already been created or `{:error, term}` in case anything else goes wrong.
#### Examples
```
storage_up(username: "postgres",
database: "ecto_test",
hostname: "localhost")
```
phoenix Testing with Ecto Testing with Ecto
==================
After you have successfully set up your database connection with Ecto for your application, its usage for your tests requires further changes, especially if you want to leverage the [Ecto SQL Sandbox](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html) that allows you to run tests that talk to the database concurrently.
Create the `config/test.exs` file or append the following content:
```
use Mix.Config
config :my_app, MyApp.Repo,
username: "postgres",
password: "postgres",
database: "myapp_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
```
Thereby, we configure the database connection for our test setup. In this case, we use a Postgres database and set it up to use the sandbox pool that will wrap each test in a transaction.
Make sure we import the configuration for the test environment at the very bottom of `config/config.exs`:
```
import_config "#{Mix.env()}.exs"
```
We also need to add an explicit statement to the end of `test/test_helper.exs` about the `sandbox` mode:
```
Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, :manual)
```
Lastly, you need to establish the database connection ahead of your tests. You can enable it either for all of your test cases by extending the [`ExUnit`](https://hexdocs.pm/ex_unit/ExUnit.html) template or by setting it up individually for each test. Let's start with the former and place it to the `test/support/repo_case.ex`:
```
defmodule MyApp.RepoCase do
use ExUnit.CaseTemplate
using do
quote do
alias MyApp.Repo
import Ecto
import Ecto.Query
import MyApp.RepoCase
# and any other stuff
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()})
end
:ok
end
end
```
The case template above brings [`Ecto`](ecto) and [`Ecto.Query`](ecto.query) functions into your tests and checks-out a database connection. It also enables a shared sandbox connection mode in case the test is not running asynchronously. See [`Ecto.Adapters.SQL.Sandbox`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html) for more information.
To add `test/support/` folder for compilation in test environment we need to update `mix.exs` configuration
```
def project do
[
# ...
elixirc_paths: elixirc_paths(Mix.env())
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
```
And then in each test that uses the repository:
```
defmodule MyApp.MyTest do
use MyApp.RepoCase
# Tests etc...
end
```
In case you don't want to define a "case template", you can checkout on each individual case:
```
defmodule MyApp.MyTest do
use ExUnit.Case
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)
end
# Tests etc...
end
```
For convenience reasons, you can also define `aliases` to automatically set up your database at the execution of your tests. Change the following content in your `mix.exs`.
```
def project do
[app: :my_app,
...
aliases: aliases()]
end
defp aliases do
[ ...
"test": ["ecto.create --quiet", "ecto.migrate", "test"]
]
end
```
[← Previous Page Embedded Schemas](embedded-schemas) [Next Page → Aggregates and subqueries](aggregates-and-subqueries)
phoenix mix ecto.gen.repo mix ecto.gen.repo
==================
Generates a new repository.
The repository will be placed in the `lib` directory.
Examples
---------
```
$ mix ecto.gen.repo -r Custom.Repo
```
This generator will automatically open the config/config.exs after generation if you have `ECTO_EDITOR` set in your environment variable.
Command line options
---------------------
* `-r`, `--repo` - the repo to generate
phoenix Ecto.Type behaviour Ecto.Type behaviour
====================
Defines functions and the [`Ecto.Type`](ecto.type#content) behaviour for implementing basic custom types.
Ecto provides two types of custom types: basic types and parameterized types. Basic types are simple, requiring only four callbacks to be implemented, and are enough for most occasions. Parameterized types can be customized on the field definition and provide a wide variety of callbacks.
The definition of basic custom types and all of their callbacks are available in this module. You can learn more about parameterized types in [`Ecto.ParameterizedType`](ecto.parameterizedtype). If in doubt, prefer to use basic custom types and rely on parameterized types if you need the extra functionality.
Example
--------
Imagine you want to store a URI struct as part of a schema in a url-shortening service. There isn't an Ecto field type to support that value at runtime therefore a custom one is needed.
You also want to query not only by the full url, but for example by specific ports used. This is possible by putting the URI data into a map field instead of just storing the plain string representation.
```
from s in ShortUrl,
where: fragment("?->>? ILIKE ?", s.original_url, "port", "443")
```
So the custom type does need to handle the conversion from external data to runtime data ([`cast/1`](#c:cast/1)) as well as transforming that runtime data into the `:map` Ecto native type and back ([`dump/1`](#c:dump/1) and [`load/1`](#c:load/1)).
```
defmodule EctoURI do
use Ecto.Type
def type, do: :map
# Provide custom casting rules.
# Cast strings into the URI struct to be used at runtime
def cast(uri) when is_binary(uri) do
{:ok, URI.parse(uri)}
end
# Accept casting of URI structs as well
def cast(%URI{} = uri), do: {:ok, uri}
# Everything else is a failure though
def cast(_), do: :error
# When loading data from the database, as long as it's a map,
# we just put the data back into a URI struct to be stored in
# the loaded schema struct.
def load(data) when is_map(data) do
data =
for {key, val} <- data do
{String.to_existing_atom(key), val}
end
{:ok, struct!(URI, data)}
end
# When dumping data to the database, we *expect* a URI struct
# but any value could be inserted into the schema struct at runtime,
# so we need to guard against them.
def dump(%URI{} = uri), do: {:ok, Map.from_struct(uri)}
def dump(_), do: :error
end
```
Now we can use our new field type above in our schemas:
```
defmodule ShortUrl do
use Ecto.Schema
schema "posts" do
field :original_url, EctoURI
end
end
```
Note: `nil` values are always bypassed and cannot be handled by custom types.
Custom types and primary keys
------------------------------
Remember that, if you change the type of your primary keys, you will also need to change the type of all associations that point to said primary key.
Imagine you want to encode the ID so they cannot enumerate the content in your application. An Ecto type could handle the conversion between the encoded version of the id and its representation in the database. For the sake of simplicity, we'll use base64 encoding in this example:
```
defmodule EncodedId do
use Ecto.Type
def type, do: :id
def cast(id) when is_integer(id) do
{:ok, encode_id(id)}
end
def cast(_), do: :error
def dump(id) when is_binary(id) do
Base.decode64(id)
end
def load(id) when is_integer(id) do
{:ok, encode_id(id)}
end
defp encode_id(id) do
id
|> Integer.to_string()
|> Base.encode64
end
end
```
To use it as the type for the id in our schema, we can use the `@primary_key` module attribute:
```
defmodule BlogPost do
use Ecto.Schema
@primary_key {:id, EncodedId, autogenerate: true}
schema "posts" do
belongs_to :author, Author, type: EncodedId
field :content, :string
end
end
defmodule Author do
use Ecto.Schema
@primary_key {:id, EncodedId, autogenerate: true}
schema "authors" do
field :name, :string
has_many :posts, BlogPost
end
end
```
The `@primary_key` attribute will tell ecto which type to use for the id.
Note the `type: EncodedId` option given to `belongs_to` in the `BlogPost` schema. By default, Ecto will treat associations as if their keys were `:integer`s. Our primary keys are a custom type, so when Ecto tries to cast those ids, it will fail.
Alternatively, you can set `@foreign_key_type EncodedId` after `@primary_key` to automatically configure the type of all `belongs_to` fields.
Summary
========
Types
------
[base()](#t:base/0) [composite()](#t:composite/0) [custom()](#t:custom/0) Custom types are represented by user-defined modules.
[primitive()](#t:primitive/0) Primitive Ecto types (handled by Ecto).
[t()](#t:t/0) An Ecto type, primitive or custom.
Callbacks
----------
[autogenerate()](#c:autogenerate/0) Generates a loaded version of the data.
[cast(term)](#c:cast/1) Casts the given input to the custom type.
[dump(term)](#c:dump/1) Dumps the given term into an Ecto native type.
[embed\_as(format)](#c:embed_as/1) Dictates how the type should be treated inside embeds.
[equal?(term, term)](#c:equal?/2) Checks if two terms are semantically equal.
[load(term)](#c:load/1) Loads the given term into a custom type.
[type()](#c:type/0) Returns the underlying schema type for the custom type.
Functions
----------
[base?(atom)](#base?/1) Checks if the given atom can be used as base type.
[cast(type, value)](#cast/2) Casts a value to the given type.
[composite?(atom)](#composite?/1) Checks if the given atom can be used as composite type.
[dump(type, value, dumper \\ &dump/2)](#dump/3) Dumps a value to the given type.
[embed\_as(base, format)](#embed_as/2) Gets how the type is treated inside embeds for the given format.
[embedded\_dump(type, value, format)](#embedded_dump/3) Dumps the `value` for `type` considering it will be embedded in `format`.
[embedded\_load(type, value, format)](#embedded_load/3) Loads the `value` for `type` considering it was embedded in `format`.
[equal?(type, term1, term2)](#equal?/3) Checks if two terms are equal.
[include?(type, term, collection)](#include?/3) Checks if `collection` includes a `term`.
[load(type, value, loader \\ &load/2)](#load/3) Loads a value with the given type.
[match?(schema\_type, query\_type)](#match?/2) Checks if a given type matches with a primitive type that can be found in queries.
[primitive?(base)](#primitive?/1) Checks if we have a primitive type.
[type(type)](#type/1) Retrieves the underlying schema type for the given, possibly custom, type.
Types
======
### base()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L179)
```
@type base() ::
:integer
| :float
| :boolean
| :string
| :map
| :binary
| :decimal
| :id
| :binary_id
| :utc_datetime
| :naive_datetime
| :date
| :time
| :any
| :utc_datetime_usec
| :naive_datetime_usec
| :time_usec
```
### composite()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L184)
```
@type composite() :: {:array, t()} | {:map, t()} | private_composite()
```
### custom()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L177)
```
@type custom() :: module() | {:parameterized, module(), term()}
```
Custom types are represented by user-defined modules.
### primitive()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L174)
```
@type primitive() :: base() | composite()
```
Primitive Ecto types (handled by Ecto).
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L171)
```
@type t() :: primitive() | custom()
```
An Ecto type, primitive or custom.
Callbacks
==========
### autogenerate()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L270)
```
@callback autogenerate() :: term()
```
Generates a loaded version of the data.
This is callback is invoked when a custom type is given to `field` with the `:autogenerate` flag.
### cast(term)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L229)
```
@callback cast(term()) :: {:ok, term()} | :error | {:error, keyword()}
```
Casts the given input to the custom type.
This callback is called on external input and can return any type, as long as the `dump/1` function is able to convert the returned value into an Ecto native type. There are two situations where this callback is called:
1. When casting values by [`Ecto.Changeset`](ecto.changeset)
2. When passing arguments to [`Ecto.Query`](ecto.query)
You can return `:error` if the given term cannot be cast. A default error message of "is invalid" will be added to the changeset.
You may also return `{:error, keyword()}` to customize the changeset error message and its metadata. Passing a `:message` key, will override the default message. It is not possible to override the `:type` key.
For `{:array, CustomType}` or `{:map, CustomType}` the returned keyword list will be erased and the default error will be shown.
### dump(term)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L247)
```
@callback dump(term()) :: {:ok, term()} | :error
```
Dumps the given term into an Ecto native type.
This callback is called with any term that was stored in the struct and it needs to validate them and convert it to an Ecto native type.
### embed\_as(format)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L262)
```
@callback embed_as(format :: atom()) :: :self | :dump
```
Dictates how the type should be treated inside embeds.
By default, the type is sent as itself, without calling dumping to keep the higher level representation. But it can be set to `:dump` so that it is dumped before being encoded.
### equal?(term, term)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L252)
```
@callback equal?(term(), term()) :: boolean()
```
Checks if two terms are semantically equal.
### load(term)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L239)
```
@callback load(term()) :: {:ok, term()} | :error
```
Loads the given term into a custom type.
This callback is called when loading data from the database and receives an Ecto native type. It can return any type, as long as the `dump/1` function is able to convert the returned value back into an Ecto native type.
### type()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L204)
```
@callback type() :: t()
```
Returns the underlying schema type for the custom type.
For example, if you want to provide your own date structures, the type function should return `:date`.
Note this function is not required to return Ecto primitive types, the type is only required to be known by the adapter.
Functions
==========
### base?(atom)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L320)
```
@spec base?(atom()) :: boolean()
```
Checks if the given atom can be used as base type.
```
iex> base?(:string)
true
iex> base?(:array)
false
iex> base?(Custom)
false
```
### cast(type, value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L737)
```
@spec cast(t(), term()) :: {:ok, term()} | {:error, keyword()} | :error
```
Casts a value to the given type.
[`cast/2`](#cast/2) is used by the finder queries and changesets to cast outside values to specific types.
Note that nil can be cast to all primitive types as data stores allow nil to be set on any column.
NaN and infinite decimals are not supported, use custom types instead.
```
iex> cast(:any, "whatever")
{:ok, "whatever"}
iex> cast(:any, nil)
{:ok, nil}
iex> cast(:string, nil)
{:ok, nil}
iex> cast(:integer, 1)
{:ok, 1}
iex> cast(:integer, "1")
{:ok, 1}
iex> cast(:integer, "1.0")
:error
iex> cast(:id, 1)
{:ok, 1}
iex> cast(:id, "1")
{:ok, 1}
iex> cast(:id, "1.0")
:error
iex> cast(:float, 1.0)
{:ok, 1.0}
iex> cast(:float, 1)
{:ok, 1.0}
iex> cast(:float, "1")
{:ok, 1.0}
iex> cast(:float, "1.0")
{:ok, 1.0}
iex> cast(:float, "1-foo")
:error
iex> cast(:boolean, true)
{:ok, true}
iex> cast(:boolean, false)
{:ok, false}
iex> cast(:boolean, "1")
{:ok, true}
iex> cast(:boolean, "0")
{:ok, false}
iex> cast(:boolean, "whatever")
:error
iex> cast(:string, "beef")
{:ok, "beef"}
iex> cast(:binary, "beef")
{:ok, "beef"}
iex> cast(:decimal, Decimal.new("1.0"))
{:ok, Decimal.new("1.0")}
iex> cast(:decimal, "1.0bad")
:error
iex> cast({:array, :integer}, [1, 2, 3])
{:ok, [1, 2, 3]}
iex> cast({:array, :integer}, ["1", "2", "3"])
{:ok, [1, 2, 3]}
iex> cast({:array, :string}, [1, 2, 3])
:error
iex> cast(:string, [1, 2, 3])
:error
```
### composite?(atom)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L306)
```
@spec composite?(atom()) :: boolean()
```
Checks if the given atom can be used as composite type.
```
iex> composite?(:array)
true
iex> composite?(:string)
false
```
### dump(type, value, dumper \\ &dump/2)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L470)
```
@spec dump(t(), term(), (t(), term() -> {:ok, term()} | :error)) ::
{:ok, term()} | :error
```
Dumps a value to the given type.
Opposite to casting, dumping requires the returned value to be a valid Ecto type, as it will be sent to the underlying data store.
```
iex> dump(:string, nil)
{:ok, nil}
iex> dump(:string, "foo")
{:ok, "foo"}
iex> dump(:integer, 1)
{:ok, 1}
iex> dump(:integer, "10")
:error
iex> dump(:binary, "foo")
{:ok, "foo"}
iex> dump(:binary, 1)
:error
iex> dump({:array, :integer}, [1, 2, 3])
{:ok, [1, 2, 3]}
iex> dump({:array, :integer}, [1, "2", 3])
:error
iex> dump({:array, :binary}, ["1", "2", "3"])
{:ok, ["1", "2", "3"]}
```
### embed\_as(base, format)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L327)
Gets how the type is treated inside embeds for the given format.
See [`embed_as/1`](#c:embed_as/1).
### embedded\_dump(type, value, format)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L341)
Dumps the `value` for `type` considering it will be embedded in `format`.
#### Examples
```
iex> Ecto.Type.embedded_dump(:decimal, Decimal.new("1"), :json)
{:ok, Decimal.new("1")}
```
### embedded\_load(type, value, format)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L357)
Loads the `value` for `type` considering it was embedded in `format`.
#### Examples
```
iex> Ecto.Type.embedded_load(:decimal, "1", :json)
{:ok, Decimal.new("1")}
```
### equal?(type, term1, term2)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L1122)
```
@spec equal?(t(), term(), term()) :: boolean()
```
Checks if two terms are equal.
Depending on the given `type` performs a structural or semantical comparison.
#### Examples
```
iex> equal?(:integer, 1, 1)
true
iex> equal?(:decimal, Decimal.new("1"), Decimal.new("1.00"))
true
```
### include?(type, term, collection)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L1146)
```
@spec include?(t(), term(), Enum.t()) :: boolean()
```
Checks if `collection` includes a `term`.
Depending on the given `type` performs a structural or semantical comparison.
#### Examples
```
iex> include?(:integer, 1, 1..3)
true
iex> include?(:decimal, Decimal.new("1"), [Decimal.new("1.00"), Decimal.new("2.00")])
true
```
### load(type, value, loader \\ &load/2)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L571)
```
@spec load(t(), term(), (t(), term() -> {:ok, term()} | :error)) ::
{:ok, term()} | :error
```
Loads a value with the given type.
```
iex> load(:string, nil)
{:ok, nil}
iex> load(:string, "foo")
{:ok, "foo"}
iex> load(:integer, 1)
{:ok, 1}
iex> load(:integer, "10")
:error
```
### match?(schema\_type, query\_type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L417)
```
@spec match?(t(), primitive()) :: boolean()
```
Checks if a given type matches with a primitive type that can be found in queries.
```
iex> match?(:string, :any)
true
iex> match?(:any, :string)
true
iex> match?(:string, :string)
true
iex> match?({:array, :string}, {:array, :any})
true
iex> match?(Ecto.UUID, :uuid)
true
iex> match?(Ecto.UUID, :string)
false
```
### primitive?(base)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L291)
```
@spec primitive?(t()) :: boolean()
```
Checks if we have a primitive type.
```
iex> primitive?(:string)
true
iex> primitive?(Another)
false
iex> primitive?({:array, :string})
true
iex> primitive?({:array, Another})
true
```
### type(type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/type.ex#L388)
```
@spec type(t()) :: t()
```
Retrieves the underlying schema type for the given, possibly custom, type.
```
iex> type(:string)
:string
iex> type(Ecto.UUID)
:uuid
iex> type({:array, :string})
{:array, :string}
iex> type({:array, Ecto.UUID})
{:array, :uuid}
iex> type({:map, Ecto.UUID})
{:map, :uuid}
```
| programming_docs |
phoenix Replicas and dynamic repositories Replicas and dynamic repositories
==================================
When applications reach a certain scale, a single database may not be enough to sustain the required throughput. In such scenarios, it is very common to introduce read replicas: all write operations are sent to the primary database and most of the read operations are performed against the replicas. The credentials of the primary and replica databases are typically known upfront by the time the code is compiled.
In other cases, you may need a single Ecto repository to interact with different database instances which are not known upfront. For instance, you may need to communicate with hundreds of databases very sporadically, so instead of opening up a connection to each of those hundreds of databases when your application starts, you want to quickly start a connection, perform some queries, and then shut down, while still leveraging Ecto's APIs as a whole.
This guide will cover how to tackle both approaches.
Primary and Replicas
---------------------
Since the credentials of the primary and replicas databases are known upfront, adding support for primary and replica databases in your Ecto application is relatively straightforward. Imagine you have a `MyApp.Repo` and you want to add four read replicas. This could be done in three steps.
First, define the primary and replicas repositories in `lib/my_app/repo.ex`:
```
defmodule MyApp.Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
@replicas [
MyApp.Repo.Replica1,
MyApp.Repo.Replica2,
MyApp.Repo.Replica3,
MyApp.Repo.Replica4
]
def replica do
Enum.random(@replicas)
end
for repo <- @replicas do
defmodule repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres,
read_only: true
end
end
end
```
The code above defines a regular `MyApp.Repo` and four replicas, called `MyApp.Repo.Replica1` up to `MyApp.Repo.Replica4`. We pass the `:read_only` option to the replica repositories, so operations such as `insert`, `update` and friends are not made accessible. We also define a function called `replica` with the purpose of returning a random replica.
Next we need to make sure both primary and replicas are configured properly in your `config/config.exs` files. In development and test, you can likely use the same database credentials for all repositories, all pointing to the same database address:
```
replicas = [
MyApp.Repo,
MyApp.Repo.Replica1,
MyApp.Repo.Replica2,
MyApp.Repo.Replica3,
MyApp.Repo.Replica4
]
for repo <- replicas do
config :my_app, repo,
username: "postgres",
password: "postgres",
database: "my_app_prod",
hostname: "localhost",
pool_size: 10
end
```
In production, you want each database to connect to a different hostname:
```
repos = %{
MyApp.Repo => "prod-primary",
MyApp.Repo.Replica1 => "prod-replica-1",
MyApp.Repo.Replica2 => "prod-replica-2",
MyApp.Repo.Replica3 => "prod-replica-3",
MyApp.Repo.Replica4 => "prod-replica-4"
}
for {repo, hostname} <- repos do
config :my_app, repo,
username: "postgres",
password: "postgres",
database: "my_app_prod",
hostname: hostname,
pool_size: 10
end
```
Finally, make sure to start all repositories in your supervision tree:
```
children = [
MyApp.Repo,
MyApp.Repo.Replica1,
MyApp.Repo.Replica2,
MyApp.Repo.Replica3,
MyApp.Repo.Replica4
]
```
Now that all repositories are configured, we can safely use them in your application code. Every time you are performing a read operation, you can call the `replica/0` function that we have added to return a random replica we will send the query to:
```
MyApp.Repo.replica().all(query)
```
And now you are ready to work with primary and replicas, no hacks or complex dependencies required!
Testing replicas
-----------------
While all of the work we have done so far should fully work in development and production, it may not be enough for tests. Most developers testing Ecto applications are using a sandbox, such as the [Ecto SQL Sandbox](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html).
When using a sandbox, each of your tests run in an isolated and independent transaction. Once the test is done, the transaction is rolled back. Which means we can trivially revert all of the changes done in a test in a very performant way.
Unfortunately, even if you configure your primary and replicas to have the same credentials and point to the same hostname, each Ecto repository will open up their own pool of database connections. This means that, once you move to a primary + replicas setup, a simple test like this one won't pass:
```
user = Repo.insert!(%User{name: "jane doe"})
assert Repo.replica().get!(User, user.id)
```
That's because `Repo.insert!` will write to one database connection and the repository returned by `Repo.replica()` will perform the read in another connection. Since the write is done in a transaction, its contents won't be available to other connections until the transaction commits, which will never happen for test connections.
There are two options to tackle this problem: one is to change replicas and the other is to use dynamic repos.
### A custom `replica` definition
One simple solution to the problem above is to use a custom `replica` implementation during tests that always return the primary repository, like this:
```
if Mix.env() == :test do
def replica, do: __MODULE__
else
def replica, do: Enum.random(@replicas)
end
```
Now during tests, the replica will always return the repository primary repository itself. While this approach works fine, it has the downside that, if you accidentally invoke a write function in a replica, the test will pass, since the `replica` function is returning the primary repo, while the code will fail in production.
### Using `:default_dynamic_repo`
Another approach to testing is to set the `:default_dynamic_repo` option when defining the repository. Let's see what we mean by that.
When you list a repository in your supervision tree, such as `MyApp.Repo`, behind the scenes it will start a supervision tree with a process named `MyApp.Repo`. By default, the process has the same name as the repository module itself. Now every time you invoke a function in `MyApp.Repo`, such as `MyApp.Repo.insert/2`, Ecto will use the connection pool from the process named `MyApp.Repo`.
From v3.0, Ecto has the ability to start multiple processes from the same repository. The only requirement is that they must have different process names, like this:
```
children = [
MyApp.Repo,
{MyApp.Repo, name: :another_instance_of_repo}
]
```
While the particular example doesn't make much sense (we will cover an actual use case for this feature next), the idea is that now you have two repositories running: one is named `MyApp.Repo` and the other one is named `:another_instance_of_repo`. Each of those processes have their own connection pool. You can tell Ecto which process you want to use in your repo operations by calling:
```
MyApp.Repo.put_dynamic_repo(MyApp.Repo)
MyApp.Repo.put_dynamic_repo(:another_instance_of_repo)
```
Once you call `MyApp.Repo.put_dynamic_repo(name)`, all invocations made on `MyApp.Repo` will use the connection pool denoted by `name`.
How can this help with our replica tests? If we look back to the supervision tree we defined earlier in this guide, you will find this:
```
children = [
MyApp.Repo,
MyApp.Repo.Replica1,
MyApp.Repo.Replica2,
MyApp.Repo.Replica3,
MyApp.Repo.Replica4
]
```
We are starting five different repositories and five different connection pools. Since we want the replica repositories to use the `MyApp.Repo`, we can achieve this by doing the following on the setup of each test:
```
@replicas [
MyApp.Repo.Replica1,
MyApp.Repo.Replica2,
MyApp.Repo.Replica3,
MyApp.Repo.Replica4
]
setup do
for replica <- @replicas do
replica.put_dynamic_repo(MyApp.Repo)
end
:ok
end
```
Note `put_dynamic_repo` is per process. So every time you spawn a new process, the `dynamic_repo` value will reset to its default until you call `put_dynamic_repo` again.
Luckily, there is even a better way! We can pass a `:default_dynamic_repo` option when we define the repository. In this case, we want to set the `:default_dynamic_repo` to `MyApp.Repo` only during the test environment. In your `lib/my_app/repo.ex`, do this:
```
for repo <- @replicas do
default_dynamic_repo =
if Mix.env() == :test do
MyApp.Repo
else
repo
end
defmodule repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres,
read_only: true,
default_dynamic_repo: default_dynamic_repo
end
end
```
And now your tests should work as before, while still being able to detect if you accidentally perform a write operation in a replica.
Dynamic repositories
---------------------
At this point, we have learned that Ecto allows you to start multiple connections based on the same repository. This is typically useful when you have to connect multiple databases or perform short-lived database connections.
For example, you can start a repository with a given set of credentials dynamically, like this:
```
MyApp.Repo.start_link(
name: :some_client,
hostname: "client.example.com",
username: "...",
password: "...",
pool_size: 1
)
```
In other words, `start_link` accepts the same options as the database configuration. Now let's do a query on the dynamically started repository. If you attempt to simply perform `MyApp.Repo.all(Post)`, it may fail, as by default it will try to use a process named `MyApp.Repo`, which may or may not be running. So don't forget to call `put_dynamic_repo/1` before:
```
MyApp.Repo.put_dynamic_repo(:some_client)
MyApp.Repo.all(Post)
```
Ecto also allows you to start a repository with no name (just like that famous horse). In such cases, you need to explicitly pass `name: nil` and match on the result of `MyApp.Repo.start_link/1` to retrieve the PID, which should be given to `put_dynamic_repo`. Let's also use this opportunity and perform proper database clean-up, by shutting up the new repository and reverting the value of `put_dynamic_repo`:
```
default_dynamic_repo = MyApp.Repo.get_dynamic_repo()
{:ok, repo} =
MyApp.Repo.start_link(
name: nil,
hostname: "client.example.com",
username: "...",
password: "...",
pool_size: 1
)
try do
MyApp.Repo.put_dynamic_repo(repo)
MyApp.Repo.all(Post)
after
MyApp.Repo.put_dynamic_repo(default_dynamic_repo)
Supervisor.stop(repo)
end
```
We can encapsulate all of this in a function too, which you could define in your repository:
```
defmodule MyApp.Repo do
use Ecto.Repo, ...
def with_dynamic_repo(credentials, callback) do
default_dynamic_repo = get_dynamic_repo()
start_opts = [name: nil, pool_size: 1] ++ credentials
{:ok, repo} = MyApp.Repo.start_link(start_opts)
try do
MyApp.Repo.put_dynamic_repo(repo)
callback.()
after
MyApp.Repo.put_dynamic_repo(default_dynamic_repo)
Supervisor.stop(repo)
end
end
end
```
And now use it as:
```
credentials = [
hostname: "client.example.com",
username: "...",
password: "..."
]
MyApp.Repo.with_dynamic_repo(credentials, fn ->
MyApp.Repo.all(Post)
end)
```
And that's it! Now you can have dynamic connections, all properly encapsulated in a single function and built on top of the dynamic repo API.
[← Previous Page Polymorphic associations with many to many](polymorphic-associations-with-many-to-many) [Next Page → Schemaless queries](schemaless-queries)
phoenix Ecto.CastError exception Ecto.CastError exception
=========================
Raised when a changeset can't cast a value.
phoenix Ecto.Association.BelongsTo Ecto.Association.BelongsTo
===========================
The association struct for a `belongs_to` association.
Its fields are:
* `cardinality` - The association cardinality
* `field` - The name of the association field on the schema
* `owner` - The schema where the association was defined
* `owner_key` - The key on the `owner` schema used for the association
* `related` - The schema that is associated
* `related_key` - The key on the `related` schema used for the association
* `queryable` - The real query to use for querying association
* `defaults` - Default fields used when building the association
* `relationship` - The relationship to the specified schema, default `:parent`
* `on_replace` - The action taken on associations when schema is replaced
phoenix mix ecto.create mix ecto.create
================
Create the storage for the given repository.
The repositories to create are the ones specified under the `:ecto_repos` option in the current app configuration. However, if the `-r` option is given, it replaces the `:ecto_repos` config.
Since Ecto tasks can only be executed once, if you need to create multiple repositories, set `:ecto_repos` accordingly or pass the `-r` flag multiple times.
Examples
---------
```
$ mix ecto.create
$ mix ecto.create -r Custom.Repo
```
Command line options
---------------------
* `-r`, `--repo` - the repo to create
* `--quiet` - do not log output
* `--no-compile` - do not compile before creating
* `--no-deps-check` - do not compile before creating
phoenix Ecto.NoPrimaryKeyValueError exception Ecto.NoPrimaryKeyValueError exception
======================================
Raised at runtime when an operation that requires a primary key is invoked with a schema missing value for its primary key
phoenix Getting Started Getting Started
================
This guide is an introduction to [Ecto](https://github.com/elixir-lang/ecto), the database wrapper and query generator for Elixir. Ecto provides a standardized API and a set of abstractions for talking to all the different kinds of databases, so that Elixir developers can query whatever database they're using by employing similar constructs.
In this guide, we're going to learn some basics about Ecto, such as creating, reading, updating and destroying records from a PostgreSQL database. If you want to see the code from this guide, you can view it [at ecto/examples/friends on GitHub](https://github.com/elixir-lang/ecto/tree/master/examples/friends).
**This guide will require you to have setup PostgreSQL beforehand.**
Adding Ecto to an application
------------------------------
To start off with, we'll generate a new Elixir application by running this command:
```
mix new friends --sup
```
The `--sup` option ensures that this application has [a supervision tree](https://elixir-lang.org/getting-started/mix-otp/supervisor-and-application.html), which we'll need for Ecto a little later on.
To add Ecto to this application, there are a few steps that we need to take. The first step will be adding Ecto and a driver called Postgrex to our `mix.exs` file, which we'll do by changing the `deps` definition in that file to this:
```
defp deps do
[
{:ecto_sql, "~> 3.0"},
{:postgrex, ">= 0.0.0"}
]
end
```
Ecto provides the common querying API, but we need the Postgrex driver installed too, as that is what Ecto uses to speak in terms a PostgreSQL database can understand. Ecto talks to its own `Ecto.Adapters.Postgres` module, which then in turn talks to the `postgrex` package to talk to PostgreSQL.
To install these dependencies, we will run this command:
```
mix deps.get
```
The Postgrex application will receive queries from Ecto and execute them against our database. If we didn't do this step, we wouldn't be able to do any querying at all.
That's the first two steps taken now. We have installed Ecto and Postgrex as dependencies of our application. We now need to setup some configuration for Ecto so that we can perform actions on a database from within the application's code.
We can set up this configuration by running this command:
```
mix ecto.gen.repo -r Friends.Repo
```
This command will generate the configuration required to connect to a database. The first bit of configuration is in `config/config.exs`:
```
config :friends, Friends.Repo,
database: "friends",
username: "user",
password: "pass",
hostname: "localhost"
```
**NOTE**: Your PostgreSQL database may be setup to
* not require a username and password. If the above configuration doesn't work, try removing the username and password fields, or setting them both to "postgres".
* be running on a non-standard port. The default port is `5432`. You can specify your specific port by adding it to the config: e.g. `port: 15432`.
This configures how Ecto will connect to our database, called "friends". Specifically, it configures a "repo". More information about [Ecto.Repo can be found in its documentation](ecto.repo).
The `Friends.Repo` module is defined in `lib/friends/repo.ex` by our [`mix ecto.gen.repo`](mix.tasks.ecto.gen.repo) command:
```
defmodule Friends.Repo do
use Ecto.Repo,
otp_app: :friends,
adapter: Ecto.Adapters.Postgres
end
```
This module is what we'll be using to query our database shortly. It uses the [`Ecto.Repo`](ecto.repo) module, and the `otp_app` tells Ecto which Elixir application it can look for database configuration in. In this case, we've specified that it is the `:friends` application where Ecto can find that configuration and so Ecto will use the configuration that was set up in `config/config.exs`. Finally, we configure the database `:adapter` to Postgres.
The final piece of configuration is to setup the `Friends.Repo` as a supervisor within the application's supervision tree, which we can do in `lib/friends/application.ex`, inside the `start/2` function:
```
def start(_type, _args) do
children = [
Friends.Repo,
]
...
```
This piece of configuration will start the Ecto process which receives and executes our application's queries. Without it, we wouldn't be able to query the database at all!
There's one final bit of configuration that we'll need to add ourselves, since the generator does not add it. Underneath the configuration in `config/config.exs`, add this line:
```
config :friends, ecto_repos: [Friends.Repo]
```
This tells our application about the repo, which will allow us to run commands such as [`mix ecto.create`](mix.tasks.ecto.create) very soon.
We've now configured our application so that it's able to make queries to our database. Let's now create our database, add a table to it, and then perform some queries.
Setting up the database
------------------------
To be able to query a database, it first needs to exist. We can create the database with this command:
```
mix ecto.create
```
If the database has been created successfully, then you will see this message:
```
The database for Friends.Repo has been created.
```
**NOTE:** If you get an error, you should try changing your configuration in `config/config.exs`, as it may be an authentication error.
A database by itself isn't very queryable, so we will need to create a table within that database. To do that, we'll use what's referred to as a *migration*. If you've come from Active Record (or similar), you will have seen these before. A migration is a single step in the process of constructing your database.
Let's create a migration now with this command:
```
mix ecto.gen.migration create_people
```
This command will generate a brand new migration file in `priv/repo/migrations`, which is empty by default:
```
defmodule Friends.Repo.Migrations.CreatePeople do
use Ecto.Migration
def change do
end
end
```
Let's add some code to this migration to create a new table called "people", with a few columns in it:
```
defmodule Friends.Repo.Migrations.CreatePeople do
use Ecto.Migration
def change do
create table(:people) do
add :first_name, :string
add :last_name, :string
add :age, :integer
end
end
end
```
This new code will tell Ecto to create a new table called `people`, and add three new fields: `first_name`, `last_name` and `age` to that table. The types of these fields are `string` and `integer`. (The different types that Ecto supports are covered in the [Ecto.Schema](ecto.schema) documentation.)
**NOTE**: The naming convention for tables in Ecto databases is to use a pluralized name.
To run this migration and create the `people` table in our database, we will run this command:
```
mix ecto.migrate
```
If we found out that we made a mistake in this migration, we could run `mix ecto.rollback` to undo the changes in the migration. We could then fix the changes in the migration and run `mix ecto.migrate` again. If we ran `mix ecto.rollback` now, it would delete the table that we just created.
We now have a table created in our database. The next step that we'll need to do is to create the schema.
Creating the schema
--------------------
The schema is an Elixir representation of data from our database. Schemas are commonly associated with a database table, however they can be associated with a database view as well.
Let's create the schema within our application at `lib/friends/person.ex`:
```
defmodule Friends.Person do
use Ecto.Schema
schema "people" do
field :first_name, :string
field :last_name, :string
field :age, :integer
end
end
```
This defines the schema from the database that this schema maps to. In this case, we're telling Ecto that the `Friends.Person` schema maps to the `people` table in the database, and the `first_name`, `last_name` and `age` fields in that table. The second argument passed to `field` tells Ecto how we want the information from the database to be represented in our schema.
We've called this schema `Person` because the naming convention in Ecto for schemas is a singularized name.
We can play around with this schema in an IEx session by starting one up with `iex -S mix` and then running this code in it:
```
person = %Friends.Person{}
```
This code will give us a new `Friends.Person` struct, which will have `nil` values for all the fields. We can set values on these fields by generating a new struct:
```
person = %Friends.Person{age: 28}
```
Or with syntax like this:
```
person = %{person | age: 28}
```
We can retrieve values using this syntax:
```
person.age # => 28
```
Let's take a look at how we can insert data into the database.
Inserting data
---------------
We can insert a new record into our `people` table with this code:
```
person = %Friends.Person{}
Friends.Repo.insert(person)
```
To insert the data into our database, we call `insert` on `Friends.Repo`, which is the module that uses Ecto to talk to our database. This function tells Ecto that we want to insert a new `Friends.Person` record into the database corresponding with `Friends.Repo`. The `person` struct here represents the data that we want to insert into the database.
A successful insertion will return a tuple, like so:
```
{:ok,
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: nil,
first_name: nil, id: 1, last_name: nil}}
```
The `:ok` atom can be used for pattern matching purposes to ensure that the insertion succeeds. A situation where the insertion may not succeed is if you have a constraint on the database itself. For instance, if the database had a unique constraint on a field called `email` so that an email can only be used for one person record, then the insertion would fail.
You may wish to pattern match on the tuple in order to refer to the record inserted into the database:
```
{:ok, person} = Friends.Repo.insert person
```
Validating changes
-------------------
In Ecto, you may wish to validate changes before they go to the database. For instance, you may wish that a person has both a first name and a last name before a record can be entered into the database. For this, Ecto has [*changesets*](ecto.changeset).
Let's add a changeset to our `Friends.Person` module inside `lib/friends/person.ex` now:
```
def changeset(person, params \\ %{}) do
person
|> Ecto.Changeset.cast(params, [:first_name, :last_name, :age])
|> Ecto.Changeset.validate_required([:first_name, :last_name])
end
```
This changeset takes a `person` and a set of params, which are to be the changes to apply to this person. The `changeset` function first casts the `first_name`, `last_name` and `age` keys from the parameters passed in to the changeset. Casting tells the changeset what parameters are allowed to be passed through in this changeset, and anything not in the list will be ignored.
On the next line, we call `validate_required` which says that, for this changeset, we expect `first_name` and `last_name` to have values specified. Let's use this changeset to attempt to create a new record without a `first_name` and `last_name`:
```
person = %Friends.Person{}
changeset = Friends.Person.changeset(person, %{})
Friends.Repo.insert(changeset)
```
On the first line here, we get a struct from the `Friends.Person` module. We know what that does, because we saw it not too long ago. On the second line we do something brand new: we define a changeset. This changeset says that on the specified `person` object, we're looking to make some changes. In this case, we're not looking to change anything at all.
On the final line, rather than inserting the `person`, we insert the `changeset`. The `changeset` knows about the `person`, the changes and the validation rules that must be met before the data can be entered into the database. When this third line runs, we'll see this:
```
{:error,
#Ecto.Changeset<action: :insert, changes: %{},
errors: [first_name: "can't be blank", last_name: "can't be blank"],
data: #Friends.Person<>, valid?: false>}
```
Just like the last time we did an insertion, this returns a tuple. This time however, the first element in the tuple is `:error`, which indicates something bad happened. The specifics of what happened are included in the changeset which is returned. We can access these by doing some pattern matching:
```
{:error, changeset} = Friends.Repo.insert(changeset)
```
Then we can get to the errors by doing `changeset.errors`:
```
[first_name: {"can't be blank", [validation: :required]}, last_name: {"can't be blank", [validation: :required]}]
```
And we can ask the changeset itself if it is valid, even before doing an insertion:
```
changeset.valid?
#=> false
```
Since this changeset has errors, no new record was inserted into the `people` table.
Let's try now with some valid data.
```
person = %Friends.Person{}
changeset = Friends.Person.changeset(person, %{first_name: "Ryan", last_name: "Bigg"})
```
We start out here with a normal `Friends.Person` struct. We then create a changeset for that `person` which has a `first_name` and a `last_name` parameter specified. At this point, we can ask the changeset if it has errors:
```
changeset.errors
#=> []
```
And we can ask if it's valid or not:
```
changeset.valid?
#=> true
```
The changeset does not have errors, and is valid. Therefore if we try to insert this changeset it will work:
```
Friends.Repo.insert(changeset)
#=> {:ok,
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: nil,
first_name: "Ryan", id: 3, last_name: "Bigg"}}
```
Due to `Friends.Repo.insert` returning a tuple, we can use a `case` to determine different code paths depending on what happens:
```
case Friends.Repo.insert(changeset) do
{:ok, person} ->
# do something with person
{:error, changeset} ->
# do something with changeset
end
```
**NOTE:** `changeset.valid?` will not check constraints (such as `uniqueness_constraint`). For that, you will need to attempt to do an insertion and check for errors from the database. It's for this reason it's best practice to try inserting data and validate the returned tuple from `Friends.Repo.insert` to get the correct errors, as prior to insertion the changeset will only contain validation errors from the application itself.
If the insertion of the changeset succeeds, then you can do whatever you wish with the `person` returned in that result. If it fails, then you have access to the changeset and its errors. In the failure case, you may wish to present these errors to the end user. The errors in the changeset are a keyword list that looks like this:
```
[first_name: {"can't be blank", [validation: :required]},
last_name: {"can't be blank", [validation: :required]}]
```
The first element of the tuple is the validation message, and the second element is a keyword list of options for the validation message. Imagine that we had a field called `bio` that we were validating, and that field has to be longer than 15 characters. This is what would be returned:
```
[first_name: {"can't be blank", [validation: :required]},
last_name: {"can't be blank", [validation: :required]},
bio: {"should be at least %{count} character(s)", [count: 15, validation: :length, kind: :min, type: :string]}]
```
To display these error messages in a human friendly way, we can use [`Ecto.Changeset.traverse_errors/2`](ecto.changeset#traverse_errors/2):
```
traverse_errors(changeset, fn {msg, opts} ->
Enum.reduce(opts, msg, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
```
This will return the following for the errors shown above:
```
%{
first_name: ["can't be blank"],
last_name: ["can't be blank"],
bio: ["should be at least 15 character(s)"],
}
```
One more final thing to mention here: you can trigger an exception to be thrown by using `Friends.Repo.insert!/2`. If a changeset is invalid, you will see an [`Ecto.InvalidChangesetError`](ecto.invalidchangeseterror) exception. Here's a quick example of that:
```
Friends.Repo.insert! Friends.Person.changeset(%Friends.Person{}, %{first_name: "Ryan"})
** (Ecto.InvalidChangesetError) could not perform insert because changeset is invalid.
Errors
%{last_name: [{"can't be blank", [validation: :required]}]}
Applied changes
%{first_name: "Ryan"}
Params
%{"first_name" => "Ryan"}
Changeset
#Ecto.Changeset<
action: :insert,
changes: %{first_name: "Ryan"},
errors: [last_name: {"can't be blank", [validation: :required]}],
data: #Friends.Person<>,
valid?: false
>
(ecto) lib/ecto/repo/schema.ex:257: Ecto.Repo.Schema.insert!/4
```
This exception shows us the changes from the changeset, and how the changeset is invalid. This can be useful if you want to insert a bunch of data and then have an exception raised if that data is not inserted correctly at all.
Now that we've covered inserting data into the database, let's look at how we can pull that data back out.
Our first queries
------------------
Querying a database requires two steps in Ecto. First, we must construct the query and then we must execute that query against the database by passing the query to the repository. Before we do this, let's re-create the database for our app and setup some test data. To re-create the database, we'll run these commands:
```
mix ecto.drop
mix ecto.create
mix ecto.migrate
```
Then to create the test data, we'll run this in an `iex -S mix` session:
```
people = [
%Friends.Person{first_name: "Ryan", last_name: "Bigg", age: 28},
%Friends.Person{first_name: "John", last_name: "Smith", age: 27},
%Friends.Person{first_name: "Jane", last_name: "Smith", age: 26},
]
Enum.each(people, fn (person) -> Friends.Repo.insert(person) end)
```
This code will create three new people in our database, Ryan, John and Jane. Note here that we could've used a changeset to validate the data going into the database, but the choice was made not to use one.
We'll be querying for these people in this section. Let's jump in!
### Fetching a single record
Let's start off with fetching just one record from our `people` table:
```
Friends.Person |> Ecto.Query.first
```
That code will generate an [`Ecto.Query`](ecto.query), which will be this:
```
#Ecto.Query<from p0 in Friends.Person, order_by: [asc: p0.id], limit: 1>
```
The code between the angle brackets `<...>` here shows the Ecto query which has been constructed. We could construct this query ourselves with almost exactly the same syntax:
```
require Ecto.Query
Ecto.Query.from p in Friends.Person, order_by: [asc: p.id], limit: 1
```
We need to `require Ecto.Query` here to enable the macros from that module. Then it's a matter of calling the `from` function from [`Ecto.Query`](ecto.query) and passing in the code from between the angle brackets. As we can see here, `Ecto.Query.first` saves us from having to specify the `order` and `limit` for the query.
To execute the query that we've just constructed, we can call `Friends.Repo.one`:
```
Friends.Person |> Ecto.Query.first |> Friends.Repo.one
```
The `one` function retrieves just one record from our database and returns a new struct from the `Friends.Person` module:
```
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 28,
first_name: "Ryan", id: 1, last_name: "Bigg"}
```
Similar to `first`, there is also `last`:
```
Friends.Person |> Ecto.Query.last |> Friends.Repo.one
#=> %Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 26,
first_name: "Jane", id: 3, last_name: "Smith"}
```
The `Ecto.Repo.one` function will only return a struct if there is one record in the result from the database. If there is more than one record returned, an [`Ecto.MultipleResultsError`](ecto.multipleresultserror) exception will be thrown. Some code that would cause that issue to happen is:
```
Friends.Person |> Friends.Repo.one
```
We've left out the `Ecto.Query.first` here, and so there is no `limit` or `order` clause applied to the executed query. We'll see the executed query in the debug log:
```
[timestamp] [debug] SELECT p0."id", p0."first_name", p0."last_name", p0."age" FROM "people" AS p0 [] OK query=1.8ms
```
Then immediately after that, we will see the [`Ecto.MultipleResultsError`](ecto.multipleresultserror) exception:
```
** (Ecto.MultipleResultsError) expected at most one result but got 3 in query:
from p in Friends.Person
lib/ecto/repo/queryable.ex:67: Ecto.Repo.Queryable.one/4
```
This happens because Ecto doesn't know what one record out of all the records returned that we want. Ecto will only return a result if we are explicit in our querying about which result we want.
If there is no record which matches the query, `one` will return `nil`.
### Fetching all records
To fetch all records from the schema, Ecto provides the `all` function:
```
Friends.Person |> Friends.Repo.all
```
This will return a `Friends.Person` struct representation of all the records that currently exist within our `people` table:
```
[%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 28,
first_name: "Ryan", id: 1, last_name: "Bigg"},
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 27,
first_name: "John", id: 2, last_name: "Smith"},
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 26,
first_name: "Jane", id: 3, last_name: "Smith"}]
```
### Fetch a single record based on ID
To fetch a record based on its ID, you use the `get` function:
```
Friends.Person |> Friends.Repo.get(1)
#=> %Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 28,
first_name: "Ryan", id: 1, last_name: "Bigg"}
```
### Fetch a single record based on a specific attribute
If we want to get a record based on something other than the `id` attribute, we can use `get_by`:
```
Friends.Person |> Friends.Repo.get_by(first_name: "Ryan")
#=> %Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 28,
first_name: "Ryan", id: 1, last_name: "Bigg"}
```
### Filtering results
If we want to get multiple records matching a specific attribute, we can use `where`:
```
Friends.Person |> Ecto.Query.where(last_name: "Smith") |> Friends.Repo.all
```
```
[%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 27,
first_name: "John", id: 2, last_name: "Smith"},
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 26,
first_name: "Jane", id: 3, last_name: "Smith"}]
```
If we leave off the `Friends.Repo.all` on the end of this, we will see the query Ecto generates:
```
#Ecto.Query<from p in Friends.Person, where: p.last_name == "Smith">
```
We can also use this query syntax to fetch these same records:
```
Ecto.Query.from(p in Friends.Person, where: p.last_name == "Smith") |> Friends.Repo.all
```
One important thing to note with both query syntaxes is that they require variables to be pinned, using the pin operator (`^`). Otherwise, this happens:
```
last_name = "Smith"
Friends.Person |> Ecto.Query.where(last_name: last_name) |> Friends.Repo.all
```
```
** (Ecto.Query.CompileError) unbound variable `last_name` in query. If you are attempting to interpolate a value, use ^var
(ecto) expanding macro: Ecto.Query.where/2
iex:15: (file)
(elixir) expanding macro: Kernel.|>/2
iex:15: (file)
```
The same will happen in the longer query syntax too:
```
Ecto.Query.from(p in Friends.Person, where: p.last_name == last_name) |> Friends.Repo.all
```
```
** (Ecto.Query.CompileError) unbound variable `last_name` in query. If you are attempting to interpolate a value, use ^var
(ecto) expanding macro: Ecto.Query.where/3
iex:15: (file)
(ecto) expanding macro: Ecto.Query.from/2
iex:15: (file)
(elixir) expanding macro: Kernel.|>/2
iex:15: (file)
```
To get around this, we use the pin operator (`^`):
```
last_name = "Smith"
Friends.Person |> Ecto.Query.where(last_name: ^last_name) |> Friends.Repo.all
```
Or:
```
last_name = "Smith"
Ecto.Query.from(p in Friends.Person, where: p.last_name == ^last_name) |> Friends.Repo.all
```
The pin operator instructs the query builder to use parameterized SQL queries protecting against SQL injection.
### Composing Ecto queries
Ecto queries don't have to be built in one spot. They can be built up by calling [`Ecto.Query`](ecto.query) functions on existing queries. For instance, if we want to find all people with the last name "Smith", we can do:
```
query = Friends.Person |> Ecto.Query.where(last_name: "Smith")
```
If we want to scope this down further to only people with the first name of "Jane", we can do this:
```
query = query |> Ecto.Query.where(first_name: "Jane")
```
Our query will now have two `where` clauses in it:
```
#Ecto.Query<from p in Friends.Person, where: p.last_name == "Smith",
where: p.first_name == "Jane">
```
This can be useful if you want to do something with the first query, and then build off that query later on.
Updating records
-----------------
Updating records in Ecto requires us to first fetch a record from the database. We then create a changeset from that record and the changes we want to make to that record, and then call the `Ecto.Repo.update` function.
Let's fetch the first person from our database and change their age. First, we'll fetch the person:
```
person = Friends.Person |> Ecto.Query.first |> Friends.Repo.one
```
Next, we'll build a changeset. We need to build a changeset because if we just create a new `Friends.Person` struct with the new age, Ecto wouldn't be able to know that the age has changed without inspecting the database. Let's build that changeset:
```
changeset = Friends.Person.changeset(person, %{age: 29})
```
This changeset will inform the database that we want to update the record to have the `age` set to 29. To tell the database about the change we want to make, we run this command:
```
Friends.Repo.update(changeset)
```
Just like `Friends.Repo.insert`, `Friends.Repo.update` will return a tuple:
```
{:ok,
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 29,
first_name: "Ryan", id: 1, last_name: "Bigg"}}
```
If the changeset fails for any reason, the result of `Friends.Repo.update` will be `{:error, changeset}`. We can see this in action by passing through a blank `first_name` in our changeset's parameters:
```
changeset = Friends.Person.changeset(person, %{first_name: ""})
Friends.Repo.update(changeset)
#=> {:error,
#Ecto.Changeset<
action: :update,
changes: %{},
errors: [first_name: {"can't be blank", [validation: :required]}],
data: #Friends.Person<>,
valid?: false
>}
```
This means that you can also use a `case` statement to do different things depending on the outcome of the `update` function:
```
case Friends.Repo.update(changeset) do
{:ok, person} ->
# do something with person
{:error, changeset} ->
# do something with changeset
end
```
Similar to `insert!`, there is also `update!` which will raise an exception if the changeset is invalid:
```
changeset = Friends.Person.changeset(person, %{first_name: ""})
Friends.Repo.update! changeset
** (Ecto.InvalidChangesetError) could not perform update because changeset is invalid.
Errors
%{first_name: [{"can't be blank", [validation: :required]}]}
Applied changes
%{}
Params
%{"first_name" => ""}
Changeset
#Ecto.Changeset<
action: :update,
changes: %{},
errors: [first_name: {"can't be blank", [validation: :required]}],
data: #Friends.Person<>,
valid?: false
>
(ecto) lib/ecto/repo/schema.ex:270: Ecto.Repo.Schema.update!/4
```
Deleting records
-----------------
We've now covered creating (`insert`), reading (`get`, `get_by`, `where`) and updating records. The last thing that we'll cover in this guide is how to delete a record using Ecto.
Similar to updating, we must first fetch a record from the database and then call `Friends.Repo.delete` to delete that record:
```
person = Friends.Repo.get(Friends.Person, 1)
Friends.Repo.delete(person)
#=> {:ok,
%Friends.Person{__meta__: #Ecto.Schema.Metadata<:deleted, "people">, age: 29,
first_name: "Ryan", id: 2, last_name: "Bigg"}}
```
Similar to `insert` and `update`, `delete` returns a tuple. If the deletion succeeds, then the first element in the tuple will be `:ok`, but if it fails then it will be an `:error`.
[← Previous Page Changelog for v3.x](changelog) [Next Page → Embedded Schemas](embedded-schemas)
| programming_docs |
phoenix Ecto Ecto
=====
Ecto is split into 4 main components:
* [`Ecto.Repo`](ecto.repo) - repositories are wrappers around the data store. Via the repository, we can create, update, destroy and query existing entries. A repository needs an adapter and credentials to communicate to the database
* [`Ecto.Schema`](ecto.schema) - schemas are used to map external data into Elixir structs. We often use them to map database tables to Elixir data but they have many other use cases
* [`Ecto.Query`](ecto.query) - written in Elixir syntax, queries are used to retrieve information from a given repository. Ecto queries are secure and composable
* [`Ecto.Changeset`](ecto.changeset) - changesets provide a way for track and validate changes before they are applied to the data
In summary:
* [`Ecto.Repo`](ecto.repo) - **where** the data is
* [`Ecto.Schema`](ecto.schema) - **what** the data is
* [`Ecto.Query`](ecto.query) - **how to read** the data
* [`Ecto.Changeset`](ecto.changeset) - **how to change** the data
Besides the four components above, most developers use Ecto to interact with SQL databases, such as Postgres and MySQL via the [`ecto_sql`](https://hexdocs.pm/ecto_sql) project. `ecto_sql` provides many conveniences for working with SQL databases as well as the ability to version how your database changes through time via [database migrations](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.html#module-migrations).
If you want to quickly check a sample application using Ecto, please check the [getting started guide](getting-started) and the accompanying sample application. [Ecto's README](https://github.com/elixir-ecto/ecto) also links to other resources.
In the following sections, we will provide an overview of those components and how they interact with each other. Feel free to access their respective module documentation for more specific examples, options and configuration.
Repositories
-------------
[`Ecto.Repo`](ecto.repo) is a wrapper around the database. We can define a repository as follows:
```
defmodule Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
end
```
Where the configuration for the Repo must be in your application environment, usually defined in your `config/config.exs`:
```
config :my_app, Repo,
database: "ecto_simple",
username: "postgres",
password: "postgres",
hostname: "localhost",
# OR use a URL to connect instead
url: "postgres://postgres:postgres@localhost/ecto_simple"
```
Each repository in Ecto defines a `start_link/0` function that needs to be invoked before using the repository. In general, this function is not called directly, but used as part of your application supervision tree.
If your application was generated with a supervisor (by passing `--sup` to [`mix new`](https://hexdocs.pm/mix/Mix.Tasks.New.html)) you will have a `lib/my_app/application.ex` file containing the application start callback that defines and starts your supervisor. You just need to edit the `start/2` function to start the repo as a supervisor on your application's supervisor:
```
def start(_type, _args) do
children = [
MyApp.Repo,
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
```
Schema
-------
Schemas allow developers to define the shape of their data. Let's see an example:
```
defmodule Weather do
use Ecto.Schema
# weather is the DB table
schema "weather" do
field :city, :string
field :temp_lo, :integer
field :temp_hi, :integer
field :prcp, :float, default: 0.0
end
end
```
By defining a schema, Ecto automatically defines a struct with the schema fields:
```
iex> weather = %Weather{temp_lo: 30}
iex> weather.temp_lo
30
```
The schema also allows us to interact with a repository:
```
iex> weather = %Weather{temp_lo: 0, temp_hi: 23}
iex> Repo.insert!(weather)
%Weather{...}
```
After persisting `weather` to the database, it will return a new copy of `%Weather{}` with the primary key (the `id`) set. We can use this value to read a struct back from the repository:
```
# Get the struct back
iex> weather = Repo.get Weather, 1
%Weather{id: 1, ...}
# Delete it
iex> Repo.delete!(weather)
%Weather{...}
```
> NOTE: by using [`Ecto.Schema`](ecto.schema), an `:id` field with type `:id` (:id means :integer) is generated by default, which is the primary key of the Schema. If you want to use a different primary key, you can declare custom `@primary_key` before the `schema/2` call. Consult the [`Ecto.Schema`](ecto.schema) documentation for more information.
>
>
Notice how the storage (repository) and the data are decoupled. This provides two main benefits:
* By having structs as data, we guarantee they are light-weight, serializable structures. In many languages, the data is often represented by large, complex objects, with entwined state transactions, which makes serialization, maintenance and understanding hard;
* You do not need to define schemas in order to interact with repositories, operations like `all`, `insert_all` and so on allow developers to directly access and modify the data, keeping the database at your fingertips when necessary;
Changesets
-----------
Although in the example above we have directly inserted and deleted the struct in the repository, operations on top of schemas are done through changesets so Ecto can efficiently track changes.
Changesets allow developers to filter, cast, and validate changes before we apply them to the data. Imagine the given schema:
```
defmodule User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name
field :email
field :age, :integer
end
def changeset(user, params \\ %{}) do
user
|> cast(params, [:name, :email, :age])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> validate_inclusion(:age, 18..100)
end
end
```
The `changeset/2` function first invokes [`Ecto.Changeset.cast/4`](ecto.changeset#cast/4) with the struct, the parameters and a list of allowed fields; this returns a changeset. The parameters is a map with binary keys and values that will be cast based on the type defined on the schema.
Any parameter that was not explicitly listed in the fields list will be ignored.
After casting, the changeset is given to many `Ecto.Changeset.validate_*` functions that validate only the **changed fields**. In other words: if a field was not given as a parameter, it won't be validated at all. For example, if the params map contain only the "name" and "email" keys, the "age" validation won't run.
Once a changeset is built, it can be given to functions like `insert` and `update` in the repository that will return an `:ok` or `:error` tuple:
```
case Repo.update(changeset) do
{:ok, user} ->
# user updated
{:error, changeset} ->
# an error occurred
end
```
The benefit of having explicit changesets is that we can easily provide different changesets for different use cases. For example, one could easily provide specific changesets for registering and updating users:
```
def registration_changeset(user, params) do
# Changeset on create
end
def update_changeset(user, params) do
# Changeset on update
end
```
Changesets are also capable of transforming database constraints, like unique indexes and foreign key checks, into errors. Allowing developers to keep their database consistent while still providing proper feedback to end users. Check [`Ecto.Changeset.unique_constraint/3`](ecto.changeset#unique_constraint/3) for some examples as well as the other `_constraint` functions.
Query
------
Last but not least, Ecto allows you to write queries in Elixir and send them to the repository, which translates them to the underlying database. Let's see an example:
```
import Ecto.Query, only: [from: 2]
query = from u in User,
where: u.age > 18 or is_nil(u.email),
select: u
# Returns %User{} structs matching the query
Repo.all(query)
```
In the example above we relied on our schema but queries can also be made directly against a table by giving the table name as a string. In such cases, the data to be fetched must be explicitly outlined:
```
query = from u in "users",
where: u.age > 18 or is_nil(u.email),
select: %{name: u.name, age: u.age}
# Returns maps as defined in select
Repo.all(query)
```
Queries are defined and extended with the `from` macro. The supported keywords are:
* `:distinct`
* `:where`
* `:order_by`
* `:offset`
* `:limit`
* `:lock`
* `:group_by`
* `:having`
* `:join`
* `:select`
* `:preload`
Examples and detailed documentation for each of those are available in the [`Ecto.Query`](ecto.query) module. Functions supported in queries are listed in [`Ecto.Query.API`](ecto.query.api).
When writing a query, you are inside Ecto's query syntax. In order to access params values or invoke Elixir functions, you need to use the `^` operator, which is overloaded by Ecto:
```
def min_age(min) do
from u in User, where: u.age > ^min
end
```
Besides `Repo.all/1` which returns all entries, repositories also provide `Repo.one/1` which returns one entry or nil, `Repo.one!/1` which returns one entry or raises, `Repo.get/2` which fetches entries for a particular ID and more.
Finally, if you need an escape hatch, Ecto provides fragments (see [`Ecto.Query.API.fragment/1`](ecto.query.api#fragment/1)) to inject SQL (and non-SQL) fragments into queries. Also, most adapters provide direct APIs for queries, like `Ecto.Adapters.SQL.query/4`, allowing developers to completely bypass Ecto queries.
Other topics
-------------
### Associations
Ecto supports defining associations on schemas:
```
defmodule Post do
use Ecto.Schema
schema "posts" do
has_many :comments, Comment
end
end
defmodule Comment do
use Ecto.Schema
schema "comments" do
field :title, :string
belongs_to :post, Post
end
end
```
When an association is defined, Ecto also defines a field in the schema with the association name. By default, associations are not loaded into this field:
```
iex> post = Repo.get(Post, 42)
iex> post.comments
#Ecto.Association.NotLoaded<...>
```
However, developers can use the preload functionality in queries to automatically pre-populate the field:
```
Repo.all from p in Post, preload: [:comments]
```
Preloading can also be done with a pre-defined join value:
```
Repo.all from p in Post,
join: c in assoc(p, :comments),
where: c.votes > p.votes,
preload: [comments: c]
```
Finally, for the simple cases, preloading can also be done after a collection was fetched:
```
posts = Repo.all(Post) |> Repo.preload(:comments)
```
The [`Ecto`](ecto#content) module also provides conveniences for working with associations. For example, [`Ecto.assoc/2`](#assoc/2) returns a query with all associated data to a given struct:
```
import Ecto
# Get all comments for the given post
Repo.all assoc(post, :comments)
# Or build a query on top of the associated comments
query = from c in assoc(post, :comments), where: not is_nil(c.title)
Repo.all(query)
```
Another function in [`Ecto`](ecto#content) is [`build_assoc/3`](#build_assoc/3), which allows someone to build an associated struct with the proper fields:
```
Repo.transaction fn ->
post = Repo.insert!(%Post{title: "Hello", body: "world"})
# Build a comment from post
comment = Ecto.build_assoc(post, :comments, body: "Excellent!")
Repo.insert!(comment)
end
```
In the example above, [`Ecto.build_assoc/3`](#build_assoc/3) is equivalent to:
```
%Comment{post_id: post.id, body: "Excellent!"}
```
You can find more information about defining associations and each respective association module in [`Ecto.Schema`](ecto.schema) docs.
> NOTE: Ecto does not lazy load associations. While lazily loading associations may sound convenient at first, in the long run it becomes a source of confusion and performance issues.
>
>
### Embeds
Ecto also supports embeds. While associations keep parent and child entries in different tables, embeds stores the child along side the parent.
Databases like MongoDB have native support for embeds. Databases like PostgreSQL uses a mixture of JSONB (`embeds_one/3`) and ARRAY columns to provide this functionality.
Check [`Ecto.Schema.embeds_one/3`](ecto.schema#embeds_one/3) and [`Ecto.Schema.embeds_many/3`](ecto.schema#embeds_many/3) for more information.
### Mix tasks and generators
Ecto provides many tasks to help your workflow as well as code generators. You can find all available tasks by typing [`mix help`](https://hexdocs.pm/mix/Mix.Tasks.Help.html) inside a project with Ecto listed as a dependency.
Ecto generators will automatically open the generated files if you have `ECTO_EDITOR` set in your environment variable.
#### Repo resolution
Ecto requires developers to specify the key `:ecto_repos` in their application configuration before using tasks like `ecto.create` and `ecto.migrate`. For example:
```
config :my_app, :ecto_repos, [MyApp.Repo]
config :my_app, MyApp.Repo,
database: "ecto_simple",
username: "postgres",
password: "postgres",
hostname: "localhost"
```
Summary
========
Functions
----------
[assoc(struct\_or\_structs, assocs, opts \\ [])](#assoc/3) Builds a query for the association in the given struct or structs.
[assoc\_loaded?(list)](#assoc_loaded?/1) Checks if an association is loaded.
[build\_assoc(struct, assoc, attributes \\ %{})](#build_assoc/3) Builds a struct from the given `assoc` in `struct`.
[embedded\_dump(data, format)](#embedded_dump/2) Dumps the given struct defined by an embedded schema.
[embedded\_load(schema\_or\_types, data, format)](#embedded_load/3) Loads previously dumped `data` in the given `format` into a schema.
[get\_meta(struct, atom)](#get_meta/2) Gets the metadata from the given struct.
[primary\_key!(struct)](#primary_key!/1) Returns the schema primary keys as a keyword list.
[primary\_key(struct)](#primary_key/1) Returns the schema primary keys as a keyword list.
[put\_meta(struct, opts)](#put_meta/2) Returns a new struct with updated metadata.
Functions
==========
### assoc(struct\_or\_structs, assocs, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L510)
Builds a query for the association in the given struct or structs.
#### Examples
In the example below, we get all comments associated to the given post:
```
post = Repo.get Post, 1
Repo.all Ecto.assoc(post, :comments)
```
[`assoc/2`](#assoc/2) can also receive a list of posts, as long as the posts are not empty:
```
posts = Repo.all from p in Post, where: is_nil(p.published_at)
Repo.all Ecto.assoc(posts, :comments)
```
This function can also be used to dynamically load through associations by giving it a list. For example, to get all authors for all comments for the given posts, do:
```
posts = Repo.all from p in Post, where: is_nil(p.published_at)
Repo.all Ecto.assoc(posts, [:comments, :author])
```
#### Options
* `:prefix` - the prefix to fetch assocs from. By default, queries will use the same prefix as the first struct in the given collection. This option allows the prefix to be changed.
### assoc\_loaded?(list)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L568)
Checks if an association is loaded.
#### Examples
```
iex> post = Repo.get(Post, 1)
iex> Ecto.assoc_loaded?(post.comments)
false
iex> post = post |> Repo.preload(:comments)
iex> Ecto.assoc_loaded?(post.comments)
true
```
### build\_assoc(struct, assoc, attributes \\ %{})[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L471)
Builds a struct from the given `assoc` in `struct`.
#### Examples
If the relationship is a `has_one` or `has_many` and the primary key is set in the parent struct, the key will automatically be set in the built association:
```
iex> post = Repo.get(Post, 13)
%Post{id: 13}
iex> build_assoc(post, :comments)
%Comment{id: nil, post_id: 13}
```
Note though it doesn't happen with `belongs_to` cases, as the key is often the primary key and such is usually generated dynamically:
```
iex> comment = Repo.get(Comment, 13)
%Comment{id: 13, post_id: 25}
iex> build_assoc(comment, :post)
%Post{id: nil}
```
You can also pass the attributes, which can be a map or a keyword list, to set the struct's fields except the association key.
```
iex> build_assoc(post, :comments, text: "cool")
%Comment{id: nil, post_id: 13, text: "cool"}
iex> build_assoc(post, :comments, %{text: "cool"})
%Comment{id: nil, post_id: 13, text: "cool"}
iex> build_assoc(post, :comments, post_id: 1)
%Comment{id: nil, post_id: 13}
```
The given attributes are expected to be structured data. If you want to build an association with external data, such as a request parameters, you can use [`Ecto.Changeset.cast/3`](ecto.changeset#cast/3) after [`build_assoc/3`](#build_assoc/3):
```
parent
|> Ecto.build_assoc(:child)
|> Ecto.Changeset.cast(params, [:field1, :field2])
```
### embedded\_dump(data, format)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L696)
```
@spec embedded_dump(Ecto.Schema.t(), format :: atom()) :: map()
```
Dumps the given struct defined by an embedded schema.
This converts the given embedded schema to a map to be serialized with the given format. For example:
```
iex> Ecto.embedded_dump(%Post{}, :json)
%{title: "hello"}
```
### embedded\_load(schema\_or\_types, data, format)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L681)
```
@spec embedded_load(
module_or_map :: module() | map(),
data :: map(),
format :: atom()
) :: Ecto.Schema.t() | map()
```
Loads previously dumped `data` in the given `format` into a schema.
The first argument can be a an embedded schema module, or a map (of types) and determines the return value: a struct or a map, respectively.
The second argument `data` specifies fields and values that are to be loaded. It can be a map, a keyword list, or a `{fields, values}` tuple. Fields can be atoms or strings.
The third argument `format` is the format the data has been dumped as. For example, databases may dump embedded to `:json`, this function allows such dumped data to be put back into the schemas.
Fields that are not present in the schema (or `types` map) are ignored. If any of the values has invalid type, an error is raised.
Note that if you want to load data into a non-embedded schema that was directly persisted into a given repository, then use [`Ecto.Repo.load/2`](ecto.repo#c:load/2).
#### Examples
```
iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT users.settings FROM users", [])
iex> Enum.map(result.rows, fn [settings] -> Ecto.embedded_load(Setting, Jason.decode!(settings), :json) end)
[%Setting{...}, ...]
```
### get\_meta(struct, atom)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L576)
Gets the metadata from the given struct.
### primary\_key!(struct)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L418)
```
@spec primary_key!(Ecto.Schema.t()) :: Keyword.t()
```
Returns the schema primary keys as a keyword list.
Raises [`Ecto.NoPrimaryKeyFieldError`](ecto.noprimarykeyfielderror) if the schema has no primary key field.
### primary\_key(struct)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L405)
```
@spec primary_key(Ecto.Schema.t()) :: Keyword.t()
```
Returns the schema primary keys as a keyword list.
### put\_meta(struct, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto.ex#L600)
```
@spec put_meta(Ecto.Schema.schema(), meta) :: Ecto.Schema.schema()
when meta: [
source: Ecto.Schema.source(),
prefix: Ecto.Schema.prefix(),
context: Ecto.Schema.Metadata.context(),
state: Ecto.Schema.Metadata.state()
]
```
Returns a new struct with updated metadata.
It is possible to set:
* `:source` - changes the struct query source
* `:prefix` - changes the struct query prefix
* `:context` - changes the struct meta context
* `:state` - changes the struct state
Please refer to the [`Ecto.Schema.Metadata`](ecto.schema.metadata) module for more information.
| programming_docs |
phoenix Multi tenancy with foreign keys Multi tenancy with foreign keys
================================
In [Multi tenancy with query prefixes](multi-tenancy-with-query-prefixes), we have learned how to set up multi tenant applications by using separate query prefixes, known as DDL Schemas in PostgreSQL and MSSQL and simply a separate database in MySQL.
Each query prefix is isolated, having their own tables and data, which provides the security guarantees we need. On the other hand, such approach for multi tenancy may be too expensive, as each schema needs to be created, migrated, and versioned separately.
Therefore, some applications may prefer a cheaper mechanism for multi tenancy, by relying on foreign keys. The idea here is that most - if not all - resources in the system belong to a tenant. The tenant is typically an organization or a user and all resources have an `org_id` (or `user_id`) foreign key pointing directly to it.
In this guide, we will show how to leverage Ecto constructs to guarantee that all Ecto queries in your application are properly scoped to a chosen `org_id`.
Adding org\_id to read operations
----------------------------------
The first step in our implementation is to make the repository aware of `org_id`. We want to allow commands such as:
```
MyApp.Repo.all Post, org_id: 13
```
Where the repository will automatically scope all posts to the organization with `ID=13`. We can achieve this with the [`Ecto.Repo.prepare_query/3`](ecto.repo#c:prepare_query/3) repository callback:
```
defmodule MyApp.Repo do
use Ecto.Repo, otp_app: :my_app
require Ecto.Query
@impl true
def prepare_query(_operation, query, opts) do
cond do
opts[:skip_org_id] || opts[:schema_migration] ->
{query, opts}
org_id = opts[:org_id] ->
{Ecto.Query.where(query, org_id: ^org_id), opts}
true ->
raise "expected org_id or skip_org_id to be set"
end
end
end
```
Now we can pass `:org_id` to all READ operations, such as `get`, `get_by`, `preload`, etc and all query operations, such `all`, `update_all`, and `delete_all`. Note we have intentionally made the `:org_id` required, with the exception of two scenarios:
* if you explicitly set `:skip_org_id` to true, it won't require an `:org_id`. This reduces the odds of a developer forgetting to scope their queries, which can accidentally expose private data to other users
* if the `:schema_migration` option is set. This means the repository operation was issued by Ecto itself when migrating our database and we don't want to apply an `org_id` to them
Still, setting the `org_id` for every operation is cumbersome and error prone. We will be better served if all operations attempt to set an `org_id`.
Setting `org_id` by default
----------------------------
To make sure our read operations use the `org_id` by default, we will make two additional changes to the repository.
First, we will store the `org_id` in the process dictionary. The process dictionary is a storage that is exclusive to each process. For example, each test in your project runs in a separate process. Each request in a web application runs in a separate process too. Each of these processes have their own dictionary which we will store and read from. Let's add these functions:
```
defmodule MyApp.Repo do
...
@tenant_key {__MODULE__, :org_id}
def put_org_id(org_id) do
Process.put(@tenant_key, org_id)
end
def get_org_id() do
Process.get(@tenant_key)
end
end
```
We added two new functions. The first, `put_org_id`, stores the organization id in the process dictionary. `get_org_id` reads the value in the process dictionary.
You will want to call `put_org_id` on every process before you use the repository. For example, on every request in a web application, as soon as you read the current organization from the request parameter or the session, you should call `MyApp.Repo.put_org_id(params_org_id)`. In tests, you want to explicitly set the `put_org_id` or pass the `:org_id` option as in the previous section.
The second change we need to do is to set the `org_id` as a default option on all repository operations. The value of `org_id` will be precisely the value in the process dictionary. We can do so trivially by implementing the `default_options` callback:
```
defmodule MyApp.Repo do
...
@impl true
def default_options(_operation) do
[org_id: get_org_id()]
end
end
```
With these changes, we will always set the `org_id` field in our Ecto queries, unless we explicitly set `skip_org_id: true` when calling the repository. The only remaining step is to make sure the `org_id` field is not null in your database tables and make sure the `org_id` is set whenever inserting into the database.
To better understand how our database schema should look like, let's discuss some other techniques that we can use to tighten up multi tenant support, especially in regards to associations.
Working with multi tenant associations
---------------------------------------
Let's expand our data domain a little bit.
So far we have assumed there is an organization schema. However, instead of naming its primary key `id`, we will name it `org_id`, so `Repo.one(Org, org_id: 13)` just works:
```
defmodule MyApp.Organization do
use Ecto.Schema
@primary_key {:org_id, :id, autogenerate: true}
schema "orgs" do
field :name
timestamps()
end
end
```
Let's also say that you may have multiple posts in an organization and the posts themselves may have multiple comments:
```
defmodule MyApp.Post do
use Ecto.Schema
schema "posts" do
field :title
field :org_id, :integer
has_many :comments, MyApp.Comment
timestamps()
end
end
defmodule MyApp.Comment do
use Ecto.Schema
schema "comments" do
field :body
field :org_id, :integer
belongs_to :post, MyApp.Post
timestamps()
end
end
```
One thing to have in mind is that, our `prepare_query` callback will apply to all queries, but it won't apply to joins inside the same query. Therefore, if you write this query:
```
MyApp.Repo.put_org_id(some_org_id)
MyApp.Repo.all(
from p in Post, join: c in assoc(p, :comments)
)
```
`prepare_query` will apply the `org_id` only to posts but not to the `join`. While this may seem problematic, in practice it is not an issue, because when you insert posts and comments in the database, **they will always have the same `org_id`**. If posts and comments do not have the same `org_id`, then there is a bug: the data either got corrupted or there is a bug in our software when inserting data.
Luckily, we can leverage database's foreign keys to guarantee that the `org_id`s always match between posts and comments. Our first stab at defining these schema migrations would look like this:
```
create table(:orgs, primary_key: false) do
add :org_id, :bigserial, primary_key: true
add :name, :string
timestamps()
end
create table(:posts) do
add :title, :string
add :org_id,
references(:orgs, column: :org_id),
null: false
timestamps()
end
create table(:comments) do
add :body, :string
add :org_id, references(:orgs), null: false
add :post_id, references(:posts), null: false
timestamps()
end
```
So far the only noteworthy change compared to a regular migration is the `primary_key: false` option to the `:orgs` table, as we want to mirror the primary key of `org_id` given to the schema. While the schema above works and guarantees that posts references an existing organization and that comments references existing posts and organizations, it does not guarantee that all posts and their related comments belong to the same organization.
We can tighten up this requirement by using composite foreign keys with the following changes:
```
create unique_index(:posts, [:id, :org_id])
create table(:comments) do
add :body, :string
# There is no need to define a reference for org_id
add :org_id, :integer, null: false
# Instead define a composite foreign key
add :post_id,
references(:posts, with: [org_id: :org_id]),
null: false
timestamps()
end
```
Instead of defining both `post_id` and `org_id` as individual foreign keys, we define `org_id` as a regular integer and then we define `post_id+org_id` as a composite foreign key by passing the `:with` option to `Ecto.Migration.references/2`. This makes sure comments point to posts which point to orgs, where all `org_id`s match.
Given composite foreign keys require the referenced keys to be unique, we also defined a unique index on the posts table **before** we defined the composite foreign key.
If you are using PostgreSQL and you want to tighten these guarantees even further, you can pass the `match: :full` option to `references`:
```
references(:posts, with: [org_id: :org_id], match: :full)
```
which will help enforce none of the columns in the foreign key can be `nil`.
Summary
--------
In this guide, we have changed our repository interface to guarantee our queries are always scoped to an `org_id`, unless we explicitly opt out. We also learned how to leverage database features to enforce the data is always valid.
When it comes to associations, you will want to apply composite foreign keys whenever possible. For example, imagine comments belongs to posts (which belong to an organization) and also to user (which belong to an organization). The comments schema migration should be defined like this:
```
create table(:comments) do
add :body, :string
add :org_id, :integer, null: false
add :post_id,
references(:posts, with: [org_id: :org_id]),
null: false
add :user_id,
references(:users, with: [org_id: :org_id]),
null: false
timestamps()
end
```
As long as all schemas have an `org_id`, all operations will be safely contained by the current tenant.
If by any chance you have schemas that are not tied to an `org_id`, you can even consider keeping them in a separate query prefix or in a separate database altogether, so you keep non-tenant data completely separated from tenant-specific data.
[← Previous Page Multi tenancy with query prefixes](multi-tenancy-with-query-prefixes) [Next Page → Self-referencing many to many](self-referencing-many-to-many)
phoenix Ecto.Query Ecto.Query
===========
Provides the Query DSL.
Queries are used to retrieve and manipulate data from a repository (see [`Ecto.Repo`](ecto.repo)). Ecto queries come in two flavors: keyword-based and macro-based. Most examples will use the keyword-based syntax, the macro one will be explored in later sections.
Let's see a sample query:
```
# Imports only from/2 of Ecto.Query
import Ecto.Query, only: [from: 2]
# Create a query
query = from u in "users",
where: u.age > 18,
select: u.name
# Send the query to the repository
Repo.all(query)
```
In the example above, we are directly querying the "users" table from the database.
Query expressions
------------------
Ecto allows a limited set of expressions inside queries. In the query below, for example, we use `u.age` to access a field, the `>` comparison operator and the literal `0`:
```
query = from u in "users", where: u.age > 0, select: u.name
```
You can find the full list of operations in [`Ecto.Query.API`](ecto.query.api). Besides the operations listed there, the following literals are supported in queries:
* Integers: `1`, `2`, `3`
* Floats: `1.0`, `2.0`, `3.0`
* Booleans: `true`, `false`
* Binaries: `<<1, 2, 3>>`
* Strings: `"foo bar"`, `~s(this is a string)`
* Atoms (other than booleans and `nil`): `:foo`, `:bar`
* Arrays: `[1, 2, 3]`, `~w(interpolate words)`
All other types and dynamic values must be passed as a parameter using interpolation as explained below.
Interpolation and casting
--------------------------
External values and Elixir expressions can be injected into a query expression with `^`:
```
def with_minimum(age, height_ft) do
from u in "users",
where: u.age > ^age and u.height > ^(height_ft * 3.28),
select: u.name
end
with_minimum(18, 5.0)
```
When interpolating values, you may want to explicitly tell Ecto what is the expected type of the value being interpolated:
```
age = "18"
Repo.all(from u in "users",
where: u.age > type(^age, :integer),
select: u.name)
```
In the example above, Ecto will cast the age to type integer. When a value cannot be cast, [`Ecto.Query.CastError`](ecto.query.casterror) is raised.
To avoid the repetition of always specifying the types, you may define an [`Ecto.Schema`](ecto.schema). In such cases, Ecto will analyze your queries and automatically cast the interpolated "age" when compared to the `u.age` field, as long as the age field is defined with type `:integer` in your schema:
```
age = "18"
Repo.all(from u in User, where: u.age > ^age, select: u.name)
```
Another advantage of using schemas is that we no longer need to specify the select option in queries, as by default Ecto will retrieve all fields specified in the schema:
```
age = "18"
Repo.all(from u in User, where: u.age > ^age)
```
For this reason, we will use schemas on the remaining examples but remember Ecto does not require them in order to write queries.
`nil` comparison
-----------------
`nil` comparison in filters, such as where and having, is forbidden and it will raise an error:
```
# Raises if age is nil
from u in User, where: u.age == ^age
```
This is done as a security measure to avoid attacks that attempt to traverse entries with nil columns. To check that value is `nil`, use [`is_nil/1`](https://hexdocs.pm/elixir/Kernel.html#is_nil/1) instead:
```
from u in User, where: is_nil(u.age)
```
Composition
------------
Ecto queries are composable. For example, the query above can actually be defined in two parts:
```
# Create a query
query = from u in User, where: u.age > 18
# Extend the query
query = from u in query, select: u.name
```
Composing queries uses the same syntax as creating a query. The difference is that, instead of passing a schema like `User` on the right-hand side of `in`, we passed the query itself.
Any value can be used on the right-hand side of `in` as long as it implements the [`Ecto.Queryable`](ecto.queryable) protocol. For now, we know the protocol is implemented for both atoms (like `User`) and strings (like "users").
In any case, regardless if a schema has been given or not, Ecto queries are always composable thanks to its binding system.
### Positional bindings
On the left-hand side of `in` we specify the query bindings. This is done inside `from` and `join` clauses. In the query below `u` is a binding and `u.age` is a field access using this binding.
```
query = from u in User, where: u.age > 18
```
Bindings are not exposed from the query. When composing queries, you must specify bindings again for each refinement query. For example, to further narrow down the above query, we again need to tell Ecto what bindings to expect:
```
query = from u in query, select: u.city
```
Bindings in Ecto are positional, and the names do not have to be consistent between input and refinement queries. For example, the query above could also be written as:
```
query = from q in query, select: q.city
```
It would make no difference to Ecto. This is important because it allows developers to compose queries without caring about the bindings used in the initial query.
When using joins, the bindings should be matched in the order they are specified:
```
# Create a query
query = from p in Post,
join: c in Comment, on: c.post_id == p.id
# Extend the query
query = from [p, c] in query,
select: {p.title, c.body}
```
You are not required to specify all bindings when composing. For example, if we would like to order the results above by post insertion date, we could further extend it as:
```
query = from q in query, order_by: q.inserted_at
```
The example above will work if the input query has 1 or 10 bindings. As long as the number of bindings is less than the number of `from`s + `join`s, Ecto will match only what you have specified. The first binding always matches the source given in `from`.
Similarly, if you are interested only in the last binding (or the last bindings) in a query, you can use `...` to specify "all bindings before" and match on the last one.
For instance, imagine you wrote:
```
posts_with_comments =
from p in query, join: c in Comment, on: c.post_id == p.id
```
And now we want to make sure to return both the post title and the comment body. Although we may not know how many bindings there are in the query, we are sure posts is the first binding and comments are the last one, so we can write:
```
from [p, ..., c] in posts_with_comments, select: {p.title, c.body}
```
In other words, `...` will include all the bindings between the first and the last, which may be one, many or no bindings at all.
### Named bindings
Another option for flexibly building queries with joins are named bindings. Coming back to the previous example, we can use the `as: :comment` option to bind the comments join to a concrete name:
```
posts_with_comments =
from p in Post,
join: c in Comment, as: :comment, on: c.post_id == p.id
```
Now we can refer to it using the following form of a bindings list:
```
from [p, comment: c] in posts_with_comments, select: {p.title, c.body}
```
This approach lets us not worry about keeping track of the position of the bindings when composing the query. The `:as` option can be given both on joins and on `from`:
```
from p in Post, as: :post
```
Only atoms are accepted for binding names. Named binding references must always be placed at the end of the bindings list:
```
[positional_binding_1, positional_binding_2, named_1: binding, named_2: binding]
```
Named bindings can also be used for late binding with the `as/1` construct, allowing you to refer to a binding that has not been defined yet:
```
from c in Comment, where: as(:posts).id == c.post_id
```
This is especially useful when working with subqueries, where you may need to refer to a parent binding with `parent_as`, which is not known when writing the subquery:
```
child_query = from c in Comment, where: parent_as(:posts).id == c.post_id
from p in Post, as: :posts, inner_lateral_join: c in subquery(child_query)
```
You can also match on a specific binding when building queries. For example, let's suppose you want to create a generic sort function that will order by a given `field` with a given `as` in `query`:
```
# Knowing the name of the binding
def sort(query, as, field) do
from [{^as, x}] in query, order_by: field(x, ^field)
end
```
### Bindingless operations
Although bindings are extremely useful when working with joins, they are not necessary when the query has only the `from` clause. For such cases, Ecto supports a way for building queries without specifying the binding:
```
from Post,
where: [category: "fresh and new"],
order_by: [desc: :published_at],
select: [:id, :title, :body]
```
The query above will select all posts with category "fresh and new", order by the most recently published, and return Post structs with only the id, title and body fields set. It is equivalent to:
```
from p in Post,
where: p.category == "fresh and new",
order_by: [desc: p.published_at],
select: struct(p, [:id, :title, :body])
```
One advantage of bindingless queries is that they are data-driven and therefore useful for dynamically building queries. For example, the query above could also be written as:
```
where = [category: "fresh and new"]
order_by = [desc: :published_at]
select = [:id, :title, :body]
from Post, where: ^where, order_by: ^order_by, select: ^select
```
This feature is very useful when queries need to be built based on some user input, like web search forms, CLIs and so on.
Fragments
----------
If you need an escape hatch, Ecto provides fragments (see [`Ecto.Query.API.fragment/1`](ecto.query.api#fragment/1)) to inject SQL (and non-SQL) fragments into queries.
For example, to get all posts while running the "lower(?)" function in the database where `p.title` is interpolated in place of `?`, one can write:
```
from p in Post,
where: is_nil(p.published_at) and
fragment("lower(?)", p.title) == ^title
```
Also, most adapters provide direct APIs for queries, like `Ecto.Adapters.SQL.query/4`, allowing developers to completely bypass Ecto queries.
Macro API
----------
In all examples so far we have used the **keywords query syntax** to create a query:
```
import Ecto.Query
from u in "users", where: u.age > 18, select: u.name
```
Due to the prevalence of the pipe operator in Elixir, Ecto also supports a pipe-based syntax:
```
"users"
|> where([u], u.age > 18)
|> select([u], u.name)
```
The keyword-based and pipe-based examples are equivalent. The downside of using macros is that the binding must be specified for every operation. However, since keyword-based and pipe-based examples are equivalent, the bindingless syntax also works for macros:
```
"users"
|> where([u], u.age > 18)
|> select([:name])
```
Such a syntax allows developers to write queries using bindings only in more complex query expressions.
This module documents each of those macros, providing examples in both the keywords query and pipe expression formats.
Query prefix
-------------
It is possible to set a prefix for the queries. For Postgres users, this will specify the schema where the table is located, while for MySQL users this will specify the database where the table is located. When no prefix is set, Postgres queries are assumed to be in the public schema, while MySQL queries are assumed to be in the database set in the config for the repo.
The query prefix may be set either for the whole query or on each individual `from` and `join` expression. If a `prefix` is not given to a `from` or a `join`, the prefix of the schema given to the `from` or `join` is used. The query prefix is used only if none of the above are declared.
Let's see some examples. To see the query prefix globally, the simplest mechanism is to pass an option to the repository operation:
```
results = Repo.all(query, prefix: "accounts")
```
You may also set the prefix for the whole query by setting the prefix field:
```
results =
query # May be User or an Ecto.Query itself
|> Ecto.Query.put_query_prefix("accounts")
|> Repo.all()
```
Setting the prefix in the query changes the default prefix of all `from` and `join` expressions. You can override the query prefix by either setting the `@schema_prefix` in your schema definitions or by passing the prefix option:
```
from u in User,
prefix: "accounts",
join: p in assoc(u, :posts),
prefix: "public"
```
Overall, here is the prefix lookup precedence:
1. The `:prefix` option given to `from`/`join` has the highest precedence
2. Then it falls back to the `@schema_prefix` attribute declared in the schema given to `from`/`join`
3. Then it falls back to the query prefix
The prefixes set in the query will be preserved when loading data.
Summary
========
Types
------
[dynamic()](#t:dynamic/0) [t()](#t:t/0) Functions
----------
[distinct(query, binding \\ [], expr)](#distinct/3) A distinct query expression.
[dynamic(binding \\ [], expr)](#dynamic/2) Builds a dynamic query expression.
[except(query, other\_query)](#except/2) An except (set difference) query expression.
[except\_all(query, other\_query)](#except_all/2) An except (set difference) query expression.
[exclude(query, field)](#exclude/2) Resets a previously set field on a query.
[first(queryable, order\_by \\ nil)](#first/2) Restricts the query to return the first result ordered by primary key.
[from(expr, kw \\ [])](#from/2) Creates a query.
[group\_by(query, binding \\ [], expr)](#group_by/3) A group by query expression.
[has\_named\_binding?(queryable, key)](#has_named_binding?/2) Returns `true` if the query has a binding with the given name, otherwise `false`.
[having(query, binding \\ [], expr)](#having/3) An AND having query expression.
[intersect(query, other\_query)](#intersect/2) An intersect query expression.
[intersect\_all(query, other\_query)](#intersect_all/2) An intersect query expression.
[join(query, qual, binding \\ [], expr, opts \\ [])](#join/5) A join query expression.
[last(queryable, order\_by \\ nil)](#last/2) Restricts the query to return the last result ordered by primary key.
[limit(query, binding \\ [], expr)](#limit/3) A limit query expression.
[lock(query, binding \\ [], expr)](#lock/3) A lock query expression.
[offset(query, binding \\ [], expr)](#offset/3) An offset query expression.
[or\_having(query, binding \\ [], expr)](#or_having/3) An OR having query expression.
[or\_where(query, binding \\ [], expr)](#or_where/3) An OR where query expression.
[order\_by(query, binding \\ [], expr)](#order_by/3) An order by query expression.
[preload(query, bindings \\ [], expr)](#preload/3) Preloads the associations into the result set.
[put\_query\_prefix(query, prefix)](#put_query_prefix/2) Puts the given prefix in a query.
[recursive\_ctes(query, value)](#recursive_ctes/2) Enables or disables recursive mode for CTEs.
[reverse\_order(query)](#reverse_order/1) Reverses the ordering of the query.
[select(query, binding \\ [], expr)](#select/3) A select query expression.
[select\_merge(query, binding \\ [], expr)](#select_merge/3) Mergeable select query expression.
[subquery(query, opts \\ [])](#subquery/2) Converts a query into a subquery.
[union(query, other\_query)](#union/2) A union query expression.
[union\_all(query, other\_query)](#union_all/2) A union all query expression.
[update(query, binding \\ [], expr)](#update/3) An update query expression.
[where(query, binding \\ [], expr)](#where/3) An AND where query expression.
[windows(query, binding \\ [], expr)](#windows/3) Defines windows which can be used with [`Ecto.Query.WindowAPI`](ecto.query.windowapi).
[with\_cte(query, name, list)](#with_cte/3) A common table expression (CTE) also known as WITH expression.
Types
======
### dynamic()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L430)
```
@opaque dynamic()
```
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L429)
```
@type t() :: %Ecto.Query{
aliases: term(),
assocs: term(),
combinations: term(),
distinct: term(),
from: term(),
group_bys: term(),
havings: term(),
joins: term(),
limit: term(),
lock: term(),
offset: term(),
order_bys: term(),
prefix: term(),
preloads: term(),
select: term(),
sources: term(),
updates: term(),
wheres: term(),
windows: term(),
with_ctes: term()
}
```
Functions
==========
### distinct(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1356)
A distinct query expression.
When true, only keeps distinct values from the resulting select expression.
If supported by your database, you can also pass query expressions to distinct and it will generate a query with DISTINCT ON. In such cases, `distinct` accepts exactly the same expressions as `order_by` and any `distinct` expression will be automatically prepended to the `order_by` expressions in case there is any `order_by` expression.
#### Keywords examples
```
# Returns the list of different categories in the Post schema
from(p in Post, distinct: true, select: p.category)
# If your database supports DISTINCT ON(),
# you can pass expressions to distinct too
from(p in Post,
distinct: p.category,
order_by: [p.date])
# The DISTINCT ON() also supports ordering similar to ORDER BY.
from(p in Post,
distinct: [desc: p.category],
order_by: [p.date])
# Using atoms
from(p in Post, distinct: :category, order_by: :date)
```
#### Expressions example
```
Post
|> distinct(true)
|> order_by([p], [p.category, p.author])
```
### dynamic(binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L542)
Builds a dynamic query expression.
Dynamic query expressions allow developers to compose query expressions bit by bit, so that they can be interpolated into parts of a query or another dynamic expression later on.
#### Examples
Imagine you have a set of conditions you want to build your query on:
```
conditions = false
conditions =
if params["is_public"] do
dynamic([p], p.is_public or ^conditions)
else
conditions
end
conditions =
if params["allow_reviewers"] do
dynamic([p, a], a.reviewer == true or ^conditions)
else
conditions
end
from query, where: ^conditions
```
In the example above, we were able to build the query expressions bit by bit, using different bindings, and later interpolate it all at once into the actual query.
A dynamic expression can always be interpolated inside another dynamic expression and into the constructs described below.
#### `where`, `having` and a `join`'s `on`
The `dynamic` macro can be interpolated at the root of a `where`, `having` or a `join`'s `on`.
For example, assuming the `conditions` variable defined in the previous section, the following is forbidden because it is not at the root of a `where`:
```
from q in query, where: q.some_condition and ^conditions
```
Fortunately that's easily solved by simply rewriting it to:
```
conditions = dynamic([q], q.some_condition and ^conditions)
from query, where: ^conditions
```
#### `order_by`
Dynamics can be interpolated inside keyword lists at the root of `order_by`. For example, you can write:
```
order_by = [
asc: :some_field,
desc: dynamic([p], fragment("?>>?", p.another_field, "json_key"))
]
from query, order_by: ^order_by
```
Dynamics are also supported in [`order_by/2`](#order_by/2) clauses inside [`windows/2`](#windows/2).
As with `where` and friends, it is not possible to pass dynamics outside of a root. For example, this won't work:
```
from query, order_by: [asc: ^dynamic(...)]
```
But this will:
```
from query, order_by: ^[asc: dynamic(...)]
```
#### `group_by`
Dynamics can be interpolated inside keyword lists at the root of `group_by`. For example, you can write:
```
group_by = [
:some_field,
dynamic([p], fragment("?>>?", p.another_field, "json_key"))
]
from query, group_by: ^group_by
```
Dynamics are also supported in `partition_by/2` clauses inside [`windows/2`](#windows/2).
As with `where` and friends, it is not possible to pass dynamics outside of a root. For example, this won't work:
```
from query, group_by: [:some_field, ^dynamic(...)]
```
But this will:
```
from query, group_by: ^[:some_field, dynamic(...)]
```
#### Updates
A `dynamic` is also supported inside updates, for example:
```
updates = [
set: [average: dynamic([p], p.sum / p.count)]
]
from query, update: ^updates
```
### except(query, other\_query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1594)
An except (set difference) query expression.
Takes the difference of the result sets of multiple queries. The `select` of each query must be exactly the same, with the same types in the same order.
Except expression returns only unique rows as if each query returned distinct results. This may cause a performance penalty. If you need to take the difference of multiple result sets without removing duplicate rows consider using [`except_all/2`](#except_all/2).
Note that the operations `order_by`, `limit` and `offset` of the current `query` apply to the result of the set difference.
#### Keywords example
```
supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, except: ^supplier_query
```
#### Expressions example
```
supplier_query = Supplier |> select([s], s.city)
Customer |> select([c], c.city) |> except(^supplier_query)
```
### except\_all(query, other\_query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1618)
An except (set difference) query expression.
Takes the difference of the result sets of multiple queries. The `select` of each query must be exactly the same, with the same types in the same order.
Note that the operations `order_by`, `limit` and `offset` of the current `query` apply to the result of the set difference.
#### Keywords example
```
supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, except_all: ^supplier_query
```
#### Expressions example
```
supplier_query = Supplier |> select([s], s.city)
Customer |> select([c], c.city) |> except_all(^supplier_query)
```
### exclude(query, field)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L723)
Resets a previously set field on a query.
It can reset many fields except the query source (`from`). When excluding a `:join`, it will remove *all* types of joins. If you prefer to remove a single type of join, please see paragraph below.
#### Examples
```
Ecto.Query.exclude(query, :join)
Ecto.Query.exclude(query, :where)
Ecto.Query.exclude(query, :order_by)
Ecto.Query.exclude(query, :group_by)
Ecto.Query.exclude(query, :having)
Ecto.Query.exclude(query, :distinct)
Ecto.Query.exclude(query, :select)
Ecto.Query.exclude(query, :combinations)
Ecto.Query.exclude(query, :with_ctes)
Ecto.Query.exclude(query, :limit)
Ecto.Query.exclude(query, :offset)
Ecto.Query.exclude(query, :lock)
Ecto.Query.exclude(query, :preload)
```
You can also remove specific joins as well such as `left_join` and `inner_join`:
```
Ecto.Query.exclude(query, :inner_join)
Ecto.Query.exclude(query, :cross_join)
Ecto.Query.exclude(query, :left_join)
Ecto.Query.exclude(query, :right_join)
Ecto.Query.exclude(query, :full_join)
Ecto.Query.exclude(query, :inner_lateral_join)
Ecto.Query.exclude(query, :left_lateral_join)
```
However, keep in mind that if a join is removed and its bindings were referenced elsewhere, the bindings won't be removed, leading to a query that won't compile.
### first(queryable, order\_by \\ nil)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L2047)
Restricts the query to return the first result ordered by primary key.
The query will be automatically ordered by the primary key unless `order_by` is given or `order_by` is set in the query. Limit is always set to 1.
#### Examples
```
Post |> first |> Repo.one
query |> first(:inserted_at) |> Repo.one
```
### from(expr, kw \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L803)
Creates a query.
It can either be a keyword query or a query expression.
If it is a keyword query the first argument must be either an `in` expression, or a value that implements the [`Ecto.Queryable`](ecto.queryable) protocol. If the query needs a reference to the data source in any other part of the expression, then an `in` must be used to create a reference variable. The second argument should be a keyword query where the keys are expression types and the values are expressions.
If it is a query expression the first argument must be a value that implements the [`Ecto.Queryable`](ecto.queryable) protocol and the second argument the expression.
#### Keywords example
```
from(c in City, select: c)
```
#### Expressions example
```
City |> select([c], c)
```
#### Examples
```
def paginate(query, page, size) do
from query,
limit: ^size,
offset: ^((page-1) * size)
end
```
The example above does not use `in` because `limit` and `offset` do not require a reference to the data source. However, extending the query with a where expression would require the use of `in`:
```
def published(query) do
from p in query, where: not(is_nil(p.published_at))
end
```
Notice we have created a `p` variable to reference the query's original data source. This assumes that the original query only had one source. When the given query has more than one source, positional or named bindings may be used to access the additional sources.
```
def published_multi(query) do
from [p,o] in query,
where: not(is_nil(p.published_at)) and not(is_nil(o.published_at))
end
```
Note that the variables `p` and `o` can be named whatever you like as they have no importance in the query sent to the database.
### group\_by(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1827)
A group by query expression.
Groups together rows from the schema that have the same values in the given fields. Using `group_by` "groups" the query giving it different semantics in the `select` expression. If a query is grouped, only fields that were referenced in the `group_by` can be used in the `select` or if the field is given as an argument to an aggregate function.
`group_by` also accepts a list of atoms where each atom refers to a field in source. For more complicated queries you can access fields directly instead of atoms.
#### Keywords examples
```
# Returns the number of posts in each category
from(p in Post,
group_by: p.category,
select: {p.category, count(p.id)})
# Using atoms
from(p in Post, group_by: :category, select: {p.category, count(p.id)})
# Using direct fields access
from(p in Post,
join: c in assoc(p, :category),
group_by: [p.id, c.name])
```
#### Expressions example
```
Post |> group_by([p], p.category) |> select([p], count(p.id))
```
### has\_named\_binding?(queryable, key)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L2103)
Returns `true` if the query has a binding with the given name, otherwise `false`.
For more information on named bindings see "Named bindings" in this module doc.
### having(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1855)
An AND having query expression.
Like `where`, `having` filters rows from the schema, but after the grouping is performed giving it the same semantics as `select` for a grouped query (see [`group_by/3`](#group_by/3)). `having` groups the query even if the query has no `group_by` expression.
#### Keywords example
```
# Returns the number of posts in each category where the
# average number of comments is above ten
from(p in Post,
group_by: p.category,
having: avg(p.num_comments) > 10,
select: {p.category, count(p.id)})
```
#### Expressions example
```
Post
|> group_by([p], p.category)
|> having([p], avg(p.num_comments) > 10)
|> select([p], count(p.id))
```
### intersect(query, other\_query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1647)
An intersect query expression.
Takes the overlap of the result sets of multiple queries. The `select` of each query must be exactly the same, with the same types in the same order.
Intersect expression returns only unique rows as if each query returned distinct results. This may cause a performance penalty. If you need to take the intersection of multiple result sets without removing duplicate rows consider using [`intersect_all/2`](#intersect_all/2).
Note that the operations `order_by`, `limit` and `offset` of the current `query` apply to the result of the set difference.
#### Keywords example
```
supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, intersect: ^supplier_query
```
#### Expressions example
```
supplier_query = Supplier |> select([s], s.city)
Customer |> select([c], c.city) |> intersect(^supplier_query)
```
### intersect\_all(query, other\_query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1671)
An intersect query expression.
Takes the overlap of the result sets of multiple queries. The `select` of each query must be exactly the same, with the same types in the same order.
Note that the operations `order_by`, `limit` and `offset` of the current `query` apply to the result of the set difference.
#### Keywords example
```
supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, intersect_all: ^supplier_query
```
#### Expressions example
```
supplier_query = Supplier |> select([s], s.city)
Customer |> select([c], c.city) |> intersect_all(^supplier_query)
```
### join(query, qual, binding \\ [], expr, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1057)
A join query expression.
Receives a source that is to be joined to the query and a condition for the join. The join condition can be any expression that evaluates to a boolean value. The qualifier must be one of `:inner`, `:left`, `:right`, `:cross`, `:full`, `:inner_lateral` or `:left_lateral`.
For a keyword query the `:join` keyword can be changed to `:inner_join`, `:left_join`, `:right_join`, `:cross_join`, `:full_join`, `:inner_lateral_join` or `:left_lateral_join`. `:join` is equivalent to `:inner_join`.
Currently it is possible to join on:
* an [`Ecto.Schema`](ecto.schema), such as `p in Post`
* an interpolated Ecto query with zero or more `where` clauses, such as `c in ^(from "posts", where: [public: true])`
* an association, such as `c in assoc(post, :comments)`
* a subquery, such as `c in subquery(another_query)`
* a query fragment, such as `c in fragment("SOME COMPLEX QUERY")`, see "Joining with fragments" below.
#### Options
Each join accepts the following options:
* `:on` - a query expression or keyword list to filter the join
* `:as` - a named binding for the join
* `:prefix` - the prefix to be used for the join when issuing a database query
* `:hints` - a string or a list of strings to be used as database hints
In the keyword query syntax, those options must be given immediately after the join. In the expression syntax, the options are given as the fifth argument.
#### Keywords examples
```
from c in Comment,
join: p in Post,
on: p.id == c.post_id,
select: {p.title, c.text}
from p in Post,
left_join: c in assoc(p, :comments),
select: {p, c}
```
Keywords can also be given or interpolated as part of `on`:
```
from c in Comment,
join: p in Post,
on: [id: c.post_id],
select: {p.title, c.text}
```
Any key in `on` will apply to the currently joined expression.
It is also possible to interpolate an Ecto query on the right-hand side of `in`. For example, the query above can also be written as:
```
posts = Post
from c in Comment,
join: p in ^posts,
on: [id: c.post_id],
select: {p.title, c.text}
```
The above is specially useful to dynamically join on existing queries, for example, to dynamically choose a source, or by choosing between public posts or posts that have been recently published:
```
posts =
if params["drafts"] do
from p in Post, where: [drafts: true]
else
from p in Post, where: [public: true]
end
from c in Comment,
join: p in ^posts, on: [id: c.post_id],
select: {p.title, c.text}
```
Only simple queries with `where` expressions can be interpolated in a join.
#### Expressions examples
```
Comment
|> join(:inner, [c], p in Post, on: c.post_id == p.id)
|> select([c, p], {p.title, c.text})
Post
|> join(:left, [p], c in assoc(p, :comments))
|> select([p, c], {p, c})
Post
|> join(:left, [p], c in Comment, on: c.post_id == p.id and c.is_visible == true)
|> select([p, c], {p, c})
```
#### Joining with fragments
When you need to join on a complex query, Ecto supports fragments in joins:
```
Comment
|> join(:inner, [c], p in fragment("SOME COMPLEX QUERY", c.id, ^some_param))
```
Although using fragments in joins is discouraged in favor of Ecto Query syntax, they are necessary when writing lateral joins as lateral joins require a subquery that refer to previous bindings:
```
Game
|> join(:inner_lateral, [g], gs in fragment("SELECT * FROM games_sold AS gs WHERE gs.game_id = ? ORDER BY gs.sold_on LIMIT 2", g.id))
|> select([g, gs], {g.name, gs.sold_on})
```
Note that the `join` does not automatically wrap the fragment in parentheses, since some expressions require parens and others require no parens. Therefore, in cases such as common table expressions, you will have to explicitly wrap the fragment content in parens.
#### Hints
`from` and `join` also support index hints, as found in databases such as [MySQL](https://dev.mysql.com/doc/refman/8.0/en/index-hints.html), [MSSQL](https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-2017) and [Clickhouse](https://clickhouse.tech/docs/en/sql-reference/statements/select/sample/).
For example, a developer using MySQL may write:
```
from p in Post,
join: c in Comment,
hints: ["USE INDEX FOO", "USE INDEX BAR"],
where: p.id == c.post_id,
select: c
```
Keep in mind you want to use hints rarely, so don't forget to read the database disclaimers about such functionality.
Hints must be static compile-time strings when they are specified as (list of) strings. Certain Ecto adapters may also accept dynamic hints using the tuple form:
```
from e in Event,
hints: [sample: sample_threshold()],
select: e
```
### last(queryable, order\_by \\ nil)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L2074)
Restricts the query to return the last result ordered by primary key.
The query ordering will be automatically reversed, with ASC columns becoming DESC columns (and vice-versa) and limit is set to 1. If there is no ordering, the query will be automatically ordered decreasingly by primary key.
#### Examples
```
Post |> last |> Repo.one
query |> last(:inserted_at) |> Repo.one
```
### limit(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1692)
A limit query expression.
Limits the number of rows returned from the result. Can be any expression but has to evaluate to an integer value and it can't include any field.
If `limit` is given twice, it overrides the previous value.
#### Keywords example
```
from(u in User, where: u.id == ^current_user, limit: 1)
```
#### Expressions example
```
User |> where([u], u.id == ^current_user) |> limit(1)
```
### lock(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1742)
A lock query expression.
Provides support for row-level pessimistic locking using `SELECT ... FOR UPDATE` or other, database-specific, locking clauses. `expr` can be any expression but has to evaluate to a boolean value or to a string and it can't include any fields.
If `lock` is used more than once, the last one used takes precedence.
Ecto also supports [optimistic locking](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) but not through queries. For more information on optimistic locking, have a look at the [`Ecto.Changeset.optimistic_lock/3`](ecto.changeset#optimistic_lock/3) function.
#### Keywords example
```
from(u in User, where: u.id == ^current_user, lock: "FOR SHARE NOWAIT")
```
#### Expressions example
```
User |> where([u], u.id == ^current_user) |> lock("FOR SHARE NOWAIT")
```
### offset(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1714)
An offset query expression.
Offsets the number of rows selected from the result. Can be any expression but it must evaluate to an integer value and it can't include any field.
If `offset` is given twice, it overrides the previous value.
#### Keywords example
```
# Get all posts on page 4
from(p in Post, limit: 10, offset: 30)
```
#### Expressions example
```
Post |> limit(10) |> offset(30)
```
### or\_having(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1877)
An OR having query expression.
Like `having` but combines with the previous expression by using `OR`. `or_having` behaves for `having` the same way `or_where` behaves for `where`.
#### Keywords example
```
# Augment a previous group_by with a having condition.
from(p in query, or_having: avg(p.num_comments) > 10)
```
#### Expressions example
```
# Augment a previous group_by with a having condition.
Post |> or_having([p], avg(p.num_comments) > 10)
```
### or\_where(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1437)
An OR where query expression.
Behaves exactly the same as `where` except it combines with any previous expression by using an `OR`. All expressions have to evaluate to a boolean value.
`or_where` also accepts a keyword list where each key is a field to be compared with the given value. Each key-value pair will be combined using `AND`, exactly as in `where`.
#### Keywords example
```
from(c in City, where: [country: "Sweden"], or_where: [country: "Brazil"])
```
If interpolating keyword lists, the keyword list entries are combined using ANDs and joined to any existing expression with an OR:
```
filters = [country: "USA", name: "New York"]
from(c in City, where: [country: "Sweden"], or_where: ^filters)
```
is equivalent to:
```
from c in City, where: (c.country == "Sweden") or
(c.country == "USA" and c.name == "New York")
```
The behaviour above is by design to keep the changes between `where` and `or_where` minimal. Plus, if you have a keyword list and you would like each pair to be combined using `or`, it can be easily done with [`Enum.reduce/3`](https://hexdocs.pm/elixir/Enum.html#reduce/3):
```
filters = [country: "USA", is_tax_exempt: true]
Enum.reduce(filters, City, fn {key, value}, query ->
from q in query, or_where: field(q, ^key) == ^value
end)
```
which will be equivalent to:
```
from c in City, or_where: (c.country == "USA"), or_where: c.is_tax_exempt == true
```
#### Expressions example
```
City |> where([c], c.country == "Sweden") |> or_where([c], c.country == "Brazil")
```
### order\_by(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1513)
An order by query expression.
Orders the fields based on one or more fields. It accepts a single field or a list of fields. The default direction is ascending (`:asc`) and can be customized in a keyword list as one of the following:
* `:asc`
* `:asc_nulls_last`
* `:asc_nulls_first`
* `:desc`
* `:desc_nulls_last`
* `:desc_nulls_first`
The `*_nulls_first` and `*_nulls_last` variants are not supported by all databases. While all databases default to ascending order, the choice of "nulls first" or "nulls last" is specific to each database implementation.
`order_by` may be invoked or listed in a query many times. New expressions are always appended to the previous ones.
`order_by` also accepts a list of atoms where each atom refers to a field in source or a keyword list where the direction is given as key and the field to order as value.
#### Keywords examples
```
from(c in City, order_by: c.name, order_by: c.population)
from(c in City, order_by: [c.name, c.population])
from(c in City, order_by: [asc: c.name, desc: c.population])
from(c in City, order_by: [:name, :population])
from(c in City, order_by: [asc: :name, desc_nulls_first: :population])
```
A keyword list can also be interpolated:
```
values = [asc: :name, desc_nulls_first: :population]
from(c in City, order_by: ^values)
```
A fragment can also be used:
```
from c in City, order_by: [
# A deterministic shuffled order
fragment("? % ? DESC", c.id, ^modulus),
desc: c.id,
]
```
It's also possible to order by an aliased or calculated column:
from(c in City,
```
select: %{
name: c.name,
total_population:
fragment(
"COALESCE(?, ?) + ? AS total_population",
c.animal_population,
0,
c.human_population
)
},
order_by: [
# based on `AS total_population` in the previous fragment
{:desc, fragment("total_population")}
]
```
)
#### Expressions examples
```
City |> order_by([c], asc: c.name, desc: c.population)
City |> order_by(asc: :name) # Sorts by the cities name
```
### preload(query, bindings \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L2031)
Preloads the associations into the result set.
Imagine you have a schema `Post` with a `has_many :comments` association and you execute the following query:
```
Repo.all from p in Post, preload: [:comments]
```
The example above will fetch all posts from the database and then do a separate query returning all comments associated with the given posts. The comments are then processed and associated to each returned `post` under the `comments` field.
Often times, you may want posts and comments to be selected and filtered in the same query. For such cases, you can explicitly tell an existing join to be preloaded into the result set:
```
Repo.all from p in Post,
join: c in assoc(p, :comments),
where: c.published_at > p.updated_at,
preload: [comments: c]
```
In the example above, instead of issuing a separate query to fetch comments, Ecto will fetch posts and comments in a single query and then do a separate pass associating each comment to its parent post. Therefore, instead of returning `number_of_posts * number_of_comments` results, like a `join` would, it returns only posts with the `comments` fields properly filled in.
Nested associations can also be preloaded in both formats:
```
Repo.all from p in Post,
preload: [comments: :likes]
Repo.all from p in Post,
join: c in assoc(p, :comments),
join: l in assoc(c, :likes),
where: l.inserted_at > c.updated_at,
preload: [comments: {c, likes: l}]
```
Applying a limit to the association can be achieved with `inner_lateral_join`:
```
Repo.all from p in Post, as: :post,
join: c in assoc(p, :comments),
inner_lateral_join: top_five in subquery(
from Comment,
where: [post_id: parent_as(:post).id],
order_by: :popularity,
limit: 5,
select: [:id]
), on: top_five.id == c.id,
preload: [comments: c]
```
#### Preload queries
Preload also allows queries to be given, allowing you to filter or customize how the preloads are fetched:
```
comments_query = from c in Comment, order_by: c.published_at
Repo.all from p in Post, preload: [comments: ^comments_query]
```
The example above will issue two queries, one for loading posts and then another for loading the comments associated with the posts. Comments will be ordered by `published_at`.
When specifying a preload query, you can still preload the associations of those records. For instance, you could preload an author's published posts and the comments on those posts:
```
posts_query = from p in Post, where: p.state == :published
Repo.all from a in Author, preload: [posts: ^{posts_query, [:comments]}]
```
Note: keep in mind operations like limit and offset in the preload query will affect the whole result set and not each association. For example, the query below:
```
comments_query = from c in Comment, order_by: c.popularity, limit: 5
Repo.all from p in Post, preload: [comments: ^comments_query]
```
won't bring the top of comments per post. Rather, it will only bring the 5 top comments across all posts. Instead, use a window:
```
ranking_query =
from c in Comment,
select: %{id: c.id, row_number: over(row_number(), :posts_partition)},
windows: [posts_partition: [partition_by: :post_id, order_by: :popularity]]
comments_query =
from c in Comment,
join: r in subquery(ranking_query),
on: c.id == r.id and r.row_number <= 5
Repo.all from p in Post, preload: [comments: ^comments_query]
```
#### Preload functions
Preload also allows functions to be given. In such cases, the function receives the IDs of the parent association and it must return the associated data. Ecto then will map this data and sort it by the relationship key:
```
comment_preloader = fn post_ids -> fetch_comments_by_post_ids(post_ids) end
Repo.all from p in Post, preload: [comments: ^comment_preloader]
```
This is useful when the whole dataset was already loaded or must be explicitly fetched from elsewhere. The IDs received by the preloading function and the result returned depends on the association type:
* For `has_many` and `belongs_to` - the function receives the IDs of the parent association and it must return a list of maps or structs with the associated entries. The associated map/struct must contain the "foreign\_key" field. For example, if a post has many comments, when preloading the comments with a custom function, the function will receive a list of "post\_ids" as the argument and it must return maps or structs representing the comments. The maps/structs must include the `:post_id` field
* For `has_many :through` - it behaves similarly to a regular `has_many` but note that the IDs received are of the last association. Imagine, for example, a post has many comments and each comment has an author. Therefore, a post may have many comments\_authors, written as `has_many :comments_authors, through: [:comments, :author]`. When preloading authors with a custom function via `:comments_authors`, the function will receive the IDs of the authors as the last step
* For `many_to_many` - the function receives the IDs of the parent association and it must return a tuple with the parent id as the first element and the association map or struct as the second. For example, if a post has many tags, when preloading the tags with a custom function, the function will receive a list of "post\_ids" as the argument and it must return a tuple in the format of `{post_id, tag}`
#### Keywords example
```
# Returns all posts, their associated comments, and the associated
# likes for those comments.
from(p in Post,
preload: [comments: :likes],
select: p
)
```
#### Expressions examples
```
Post |> preload(:comments) |> select([p], p)
Post
|> join(:left, [p], c in assoc(p, :comments))
|> preload([p, c], [:user, comments: c])
|> select([p], p)
```
### put\_query\_prefix(query, prefix)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L677)
Puts the given prefix in a query.
### recursive\_ctes(query, value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1188)
Enables or disables recursive mode for CTEs.
According to the SQL standard it affects all CTEs in the query, not individual ones.
See [`with_cte/3`](#with_cte/3) on example of how to build a query with a recursive CTE.
### reverse\_order(query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L2127)
Reverses the ordering of the query.
ASC columns become DESC columns (and vice-versa). If the query has no `order_by`s, it orders by the inverse of the primary key.
#### Examples
```
query |> reverse_order() |> Repo.one()
Post |> order(asc: :id) |> reverse_order() == Post |> order(desc: :id)
```
### select(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1255)
A select query expression.
Selects which fields will be selected from the schema and any transformations that should be performed on the fields. Any expression that is accepted in a query can be a select field.
Select also allows each expression to be wrapped in lists, tuples or maps as shown in the examples below. A full schema can also be selected.
There can only be one select expression in a query, if the select expression is omitted, the query will by default select the full schema. If `select` is given more than once, an error is raised. Use [`exclude/2`](#exclude/2) if you would like to remove a previous select for overriding or see [`select_merge/3`](#select_merge/3) for a limited version of `select` that is composable and can be called multiple times.
`select` also accepts a list of atoms where each atom refers to a field in the source to be selected.
#### Keywords examples
```
from(c in City, select: c) # returns the schema as a struct
from(c in City, select: {c.name, c.population})
from(c in City, select: [c.name, c.county])
from(c in City, select: %{n: c.name, answer: 42})
from(c in City, select: %{c | alternative_name: c.name})
from(c in City, select: %Data{name: c.name})
```
It is also possible to select a struct and limit the returned fields at the same time:
```
from(City, select: [:name])
```
The syntax above is equivalent to:
```
from(city in City, select: struct(city, [:name]))
```
You can also write:
```
from(city in City, select: map(city, [:name]))
```
If you want a map with only the selected fields to be returned.
For more information, read the docs for [`Ecto.Query.API.struct/2`](ecto.query.api#struct/2) and [`Ecto.Query.API.map/2`](ecto.query.api#map/2).
#### Expressions examples
```
City |> select([c], c)
City |> select([c], {c.name, c.country})
City |> select([c], %{"name" => c.name})
City |> select([:name])
City |> select([c], struct(c, [:name]))
City |> select([c], map(c, [:name]))
```
### select\_merge(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1314)
Mergeable select query expression.
This macro is similar to [`select/3`](#select/3) except it may be specified multiple times as long as every entry is a map. This is useful for merging and composing selects. For example:
```
query = from p in Post, select: %{}
query =
if include_title? do
from p in query, select_merge: %{title: p.title}
else
query
end
query =
if include_visits? do
from p in query, select_merge: %{visits: p.visits}
else
query
end
```
In the example above, the query is built little by little by merging into a final map. If both conditions above are true, the final query would be equivalent to:
```
from p in Post, select: %{title: p.title, visits: p.visits}
```
If `:select_merge` is called and there is no value selected previously, it will default to the source, `p` in the example above.
The argument given to `:select_merge` must always be a map. The value being merged on must be a struct or a map. If it is a struct, the fields merged later on must be part of the struct, otherwise an error is raised.
If the argument to `:select_merge` is a constructed struct ([`Ecto.Query.API.struct/2`](ecto.query.api#struct/2)) or map ([`Ecto.Query.API.map/2`](ecto.query.api#map/2)) where the source to struct or map may be a `nil` value (as in an outer join), the source will be returned unmodified.
```
query =
Post
|> join(:left, [p], t in Post.Translation,
on: t.post_id == p.id and t.locale == ^"en"
)
|> select_merge([_p, t], map(t, ^~w(title summary)a))
```
If there is no English translation for the post, the untranslated post `title` will be returned and `summary` will be `nil`. If there is, both `title` and `summary` will be the value from `Post.Translation`.
`select_merge` cannot be used to set fields in associations, as associations are always loaded later, overriding any previous value.
### subquery(query, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L659)
Converts a query into a subquery.
If a subquery is given, returns the subquery itself. If any other value is given, it is converted to a query via [`Ecto.Queryable`](ecto.queryable) and wrapped in the [`Ecto.SubQuery`](ecto.subquery) struct.
`subquery` is supported in `from`, `join`, and `where`, in the form `p.x in subquery(q)`.
#### Examples
```
# Get the average salary of the top 10 highest salaries
query = from Employee, order_by: [desc: :salary], limit: 10
from e in subquery(query), select: avg(e.salary)
```
A prefix can be specified for a subquery, similar to standard repo operations:
```
query = from Employee, order_by: [desc: :salary], limit: 10
from e in subquery(query, prefix: "my_prefix"), select: avg(e.salary)
```
Subquery can also be used in a `join` expression.
```
UPDATE posts
SET sync_started_at = $1
WHERE id IN (
SELECT id FROM posts
WHERE synced = false AND (sync_started_at IS NULL OR sync_started_at < $1)
LIMIT $2
)
```
We can write it as a join expression:
```
subset = from(p in Post,
where: p.synced == false and
(is_nil(p.sync_started_at) or p.sync_started_at < ^min_sync_started_at),
limit: ^batch_size
)
Repo.update_all(
from(p in Post, join: s in subquery(subset), on: s.id == p.id),
set: [sync_started_at: NaiveDateTime.utc_now()]
)
```
Or as a `where` condition:
```
subset_ids = from(p in subset, select: p.id)
Repo.update_all(
from(p in Post, where: p.id in subquery(subset_ids)),
set: [sync_started_at: NaiveDateTime.utc_now()]
)
```
If you need to refer to a parent binding which is not known when writing the subquery, you can use `parent_as` as shown in the examples under "Named bindings" in this module doc.
### union(query, other\_query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1542)
A union query expression.
Combines result sets of multiple queries. The `select` of each query must be exactly the same, with the same types in the same order.
Union expression returns only unique rows as if each query returned distinct results. This may cause a performance penalty. If you need to combine multiple result sets without removing duplicate rows consider using [`union_all/2`](#union_all/2).
Note that the operations `order_by`, `limit` and `offset` of the current `query` apply to the result of the union.
#### Keywords example
```
supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, union: ^supplier_query
```
#### Expressions example
```
supplier_query = Supplier |> select([s], s.city)
Customer |> select([c], c.city) |> union(^supplier_query)
```
### union\_all(query, other\_query)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1565)
A union all query expression.
Combines result sets of multiple queries. The `select` of each query must be exactly the same, with the same types in the same order.
Note that the operations `order_by`, `limit` and `offset` of the current `query` apply to the result of the union.
#### Keywords example
```
supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, union_all: ^supplier_query
```
#### Expressions example
```
supplier_query = Supplier |> select([s], s.city)
Customer |> select([c], c.city) |> union_all(^supplier_query)
```
### update(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1790)
An update query expression.
Updates are used to update the filtered entries. In order for updates to be applied, [`Ecto.Repo.update_all/3`](ecto.repo#c:update_all/3) must be invoked.
#### Keywords example
```
from(u in User, update: [set: [name: "new name"]])
```
#### Expressions examples
```
User |> update([u], set: [name: "new name"])
User |> update(set: [name: "new name"])
```
#### Interpolation
```
new_name = "new name"
from(u in User, update: [set: [name: ^new_name]])
new_name = "new name"
from(u in User, update: [set: [name: fragment("upper(?)", ^new_name)]])
```
#### Operators
The update expression in Ecto supports the following operators:
* `set` - sets the given field in the table to the given value
```
from(u in User, update: [set: [name: "new name"]])
```
* `inc` - increments (or decrements if the value is negative) the given field in the table by the given value
```
from(u in User, update: [inc: [accesses: 1]])
```
* `push` - pushes (appends) the given value to the end of the array field
```
from(u in User, update: [push: [tags: "cool"]])
```
* `pull` - pulls (removes) the given value from the array field
```
from(u in User, update: [pull: [tags: "not cool"]])
```
### where(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1388)
An AND where query expression.
`where` expressions are used to filter the result set. If there is more than one where expression, they are combined with an `and` operator. All where expressions have to evaluate to a boolean value.
`where` also accepts a keyword list where the field given as key is going to be compared with the given value. The fields will always refer to the source given in `from`.
#### Keywords example
```
from(c in City, where: c.country == "Sweden")
from(c in City, where: [country: "Sweden"])
```
It is also possible to interpolate the whole keyword list, allowing you to dynamically filter the source:
```
filters = [country: "Sweden"]
from(c in City, where: ^filters)
```
#### Expressions examples
```
City |> where([c], c.country == "Sweden")
City |> where(country: "Sweden")
```
### windows(query, binding \\ [], expr)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L599)
Defines windows which can be used with [`Ecto.Query.WindowAPI`](ecto.query.windowapi).
Receives a keyword list where keys are names of the windows and values are a keyword list with window expressions.
#### Examples
```
# Compare each employee's salary with the average salary in his or her department
from e in Employee,
select: {e.depname, e.empno, e.salary, over(avg(e.salary), :department)},
windows: [department: [partition_by: e.depname]]
```
In the example above, we get the average salary per department. `:department` is the window name, partitioned by `e.depname` and `avg/1` is the window function. For more information on windows functions, see [`Ecto.Query.WindowAPI`](ecto.query.windowapi).
#### Window expressions
The following keys are allowed when specifying a window.
### :partition\_by
A list of fields to partition the window by, for example:
```
windows: [department: [partition_by: e.depname]]
```
A list of atoms can also be interpolated for dynamic partitioning:
```
fields = [:depname, :year]
windows: [dynamic_window: [partition_by: ^fields]]
```
### :order\_by
A list of fields to order the window by, for example:
```
windows: [ordered_names: [order_by: e.name]]
```
It works exactly as the keyword query version of [`order_by/3`](#order_by/3).
### :frame
A fragment which defines the frame for window functions.
#### Examples
```
# Compare each employee's salary for each month with his average salary for previous 3 months
from p in Payroll,
select: {p.empno, p.date, p.salary, over(avg(p.salary), :prev_months)},
windows: [prev_months: [partition_by: p.empno, order_by: p.date, frame: fragment("ROWS 3 PRECEDING EXCLUDE CURRENT ROW")]]
```
### with\_cte(query, name, list)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query.ex#L1177)
A common table expression (CTE) also known as WITH expression.
`name` must be a compile-time literal string that is being used as the table name to join the CTE in the main query or in the recursive CTE.
**IMPORTANT!** Beware of using CTEs. In raw SQL, CTEs can be used as a mechanism to organize queries, but said mechanism has no purpose in Ecto since Ecto queries are composable by definition. In other words, if you need to break a large query into parts, use all of the functionality in Elixir and in this module to structure your code. Furthermore, breaking a query into CTEs can negatively impact performance, as the database may not optimize efficiently across CTEs. The main use case for CTEs in Ecto is to provide recursive definitions, which we outline in the following section. Non-recursive CTEs can often be written as joins or subqueries, which provide better performance.
#### Options
* `:as` - the CTE query itself or a fragment
#### Recursive CTEs
Use [`recursive_ctes/2`](#recursive_ctes/2) to enable recursive mode for CTEs.
In the CTE query itself use the same table name to leverage recursion that has been passed to the `name` argument. Make sure to write a stop condition to avoid an infinite recursion loop. Generally speaking, you should only use CTEs in Ecto for writing recursive queries.
#### Expression examples
Products and their category names for breadcrumbs:
```
category_tree_initial_query =
Category
|> where([c], is_nil(c.parent_id))
category_tree_recursion_query =
Category
|> join(:inner, [c], ct in "category_tree", on: c.parent_id == ct.id)
category_tree_query =
category_tree_initial_query
|> union_all(^category_tree_recursion_query)
Product
|> recursive_ctes(true)
|> with_cte("category_tree", as: ^category_tree_query)
|> join(:left, [p], c in "category_tree", on: c.id == p.category_id)
|> group_by([p], p.id)
|> select([p, c], %{p | category_names: fragment("ARRAY_AGG(?)", c.name)})
```
It's also possible to pass a raw SQL fragment:
```
@raw_sql_category_tree """
SELECT * FROM categories WHERE c.parent_id IS NULL
UNION ALL
SELECT * FROM categories AS c, category_tree AS ct WHERE ct.id = c.parent_id
"""
Product
|> recursive_ctes(true)
|> with_cte("category_tree", as: fragment(@raw_sql_category_tree))
|> join(:inner, [p], c in "category_tree", on: c.id == p.category_id)
```
If you don't have any Ecto schema pointing to the CTE table, you can pass a tuple with the CTE table name as the first element and an Ecto schema as the second element. This will cast the result rows to Ecto structs as long as the Ecto schema maps to the same fields in the CTE table:
```
{"category_tree", Category}
|> recursive_ctes(true)
|> with_cte("category_tree", as: ^category_tree_query)
|> join(:left, [c], p in assoc(c, :products))
|> group_by([c], c.id)
|> select([c, p], %{c | products_count: count(p.id)})
```
Keyword syntax is not supported for this feature.
#### Limitation: CTEs on schemas with source fields
Ecto allows developers to say that a table in their Ecto schema maps to a different column in their database:
```
field :group_id, :integer, source: :iGroupId
```
At the moment, using a schema with source fields in CTE may emit invalid queries. If you are running into such scenarios, your best option is to use a fragment as your CTE.
| programming_docs |
phoenix Ecto.Association.HasThrough Ecto.Association.HasThrough
============================
The association struct for `has_one` and `has_many` through associations.
Its fields are:
* `cardinality` - The association cardinality
* `field` - The name of the association field on the schema
* `owner` - The schema where the association was defined
* `owner_key` - The key on the `owner` schema used for the association
* `through` - The through associations
* `relationship` - The relationship to the specified schema, default `:child`
phoenix Ecto.ParameterizedType behaviour Ecto.ParameterizedType behaviour
=================================
Parameterized types are Ecto types that can be customized per field.
Parameterized types allow a set of options to be specified in the schema which are initialized on compilation and passed to the callback functions as the last argument.
For example, `field :foo, :string` behaves the same for every field. On the other hand, `field :foo, Ecto.Enum, values: [:foo, :bar, :baz]` will likely have a different set of values per field.
Note that options are specified as a keyword, but it is idiomatic to convert them to maps inside [`init/1`](#c:init/1) for easier pattern matching in other callbacks.
Parameterized types are a superset of regular types. In other words, with parameterized types you can do everything a regular type does, and more. For example, parameterized types can handle `nil` values in both `load` and `dump` callbacks, they can customize `cast` behavior per query and per changeset, and also control how values are embedded.
However, parameterized types are also more complex. Therefore, if everything you need to achieve can be done with basic types, they should be preferred to parameterized ones.
Examples
---------
To create a parameterized type, create a module as shown below:
```
defmodule MyApp.MyType do
use Ecto.ParameterizedType
def type(_params), do: :string
def init(opts) do
validate_opts(opts)
Enum.into(opts, %{})
end
def cast(data, params) do
...
cast_data
end
def load(data, _loader, params) do
...
{:ok, loaded_data}
end
def dump(data, dumper, params) do
...
{:ok, dumped_data}
end
def equal?(a, b, _params) do
a == b
end
end
```
To use this type in a schema field, specify the type and parameters like this:
```
schema "foo" do
field :bar, MyApp.MyType, opt1: :baz, opt2: :boo
end
```
To use this type in places where you need it to be initialized (for example, schemaless changesets), you can use [`init/2`](#init/2).
Summary
========
Types
------
[opts()](#t:opts/0) The keyword options passed from the Schema's field macro into [`init/1`](#c:init/1)
[params()](#t:params/0) The parameters for the ParameterizedType
Callbacks
----------
[autogenerate(params)](#c:autogenerate/1) Generates a loaded version of the data.
[cast(data, params)](#c:cast/2) Casts the given input to the ParameterizedType with the given parameters.
[dump(value, dumper, params)](#c:dump/3) Dumps the given term into an Ecto native type.
[embed\_as(format, params)](#c:embed_as/2) Dictates how the type should be treated inside embeds.
[equal?(value1, value2, params)](#c:equal?/3) Checks if two terms are semantically equal.
[init(opts)](#c:init/1) Callback to convert the options specified in the field macro into parameters to be used in other callbacks.
[load(value, loader, params)](#c:load/3) Loads the given term into a ParameterizedType.
[type(params)](#c:type/1) Returns the underlying schema type for the ParameterizedType.
Functions
----------
[init(type, opts)](#init/2) Inits a parameterized type given by `type` with `opts`.
Types
======
### opts()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L74)
```
@type opts() :: keyword()
```
The keyword options passed from the Schema's field macro into [`init/1`](#c:init/1)
### params()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L82)
```
@type params() :: term()
```
The parameters for the ParameterizedType
This is the value passed back from [`init/1`](#c:init/1) and subsequently passed as the last argument to all callbacks. Idiomatically it is a map.
Callbacks
==========
### autogenerate(params)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L170)
```
@callback autogenerate(params()) :: term()
```
Generates a loaded version of the data.
This is callback is invoked when a parameterized type is given to `field` with the `:autogenerate` flag.
### cast(data, params)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L114)
```
@callback cast(data :: term(), params()) :: {:ok, term()} | :error | {:error, keyword()}
```
Casts the given input to the ParameterizedType with the given parameters.
If the parameterized type is also a composite type, the inner type can be cast by calling [`Ecto.Type.cast/2`](ecto.type#cast/2) directly.
For more information on casting, see [`Ecto.Type.cast/1`](ecto.type#c:cast/1).
### dump(value, dumper, params)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L143)
```
@callback dump(value :: any(), dumper :: function(), params()) ::
{:ok, value :: any()} | :error
```
Dumps the given term into an Ecto native type.
It receives a `dumper` function in case the parameterized type is also a composite type. In order to dump the inner type, the `dumper` must be called with the inner type and the inner value as argument.
For more information on dumping, see [`Ecto.Type.dump/1`](ecto.type#c:dump/1). Note that this callback *will* be called when dumping a `nil` value, unlike [`Ecto.Type.dump/1`](ecto.type#c:dump/1).
### embed\_as(format, params)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L162)
```
@callback embed_as(format :: atom(), params()) :: :self | :dump
```
Dictates how the type should be treated inside embeds.
For more information on embedding, see [`Ecto.Type.embed_as/1`](ecto.type#c:embed_as/1)
### equal?(value1, value2, params)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L155)
```
@callback equal?(value1 :: any(), value2 :: any(), params()) :: boolean()
```
Checks if two terms are semantically equal.
### init(opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L103)
```
@callback init(opts :: opts()) :: params()
```
Callback to convert the options specified in the field macro into parameters to be used in other callbacks.
This function is called at compile time, and should raise if invalid values are specified. It is idiomatic that the parameters returned from this are a map. `field` and `schema` will be injected into the options automatically.
For example, this schema specification
```
schema "my_table" do
field :my_field, MyParameterizedType, opt1: :foo, opt2: nil
end
```
will result in the call:
```
MyParameterizedType.init([schema: "my_table", field: :my_field, opt1: :foo, opt2: nil])
```
### load(value, loader, params)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L129)
```
@callback load(value :: any(), loader :: function(), params()) ::
{:ok, value :: any()} | :error
```
Loads the given term into a ParameterizedType.
It receives a `loader` function in case the parameterized type is also a composite type. In order to load the inner type, the `loader` must be called with the inner type and the inner value as argument.
For more information on loading, see [`Ecto.Type.load/1`](ecto.type#c:load/1). Note that this callback *will* be called when loading a `nil` value, unlike [`Ecto.Type.load/1`](ecto.type#c:load/1).
### type(params)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L150)
```
@callback type(params()) :: Ecto.Type.t()
```
Returns the underlying schema type for the ParameterizedType.
For more information on schema types, see [`Ecto.Type.type/0`](ecto.type#c:type/0)
Functions
==========
### init(type, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/parameterized_type.ex#L179)
Inits a parameterized type given by `type` with `opts`.
Useful when manually initializing a type for schemaless changesets.
phoenix Constraints and Upserts Constraints and Upserts
========================
In this guide we will learn how to use constraints and upserts. To showcase those features, we will work on a practical scenario: which is by studying a many to many relationship between posts and tags.
put\_assoc vs cast\_assoc
--------------------------
Imagine we are building an application that has blog posts and such posts may have many tags. Not only that, a given tag may also belong to many posts. This is a classic scenario where we would use `many_to_many` associations. Our migrations would look like:
```
create table(:posts) do
add :title, :string
add :body, :text
timestamps()
end
create table(:tags) do
add :name, :string
timestamps()
end
create unique_index(:tags, [:name])
create table(:posts_tags, primary_key: false) do
add :post_id, references(:posts)
add :tag_id, references(:tags)
end
```
Note we added a unique index to the tag name because we don't want to have duplicated tags in our database. It is important to add an index at the database level instead of using a validation since there is always a chance two tags with the same name would be validated and inserted simultaneously, passing the validation and leading to duplicated entries.
Now let's also imagine we want the user to input such tags as a list of words split by comma, such as: "elixir, erlang, ecto". Once this data is received in the server, we will break it apart into multiple tags and associate them to the post, creating any tag that does not yet exist in the database.
While the constraints above sound reasonable, that's exactly what put us in trouble with `cast_assoc/3`. The `cast_assoc/3` changeset function was designed to receive external parameters and compare them with the associated data in our structs. To do so correctly, Ecto requires tags to be sent as a list of maps. We can see an example of this in [Polymorphic associations with many to many](polymorphic-associations-with-many-to-many). However, here we expect tags to be sent in a string separated by comma.
Furthermore, `cast_assoc/3` relies on the primary key field for each tag sent in order to decide if it should be inserted, updated or deleted. Again, because the user is simply passing a string, we don't have the ID information at hand.
When we can't cope with `cast_assoc/3`, it is time to use `put_assoc/4`. In `put_assoc/4`, we give Ecto structs or changesets instead of parameters, giving us the ability to manipulate the data as we want. Let's define the schema and the changeset function for a post which may receive tags as a string:
```
defmodule MyApp.Post do
use Ecto.Schema
schema "posts" do
field :title
field :body
many_to_many :tags, MyApp.Tag,
join_through: "posts_tags",
on_replace: :delete
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title, :body])
|> Ecto.Changeset.put_assoc(:tags, parse_tags(params))
end
defp parse_tags(params) do
(params["tags"] || "")
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(& &1 == "")
|> Enum.map(&get_or_insert_tag/1)
end
defp get_or_insert_tag(name) do
Repo.get_by(MyApp.Tag, name: name) ||
Repo.insert!(%Tag{name: name})
end
end
```
In the changeset function above, we moved all the handling of tags to a separate function, called `parse_tags/1`, which checks for the parameter, breaks each tag apart via [`String.split/2`](https://hexdocs.pm/elixir/String.html#split/2), then removes any left over whitespace with [`String.trim/1`](https://hexdocs.pm/elixir/String.html#trim/1), rejects any empty string and finally checks if the tag exists in the database or not, creating one in case none exists.
The `parse_tags/1` function is going to return a list of `MyApp.Tag` structs which are then passed to `put_assoc/4`. By calling `put_assoc/4`, we are telling Ecto those should be the tags associated to the post from now on. In case a previous tag was associated to the post and not given in `put_assoc/4`, Ecto will invoke the behaviour defined in the `:on_replace` option, which we have set to `:delete`. The `:delete` behaviour will remove the association between the post and the removed tag from the database.
And that's all we need to use `many_to_many` associations with `put_assoc/4`. `put_assoc/4` is very useful when we want to have more explicit control over our associations and it also works with `has_many`, `belongs_to` and all others association types.
However, our code is not yet ready for production. Let's see why.
Constraints and race conditions
--------------------------------
Remember we added a unique index to the tag `:name` column when creating the tags table. We did so to protect us from having duplicate tags in the database.
By adding the unique index and then using `get_by` with a `insert!` to get or insert a tag, we introduced a potential error in our application. If two posts are submitted at the same time with a similar tag, there is a chance we will check if the tag exists at the same time, leading both submissions to believe there is no such tag in the database. When that happens, only one of the submissions will succeed while the other one will fail. That's a race condition: your code will error from time to time, only when certain conditions are met. And those conditions are time sensitive.
Luckily Ecto gives us a mechanism to handle constraint errors from the database.
Checking for constraint errors
-------------------------------
Since our `get_or_insert_tag(name)` function fails when a tag already exists in the database, we need to handle such scenarios accordingly. Let's rewrite it taking race conditions into account:
```
defp get_or_insert_tag(name) do
%Tag{}
|> Ecto.Changeset.change(name: name)
|> Ecto.Changeset.unique_constraint(:name)
|> Repo.insert()
|> case do
{:ok, tag} -> tag
{:error, _} -> Repo.get_by!(MyApp.Tag, name: name)
end
end
```
Instead of inserting the tag directly, we now build a changeset, which allows us to use the `unique_constraint` annotation. Now if the `Repo.insert` operation fails because the unique index for `:name` is violated, Ecto won't raise, but return an `{:error, changeset}` tuple. Therefore, if `Repo.insert` succeeds, it is because the tag was saved, otherwise the tag already exists, which we then fetch with `Repo.get_by!`.
While the mechanism above fixes the race condition, it is a quite expensive one: we need to perform two queries for every tag that already exists in the database: the (failed) insert and then the repository lookup. Given that's the most common scenario, we may want to rewrite it to the following:
```
defp get_or_insert_tag(name) do
Repo.get_by(MyApp.Tag, name: name) ||
maybe_insert_tag(name)
end
defp maybe_insert_tag(name) do
%Tag{}
|> Ecto.Changeset.change(name: name)
|> Ecto.Changeset.unique_constraint(:name)
|> Repo.insert
|> case do
{:ok, tag} -> tag
{:error, _} -> Repo.get_by!(MyApp.Tag, name: name)
end
end
```
The above performs 1 query for every tag that already exists, 2 queries for every new tag and possibly 3 queries in the case of race conditions. While the above would perform slightly better on average, Ecto has a better option in stock.
Upserts
--------
Ecto supports the so-called "upsert" command which is an abbreviation for "update or insert". The idea is that we try to insert a record and in case it conflicts with an existing entry, for example due to a unique index, we can choose how we want the database to act by either raising an error (the default behaviour), ignoring the insert (no error) or by updating the conflicting database entries.
"upsert" in Ecto is done with the `:on_conflict` option. Let's rewrite `get_or_insert_tag(name)` once more but this time using the `:on_conflict` option. Remember that "upsert" is a new feature in PostgreSQL 9.5, so make sure you are up to date.
Your first try in using `:on_conflict` may be by setting it to `:nothing`, as below:
```
defp get_or_insert_tag(name) do
Repo.insert!(
%MyApp.Tag{name: name},
on_conflict: :nothing
)
end
```
While the above won't raise an error in case of conflicts, it also won't update the struct given, so it will return a tag without ID. One solution is to force an update to happen in case of conflicts, even if the update is about setting the tag name to its current name. In such cases, PostgreSQL also requires the `:conflict_target` option to be given, which is the column (or a list of columns) we are expecting the conflict to happen:
```
defp get_or_insert_tag(name) do
Repo.insert!(
%MyApp.Tag{name: name},
on_conflict: [set: [name: name]],
conflict_target: :name
)
end
```
And that's it! We try to insert a tag with the given name and if such tag already exists, we tell Ecto to update its name to the current value, updating the tag and fetching its id. While the above is certainly a step up from all solutions so far, it still performs one query per tag. If 10 tags are sent, we will perform 10 queries. Can we further improve this?
Upserts and insert\_all
------------------------
Ecto accepts the `:on_conflict` option not only in [`Ecto.Repo.insert/2`](ecto.repo#c:insert/2) but also in the [`Ecto.Repo.insert_all/3`](ecto.repo#c:insert_all/3) function. This means we can build one query that attempts to insert all missing tags and then another query that fetches all of them at once. Let's see how our `Post` schema will look like after those changes:
```
defmodule MyApp.Post do
use Ecto.Schema
# We need to import Ecto.Query
import Ecto.Query
# Schema is the same
schema "posts" do
add :title
add :body
many_to_many :tags, MyApp.Tag,
join_through: "posts_tags",
on_replace: :delete
timestamps()
end
# Changeset is the same
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title, :body])
|> Ecto.Changeset.put_assoc(:tags, parse_tags(params))
end
# Parse tags has slightly changed
defp parse_tags(params) do
(params["tags"] || "")
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(& &1 == "")
|> insert_and_get_all()
end
defp insert_and_get_all([]) do
[]
end
defp insert_and_get_all(names) do
timestamp =
NaiveDateTime.utc_now()
|> NaiveDateTime.truncate(:second)
placeholders = %{timestamp: timestamp}
maps =
Enum.map(names, &%{
name: &1,
inserted_at: {:placeholder, :timestamp},
updated_at: {:placeholder, :timestamp}
})
Repo.insert_all(
MyApp.Tag,
maps,
placeholders: placeholders,
on_conflict: :nothing
)
Repo.all(from t in MyApp.Tag, where: t.name in ^names)
end
end
```
Instead of getting and inserting each tag individually, the code above works on all tags at once, first by building a list of maps which is given to `insert_all`. Then we look up all tags with the given names. Regardless of how many tags are sent, we will perform only 2 queries - unless no tag is sent, in which we return an empty list back promptly. This solution is only possible thanks to the `:on_conflict` option, which guarantees `insert_all` won't fail in case a unique index is violated, such as from duplicate tag names. Remember, `insert_all` won't autogenerate values like timestamps. That's why we define a timestamp placeholder and reuse it across `inserted_at` and `updated_at` fields.
Finally, keep in mind that we haven't used transactions in any of the examples so far. That decision was deliberate as we relied on the fact that getting or inserting tags is an idempotent operation, i.e. we can repeat it many times for a given input and it will always give us the same result back. Therefore, even if we fail to introduce the post to the database due to a validation error, the user will be free to resubmit the form and we will just attempt to get or insert the same tags once again. The downside of this approach is that tags will be created even if creating the post fails, which means some tags may not have posts associated to them. In case that's not desired, the whole operation could be wrapped in a transaction or modeled with [`Ecto.Multi`](ecto.multi).
[← Previous Page Composable transactions with Multi](composable-transactions-with-multi) [Next Page → Data mapping and validation](data-mapping-and-validation)
| programming_docs |
phoenix Dynamic queries Dynamic queries
================
Ecto was designed from the ground up to have an expressive query API that leverages Elixir syntax to write queries that are pre-compiled for performance and safety. When building queries, we may use the keywords syntax
```
import Ecto.Query
from p in Post,
where: p.author == "José" and p.category == "Elixir",
where: p.published_at > ^minimum_date,
order_by: [desc: p.published_at]
```
or the pipe-based one
```
import Ecto.Query
Post
|> where([p], p.author == "José" and p.category == "Elixir")
|> where([p], p.published_at > ^minimum_date)
|> order_by([p], desc: p.published_at)
```
While many developers prefer the pipe-based syntax, having to repeat the binding `p` made it quite verbose compared to the keyword one.
Another problem with the pre-compiled query syntax is that it has limited options to compose the queries dynamically. Imagine for example a web application that provides search functionality on top of existing posts. The user should be able to specify multiple criteria, such as the author name, the post category, publishing interval, etc.
To solve those problems, Ecto also provides a data-structure centric API to build queries as well as a very powerful mechanism for dynamic queries. Let's take a look.
Focusing on data structures
----------------------------
Ecto provides a simpler API for both keyword and pipe based queries by making data structures first-class. Let's see an example:
```
from p in Post,
where: [author: "José", category: "Elixir"],
where: p.published_at > ^minimum_date,
order_by: [desc: :published_at]
```
and
```
Post
|> where(author: "José", category: "Elixir")
|> where([p], p.published_at > ^minimum_date)
|> order_by(desc: :published_at)
```
Notice how we were able to ditch the `p` selector in most expressions. In Ecto, all constructs, from `select` and `order_by` to `where` and `group_by`, accept data structures as input. The data structure can be specified at compile-time, as above, and also dynamically at runtime, shown below:
```
where = [author: "José", category: "Elixir"]
order_by = [desc: :published_at]
Post
|> where(^where)
|> where([p], p.published_at > ^minimum_date)
|> order_by(^order_by)
```
While using data-structures already brings a good amount of flexibility to Ecto queries, not all expressions can be converted to data structures. For example, `where` converts a key-value to a `key == value` comparison, and therefore order-based comparisons such as `p.published_at > ^minimum_date` need to be written as before.
Dynamic fragments
------------------
For cases where we cannot rely on data structures but still desire to build queries dynamically, Ecto includes the [`Ecto.Query.dynamic/2`](ecto.query#dynamic/2) macro.
The `dynamic` macro allows us to conditionally build query fragments and interpolate them in the main query. For example, imagine that in the example above you may optionally filter posts by a date of publication. You could of course write it like this:
```
query =
Post
|> where(^where)
|> order_by(^order_by)
query =
if published_at = params["published_at"] do
where(query, [p], p.published_at < ^published_at)
else
query
end
```
But with dynamic fragments, you can also write it as:
```
where = [author: "José", category: "Elixir"]
order_by = [desc: :published_at]
filter_published_at =
if published_at = params["published_at"] do
dynamic([p], p.published_at < ^published_at)
else
true
end
Post
|> where(^where)
|> where(^filter_published_at)
|> order_by(^order_by)
```
The `dynamic` macro allows us to build dynamic expressions that are later interpolated into the query. `dynamic` expressions can also be interpolated into dynamic expressions, allowing developers to build complex expressions dynamically without hassle.
By using dynamic fragments, we can decouple the processing of parameters from the query generation. Let's see a more complex example.
Building dynamic queries
-------------------------
Let's go back to the original problem. We want to build a search functionality where the user can configure how to traverse all posts in many different ways. For example, the user may choose how to order the data, filter by author and category, as well as select posts published after a certain date.
To tackle this in Ecto, we can break our problem into a bunch of small functions, that build either data structures or dynamic fragments, and then we interpolate it into the query:
```
def filter(params) do
Post
|> order_by(^filter_order_by(params["order_by"]))
|> where(^filter_where(params))
end
def filter_order_by("published_at_desc"),
do: [desc: dynamic([p], p.published_at)]
def filter_order_by("published_at"),
do: [asc: dynamic([p], p.published_at)]
def filter_order_by(_),
do: []
def filter_where(params) do
Enum.reduce(params, dynamic(true), fn
{"author", value}, dynamic ->
dynamic([p], ^dynamic and p.author == ^value)
{"category", value}, dynamic ->
dynamic([p], ^dynamic and p.category == ^value)
{"published_at", value}, dynamic ->
dynamic([p], ^dynamic and p.published_at > ^value)
{_, _}, dynamic ->
# Not a where parameter
dynamic
end)
end
```
Because we were able to break our problem into smaller functions that receive regular data structures, we can use all the tools available in Elixir to work with data. For handling the `order_by` parameter, it may be best to simply pattern match on the `order_by` parameter. For building the `where` clause, we can use `reduce` to start with an empty dynamic (that always returns true) and refine it with new conditions as we traverse the parameters.
Testing also becomes simpler as we can test each function in isolation, even when using dynamic queries:
```
test "filter published at based on the given date" do
assert dynamic_match?(
filter_where(%{}),
"true"
)
assert dynamic_match?(
filter_where(%{"published_at" => "2010-04-17"}),
"true and q.published_at > ^\"2010-04-17\""
)
end
defp dynamic_match?(dynamic, string) do
inspect(dynamic) == "dynamic([q], #{string})"
end
```
In the example above, we created a small helper that allows us to assert on the dynamic contents by matching on the results of `inspect(dynamic)`.
Dynamic and joins
------------------
Even query joins can be tackled dynamically. For example, let's do two modifications to the example above. Let's say we can also sort by author name ("author\_name" and "author\_name\_desc") and at the same time let's say that authors are in a separate table, which means our authors filter in `filter_where` now need to go through the join table.
Our final solution would look like this:
```
def filter(params) do
Post
# 1. Add named join binding
|> join(:inner, [p], assoc(p, :authors), as: :authors)
|> order_by(^filter_order_by(params["order_by"]))
|> where(^filter_where(params))
end
# 2. Returned dynamic with join binding
def filter_order_by("published_at_desc"),
do: [desc: dynamic([p], p.published_at)]
def filter_order_by("published_at"),
do: dynamic([p], p.published_at)
def filter_order_by("author_name_desc"),
do: [desc: dynamic([authors: a], a.name)]
def filter_order_by("author_name"),
do: dynamic([authors: a], a.name)
def filter_order_by(_),
do: []
# 3. Change the authors clause inside reduce
def filter_where(params) do
Enum.reduce(params, dynamic(true), fn
{"author", value}, dynamic ->
dynamic([authors: a], ^dynamic and a.name == ^value)
{"category", value}, dynamic ->
dynamic([p], ^dynamic and p.category == ^value)
{"published_at", value}, dynamic ->
dynamic([p], ^dynamic and p.published_at > ^value)
{_, _}, dynamic ->
# Not a where parameter
dynamic
end)
end
```
Adding more filters in the future is simply a matter of adding more clauses to the [`Enum.reduce/3`](https://hexdocs.pm/elixir/Enum.html#reduce/3) call in `filter_where`.
[← Previous Page Data mapping and validation](data-mapping-and-validation) [Next Page → Multi tenancy with query prefixes](multi-tenancy-with-query-prefixes)
phoenix Ecto.Schema Ecto.Schema
============
An Ecto schema maps external data into Elixir structs.
The definition of the schema is possible through two main APIs: [`schema/2`](#schema/2) and [`embedded_schema/1`](#embedded_schema/1).
[`schema/2`](#schema/2) is typically used to map data from a persisted source, usually a database table, into Elixir structs and vice-versa. For this reason, the first argument of [`schema/2`](#schema/2) is the source (table) name. Structs defined with [`schema/2`](#schema/2) also contain a `__meta__` field with metadata holding the status of the struct, for example, if it has been built, loaded or deleted.
On the other hand, [`embedded_schema/1`](#embedded_schema/1) is used for defining schemas that are embedded in other schemas or only exist in-memory. For example, you can use such schemas to receive data from a command line interface and validate it, without ever persisting it elsewhere. Such structs do not contain a `__meta__` field, as they are never persisted.
Besides working as data mappers, [`embedded_schema/1`](#embedded_schema/1) and [`schema/2`](#schema/2) can also be used together to decouple how the data is represented in your applications from the database. Let's see some examples.
Example
--------
```
defmodule User do
use Ecto.Schema
schema "users" do
field :name, :string
field :age, :integer, default: 0
field :password, :string, redact: true
has_many :posts, Post
end
end
```
By default, a schema will automatically generate a primary key which is named `id` and of type `:integer`. The `field` macro defines a field in the schema with given name and type. `has_many` associates many posts with the user schema. Schemas are regular structs and can be created and manipulated directly using Elixir's struct API:
```
iex> user = %User{name: "jane"}
iex> %{user | age: 30}
```
However, most commonly, structs are cast, validated and manipulated with the [`Ecto.Changeset`](ecto.changeset) module.
Note that the name of the database table does not need to correlate to your module name. For example, if you are working with a legacy database, you can reference the table name when you define your schema:
```
defmodule User do
use Ecto.Schema
schema "legacy_users" do
# ... fields ...
end
end
```
Embedded schemas are defined similarly to source-based schemas. For example, you can use an embedded schema to represent your UI, mapping and validating its inputs, and then you convert such embedded schema to other schemas that are persisted to the database:
```
defmodule SignUp do
use Ecto.Schema
embedded_schema do
field :name, :string
field :age, :integer
field :email, :string
field :accepts_conditions, :boolean
end
end
defmodule Profile do
use Ecto.Schema
schema "profiles" do
field :name
field :age
belongs_to :account, Account
end
end
defmodule Account do
use Ecto.Schema
schema "accounts" do
field :email
end
end
```
The `SignUp` schema can be cast and validated with the help of the [`Ecto.Changeset`](ecto.changeset) module, and afterwards, you can copy its data to the `Profile` and `Account` structs that will be persisted to the database with the help of [`Ecto.Repo`](ecto.repo).
Redacting fields
-----------------
A field marked with `redact: true` will display a value of `**redacted**` when inspected in changes inside a [`Ecto.Changeset`](ecto.changeset) and be excluded from inspect on the schema unless the schema module is tagged with the option `@ecto_derive_inspect_for_redacted_fields false`.
Schema attributes
------------------
Supported attributes for configuring the defined schema. They must be set after the `use Ecto.Schema` call and before the [`schema/2`](#schema/2) definition.
These attributes are:
* `@primary_key` - configures the schema primary key. It expects a tuple `{field_name, type, options}` with the primary key field name, type (typically `:id` or `:binary_id`, but can be any type) and options. It also accepts `false` to disable the generation of a primary key field. Defaults to `{:id, :id, autogenerate: true}`.
* `@schema_prefix` - configures the schema prefix. Defaults to `nil`, which generates structs and queries without prefix. When set, the prefix will be used by every built struct and on queries whenever the schema is used in a `from` or a `join`. In PostgreSQL, the prefix is called "SCHEMA" (typically set via Postgres' `search_path`). In MySQL the prefix points to databases.
* `@schema_context` - configures the schema context. Defaults to `nil`, which generates structs and queries without context. Context are not used by the built-in SQL adapters.
* `@foreign_key_type` - configures the default foreign key type used by `belongs_to` associations. It must be set in the same module that defines the `belongs_to`. Defaults to `:id`;
* `@timestamps_opts` - configures the default timestamps type used by `timestamps`. Defaults to `[type: :naive_datetime]`;
* `@derive` - the same as `@derive` available in [`Kernel.defstruct/1`](https://hexdocs.pm/elixir/Kernel.html#defstruct/1) as the schema defines a struct behind the scenes;
* `@field_source_mapper` - a function that receives the current field name and returns the mapping of this field name in the underlying source. In other words, it is a mechanism to automatically generate the `:source` option for the `field` macro. It defaults to `fn x -> x end`, where no field transformation is done;
The advantage of configuring the schema via those attributes is that they can be set with a macro to configure application wide defaults.
For example, if your database does not support autoincrementing primary keys and requires something like UUID or a RecordID, you can configure and use `:binary_id` as your primary key type as follows:
```
# Define a module to be used as base
defmodule MyApp.Schema do
defmacro __using__(_) do
quote do
use Ecto.Schema
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
end
end
end
# Now use MyApp.Schema to define new schemas
defmodule MyApp.Comment do
use MyApp.Schema
schema "comments" do
belongs_to :post, MyApp.Post
end
end
```
Any schemas using `MyApp.Schema` will get the `:id` field with type `:binary_id` as the primary key. We explain what the `:binary_id` type entails in the next section.
The `belongs_to` association on `MyApp.Comment` will also define a `:post_id` field with `:binary_id` type that references the `:id` field of the `MyApp.Post` schema.
Primary keys
-------------
Ecto supports two ID types, called `:id` and `:binary_id`, which are often used as the type for primary keys and associations.
The `:id` type is used when the primary key is an integer while the `:binary_id` is used for primary keys in particular binary formats, which may be [`Ecto.UUID`](ecto.uuid) for databases like PostgreSQL and MySQL, or some specific ObjectID or RecordID often imposed by NoSQL databases.
In both cases, both types have their semantics specified by the underlying adapter/database. If you use the `:id` type with `:autogenerate`, it means the database will be responsible for auto-generation of the id. This is often the case for primary keys in relational databases which are auto-incremented.
There are two ways to define primary keys in Ecto: using the `@primary_key` module attribute and using `primary_key: true` as option for [`field/3`](#field/3) in your schema definition. They are not mutually exclusive and can be used together.
Using `@primary_key` should be preferred for single field primary keys and sharing primary key definitions between multiple schemas using macros. Setting `@primary_key` also automatically configures the reference types for `has_one` and `has_many` associations.
Ecto also supports composite primary keys, which is where you need to use `primary_key: true` for the fields in your schema. This usually goes along with setting `@primary_key false` to disable generation of additional primary key fields.
Besides `:id` and `:binary_id`, which are often used by primary and foreign keys, Ecto provides a huge variety of types to be used by any field.
Types and casting
------------------
When defining the schema, types need to be given. Types are split into two categories, primitive types and custom types.
### Primitive types
The primitive types are:
| Ecto type | Elixir type | Literal syntax in query |
| --- | --- | --- |
| `:id` | `integer` | 1, 2, 3 |
| `:binary_id` | `binary` | `<<int, int, int, ...>>` |
| `:integer` | `integer` | 1, 2, 3 |
| `:float` | `float` | 1.0, 2.0, 3.0 |
| `:boolean` | `boolean` | true, false |
| `:string` | UTF-8 encoded `string` | "hello" |
| `:binary` | `binary` | `<<int, int, int, ...>>` |
| `{:array, inner_type}` | `list` | `[value, value, value, ...]` |
| `:map` | `map` | |
| `{:map, inner_type}` | `map` | |
| `:decimal` | [`Decimal`](https://github.com/ericmj/decimal) | |
| `:date` | [`Date`](https://hexdocs.pm/elixir/Date.html) | |
| `:time` | [`Time`](https://hexdocs.pm/elixir/Time.html) | |
| `:time_usec` | [`Time`](https://hexdocs.pm/elixir/Time.html) | |
| `:naive_datetime` | [`NaiveDateTime`](https://hexdocs.pm/elixir/NaiveDateTime.html) | |
| `:naive_datetime_usec` | [`NaiveDateTime`](https://hexdocs.pm/elixir/NaiveDateTime.html) | |
| `:utc_datetime` | [`DateTime`](https://hexdocs.pm/elixir/DateTime.html) | |
| `:utc_datetime_usec` | [`DateTime`](https://hexdocs.pm/elixir/DateTime.html) | |
**Notes:**
* When using database migrations provided by "Ecto SQL", you can pass your Ecto type as the column type. However, note the same Ecto type may support multiple database types. For example, all of `:varchar`, `:text`, `:bytea`, etc. translate to Ecto's `:string`. Similarly, Ecto's `:decimal` can be used for `:numeric` and other database types. For more information, see [all migration types](https://hexdocs.pm/ecto_sql/Ecto.Migration.html#module-field-types).
* For the `{:array, inner_type}` and `{:map, inner_type}` type, replace `inner_type` with one of the valid types, such as `:string`.
* For the `:decimal` type, `+Infinity`, `-Infinity`, and `NaN` values are not supported, even though the [`Decimal`](https://hexdocs.pm/decimal/1.6.0/Decimal.html) library handles them. To support them, you can create a custom type.
* For calendar types with and without microseconds, the precision is enforced when persisting to the DB. For example, casting `~T[09:00:00]` as `:time_usec` will succeed and result in `~T[09:00:00.000000]`, but persisting a type without microseconds as `:time_usec` will fail. Similarly, casting `~T[09:00:00.000000]` as `:time` will succeed, but persisting will not. This is the same behaviour as seen in other types, where casting has to be done explicitly and is never performed implicitly when loading from or dumping to the database.
### Custom types
Besides providing primitive types, Ecto allows custom types to be implemented by developers, allowing Ecto behaviour to be extended.
A custom type is a module that implements one of the [`Ecto.Type`](ecto.type) or [`Ecto.ParameterizedType`](ecto.parameterizedtype) behaviours. By default, Ecto provides the following custom types:
| Custom type | Database type | Elixir type |
| --- | --- | --- |
| [`Ecto.UUID`](ecto.uuid) | `:uuid` (as a binary) | `string()` (as a UUID) |
| [`Ecto.Enum`](ecto.enum) | `:string` | `atom()` |
Finally, schemas can also have virtual fields by passing the `virtual: true` option. These fields are not persisted to the database and can optionally not be type checked by declaring type `:any`.
### The datetime types
Four different datetime primitive types are available:
* `naive_datetime` - has a precision of seconds and casts values to Elixir's [`NaiveDateTime`](https://hexdocs.pm/elixir/NaiveDateTime.html) struct which has no timezone information.
* `naive_datetime_usec` - has a default precision of microseconds and also casts values to [`NaiveDateTime`](https://hexdocs.pm/elixir/NaiveDateTime.html) with no timezone information.
* `utc_datetime` - has a precision of seconds and casts values to Elixir's [`DateTime`](https://hexdocs.pm/elixir/DateTime.html) struct and expects the time zone to be set to UTC.
* `utc_datetime_usec` has a default precision of microseconds and also casts values to [`DateTime`](https://hexdocs.pm/elixir/DateTime.html) expecting the time zone be set to UTC.
All of those types are represented by the same timestamp/datetime in the underlying data storage, the difference are in their precision and how the data is loaded into Elixir.
Having different precisions allows developers to choose a type that will be compatible with the database and your project's precision requirements. For example, some older versions of MySQL do not support microseconds in datetime fields.
When choosing what datetime type to work with, keep in mind that Elixir functions like [`NaiveDateTime.utc_now/0`](https://hexdocs.pm/elixir/NaiveDateTime.html#utc_now/0) have a default precision of 6. Casting a value with a precision greater than 0 to a non-`usec` type will truncate all microseconds and set the precision to 0.
### The map type
The map type allows developers to store an Elixir map directly in the database:
```
# In your migration
create table(:users) do
add :data, :map
end
# In your schema
field :data, :map
# Now in your code
user = Repo.insert! %User{data: %{"foo" => "bar"}}
```
Keep in mind that we advise the map keys to be strings or integers instead of atoms. Atoms may be accepted depending on how maps are serialized but the database will always convert atom keys to strings due to security reasons.
In order to support maps, different databases may employ different techniques. For example, PostgreSQL will store those values in jsonb fields, allowing you to just query parts of it. MSSQL, on the other hand, does not yet provide a JSON type, so the value will be stored in a text field.
For maps to work in such databases, Ecto will need a JSON library. By default Ecto will use [Jason](https://github.com/michalmuskala/jason) which needs to be added to your deps in `mix.exs`:
```
{:jason, "~> 1.0"}
```
You can however configure the adapter to use another library. For example, if using Postgres:
```
config :postgrex, :json_library, YourLibraryOfChoice
```
Or if using MySQL:
```
config :mariaex, :json_library, YourLibraryOfChoice
```
If changing the JSON library, remember to recompile the adapter afterwards by cleaning the current build:
```
mix deps.clean --build postgrex
```
### Casting
When directly manipulating the struct, it is the responsibility of the developer to ensure the field values have the proper type. For example, you can create a user struct with an invalid value for `age`:
```
iex> user = %User{age: "0"}
iex> user.age
"0"
```
However, if you attempt to persist the struct above, an error will be raised since Ecto validates the types when sending them to the adapter/database.
Therefore, when working with and manipulating external data, it is recommended to use [`Ecto.Changeset`](ecto.changeset)'s that are able to filter and properly cast external data:
```
changeset = Ecto.Changeset.cast(%User{}, %{"age" => "0"}, [:age])
user = Repo.insert!(changeset)
```
**You can use Ecto schemas and changesets to cast and validate any kind of data, regardless if the data will be persisted to an Ecto repository or not**.
Reflection
-----------
Any schema module will generate the `__schema__` function that can be used for runtime introspection of the schema:
* `__schema__(:source)` - Returns the source as given to [`schema/2`](#schema/2);
* `__schema__(:prefix)` - Returns optional prefix for source provided by `@schema_prefix` schema attribute;
* `__schema__(:primary_key)` - Returns a list of primary key fields (empty if there is none);
* `__schema__(:fields)` - Returns a list of all non-virtual field names;
* `__schema__(:virtual_fields)` - Returns a list of all virtual field names;
* `__schema__(:field_source, field)` - Returns the alias of the given field;
* `__schema__(:type, field)` - Returns the type of the given non-virtual field;
* `__schema__(:virtual_type, field)` - Returns the type of the given virtual field;
* `__schema__(:associations)` - Returns a list of all association field names;
* `__schema__(:association, assoc)` - Returns the association reflection of the given assoc;
* `__schema__(:embeds)` - Returns a list of all embedded field names;
* `__schema__(:embed, embed)` - Returns the embedding reflection of the given embed;
* `__schema__(:read_after_writes)` - Non-virtual fields that must be read back from the database after every write (insert or update);
* `__schema__(:autogenerate_id)` - Primary key that is auto generated on insert;
* `__schema__(:redact_fields)` - Returns a list of redacted field names;
Furthermore, both `__struct__` and `__changeset__` functions are defined so structs and changeset functionalities are available.
Working with typespecs
-----------------------
Generating typespecs for schemas is out of the scope of [`Ecto.Schema`](ecto.schema#content).
In order to be able to use types such as `User.t()`, `t/0` has to be defined manually:
```
defmodule User do
use Ecto.Schema
@type t :: %__MODULE__{
name: String.t(),
age: non_neg_integer()
}
# ... schema ...
end
```
Defining the type of each field is not mandatory, but it is preferable.
Summary
========
Types
------
[belongs\_to(t)](#t:belongs_to/1) [embedded\_schema()](#t:embedded_schema/0) [embeds\_many(t)](#t:embeds_many/1) [embeds\_one(t)](#t:embeds_one/1) [has\_many(t)](#t:has_many/1) [has\_one(t)](#t:has_one/1) [many\_to\_many(t)](#t:many_to_many/1) [prefix()](#t:prefix/0) [schema()](#t:schema/0) [source()](#t:source/0) [t()](#t:t/0) Functions
----------
[belongs\_to(name, queryable, opts \\ [])](#belongs_to/3) Indicates a one-to-one or many-to-one association with another schema.
[embedded\_schema(list)](#embedded_schema/1) Defines an embedded schema with the given field definitions.
[embeds\_many(name, schema, opts \\ [])](#embeds_many/3) Indicates an embedding of many schemas.
[embeds\_many(name, schema, opts, list)](#embeds_many/4) Indicates an embedding of many schemas.
[embeds\_one(name, schema, opts \\ [])](#embeds_one/3) Indicates an embedding of a schema.
[embeds\_one(name, schema, opts, list)](#embeds_one/4) Indicates an embedding of a schema.
[field(name, type \\ :string, opts \\ [])](#field/3) Defines a field on the schema with given name and type.
[has\_many(name, queryable, opts \\ [])](#has_many/3) Indicates a one-to-many association with another schema.
[has\_one(name, queryable, opts \\ [])](#has_one/3) Indicates a one-to-one association with another schema.
[many\_to\_many(name, queryable, opts \\ [])](#many_to_many/3) Indicates a many-to-many association with another schema.
[schema(source, list)](#schema/2) Defines a schema struct with a source name and field definitions.
[timestamps(opts \\ [])](#timestamps/1) Generates `:inserted_at` and `:updated_at` timestamp fields.
Types
======
### belongs\_to(t)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L456)
```
@type belongs_to(t) :: t | Ecto.Association.NotLoaded.t()
```
### embedded\_schema()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L454)
```
@type embedded_schema() :: %{optional(atom()) => any(), __struct__: atom()}
```
### embeds\_many(t)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L461)
```
@type embeds_many(t) :: [t]
```
### embeds\_one(t)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L460)
```
@type embeds_one(t) :: t
```
### has\_many(t)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L458)
```
@type has_many(t) :: [t] | Ecto.Association.NotLoaded.t()
```
### has\_one(t)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L457)
```
@type has_one(t) :: t | Ecto.Association.NotLoaded.t()
```
### many\_to\_many(t)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L459)
```
@type many_to_many(t) :: [t] | Ecto.Association.NotLoaded.t()
```
### prefix()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L452)
```
@type prefix() :: String.t() | nil
```
### schema()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L453)
```
@type schema() :: %{
optional(atom()) => any(),
__struct__: atom(),
__meta__: Ecto.Schema.Metadata.t()
}
```
### source()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L451)
```
@type source() :: String.t()
```
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L455)
```
@type t() :: schema() | embedded_schema()
```
Functions
==========
### belongs\_to(name, queryable, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L1265)
Indicates a one-to-one or many-to-one association with another schema.
The current schema belongs to zero or one records of the other schema. The other schema often has a `has_one` or a `has_many` field with the reverse association.
You should use `belongs_to` in the table that contains the foreign key. Imagine a company <-> employee relationship. If the employee contains the `company_id` in the underlying database table, we say the employee belongs to company.
In fact, when you invoke this macro, a field with the name of foreign key is automatically defined in the schema for you.
#### Options
* `:foreign_key` - Sets the foreign key field name, defaults to the name of the association suffixed by `_id`. For example, `belongs_to :company` will define foreign key of `:company_id`. The associated `has_one` or `has_many` field in the other schema should also have its `:foreign_key` option set with the same value.
* `:references` - Sets the key on the other schema to be used for the association, defaults to: `:id`
* `:define_field` - When false, does not automatically define a `:foreign_key` field, implying the user is defining the field manually elsewhere
* `:type` - Sets the type of automatically defined `:foreign_key`. Defaults to: `:integer` and can be set per schema via `@foreign_key_type`
* `:on_replace` - The action taken on associations when the record is replaced when casting or manipulating parent changeset. May be `:raise` (default), `:mark_as_invalid`, `:nilify`, `:update`, or `:delete`. See [`Ecto.Changeset`](ecto.changeset)'s section on related data for more info.
* `:defaults` - Default values to use when building the association. It may be a keyword list of options that override the association schema or a atom/`{module, function, args}` that receives the struct and the owner as arguments. For example, if you set `Comment.belongs_to :post, defaults: [public: true]`, then when using `Ecto.build_assoc(comment, :post)`, the post will have `post.public == true`. Alternatively, you can set it to `Comment.belongs_to :post, defaults: :update_post`, which will invoke `Comment.update_post(post, comment)`, or set it to a MFA tuple such as `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(post, comment, arg3, arg4)`
* `:primary_key` - If the underlying belongs\_to field is a primary key
* `:source` - Defines the name that is to be used in database for this field
* `:where` - A filter for the association. See "Filtering associations" in [`has_many/3`](#has_many/3).
#### Examples
```
defmodule Comment do
use Ecto.Schema
schema "comments" do
belongs_to :post, Post
end
end
# The post can come preloaded on the comment record
[comment] = Repo.all(from(c in Comment, where: c.id == 42, preload: :post))
comment.post #=> %Post{...}
```
If you need custom options on the underlying field, you can define the field explicitly and then pass `define_field: false` to `belongs_to`:
```
defmodule Comment do
use Ecto.Schema
schema "comments" do
field :post_id, :integer, ... # custom options
belongs_to :post, Post, define_field: false
end
end
```
#### Polymorphic associations
One common use case for belongs to associations is to handle polymorphism. For example, imagine you have defined a Comment schema and you wish to use it for commenting on both tasks and posts.
Some abstractions would force you to define some sort of polymorphic association with two fields in your database:
```
* commentable_type
* commentable_id
```
The problem with this approach is that it breaks references in the database. You can't use foreign keys and it is very inefficient, both in terms of query time and storage.
In Ecto, we have three ways to solve this issue. The simplest is to define multiple fields in the Comment schema, one for each association:
```
* task_id
* post_id
```
Unless you have dozens of columns, this is simpler for the developer, more DB friendly and more efficient in all aspects.
Alternatively, because Ecto does not tie a schema to a given table, we can use separate tables for each association. Let's start over and define a new Comment schema:
```
defmodule Comment do
use Ecto.Schema
schema "abstract table: comments" do
# This will be used by associations on each "concrete" table
field :assoc_id, :integer
end
end
```
Notice we have changed the table name to "abstract table: comments". You can choose whatever name you want, the point here is that this particular table will never exist.
Now in your Post and Task schemas:
```
defmodule Post do
use Ecto.Schema
schema "posts" do
has_many :comments, {"posts_comments", Comment}, foreign_key: :assoc_id
end
end
defmodule Task do
use Ecto.Schema
schema "tasks" do
has_many :comments, {"tasks_comments", Comment}, foreign_key: :assoc_id
end
end
```
Now each association uses its own specific table, "posts\_comments" and "tasks\_comments", which must be created on migrations. The advantage of this approach is that we never store unrelated data together, also ensuring we keep database references fast and correct.
When using this technique, the only limitation is that you cannot build comments directly. For example, the command below
```
Repo.insert!(%Comment{})
```
will attempt to use the abstract table. Instead, one should use
```
Repo.insert!(build_assoc(post, :comments))
```
leveraging the [`Ecto.build_assoc/3`](ecto#build_assoc/3) function. You can also use [`Ecto.assoc/2`](ecto#assoc/2) or pass a tuple in the query syntax to easily retrieve associated comments to a given post or task:
```
# Fetch all comments associated with the given task
Repo.all(Ecto.assoc(task, :comments))
```
Or all comments in a given table:
```
Repo.all from(c in {"posts_comments", Comment}), ...)
```
The third and final option is to use [`many_to_many/3`](#many_to_many/3) to define the relationships between the resources. In this case, the comments table won't have the foreign key, instead there is an intermediary table responsible for associating the entries:
```
defmodule Comment do
use Ecto.Schema
schema "comments" do
# ...
end
end
```
In your posts and tasks:
```
defmodule Post do
use Ecto.Schema
schema "posts" do
many_to_many :comments, Comment, join_through: "posts_comments"
end
end
defmodule Task do
use Ecto.Schema
schema "tasks" do
many_to_many :comments, Comment, join_through: "tasks_comments"
end
end
```
See [`many_to_many/3`](#many_to_many/3) for more information on this particular approach.
### embedded\_schema(list)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L521)
Defines an embedded schema with the given field definitions.
An embedded schema is either embedded into another schema or kept exclusively in memory. For this reason, an embedded schema does not require a source name and it does not include a metadata field.
Embedded schemas by default set the primary key type to `:binary_id` but such can be configured with the `@primary_key` attribute.
### embeds\_many(name, schema, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L1823)
Indicates an embedding of many schemas.
The current schema has zero or more records of the other schema embedded inside of it. Embeds have all the things regular schemas have.
It is recommended to declare your [`embeds_many/3`](#embeds_many/3) field with type `:map` in your migrations, instead of using `{:array, :map}`. Ecto can work with both maps and arrays as the container for embeds (and in most databases maps are represented as JSON which allows Ecto to choose what works best).
The embedded may or may not have a primary key. Ecto uses the primary keys to detect if an embed is being updated or not. If a primary is not present and you still want the list of embeds to be updated, `:on_replace` must be set to `:delete`, forcing all current embeds to be deleted and replaced by new ones whenever a new list of embeds is set.
For encoding and decoding of embeds, please read the docs for [`embeds_one/3`](#embeds_one/3).
#### Options
* `:on_replace` - The action taken on associations when the embed is replaced when casting or manipulating parent changeset. May be `:raise` (default), `:mark_as_invalid`, or `:delete`. See [`Ecto.Changeset`](ecto.changeset)'s section on related data for more info.
* `:source` - Defines the name that is to be used in database for this field. This is useful when attaching to an existing database. The value should be an atom.
#### Examples
```
defmodule Order do
use Ecto.Schema
schema "orders" do
embeds_many :items, Item
end
end
defmodule Item do
use Ecto.Schema
embedded_schema do
field :title
end
end
# The items are loaded with the order
order = Repo.get!(Order, 42)
order.items #=> [%Item{...}, ...]
```
Adding and removal of embeds can only be done via the [`Ecto.Changeset`](ecto.changeset) API so Ecto can properly track the embed life-cycle:
```
# Order has no items
order = Repo.get!(Order, 42)
order.items
# => []
items = [%Item{title: "Soap"}]
# Generate a changeset
changeset = Ecto.Changeset.change(order)
# Put a one or more new items
changeset = Ecto.Changeset.put_embed(changeset, :items, items)
# Update the order and fetch items
items = Repo.update!(changeset).items
# Items are generated with a unique identification
items
# => [%Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Soap"}]
```
Updating of embeds must be done using a changeset for each changed embed.
```
# Order has an existing items
order = Repo.get!(Order, 42)
order.items
# => [%Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Soap"}]
# Generate a changeset
changeset = Ecto.Changeset.change(order)
# Put the updated item as a changeset
current_item = List.first(order.items)
item_changeset = Ecto.Changeset.change(current_item, title: "Mujju's Soap")
order_changeset = Ecto.Changeset.put_embed(changeset, :items, [item_changeset])
# Update the order and fetch items
items = Repo.update!(order_changeset).items
# Item has the updated title
items
# => [%Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Mujju's Soap"}]
```
#### Inline embedded schema
The schema module can be defined inline in the parent schema in simple cases:
```
defmodule Parent do
use Ecto.Schema
schema "parents" do
field :name, :string
embeds_many :children, Child do
field :name, :string
field :age, :integer
end
end
end
```
Primary keys are automatically set up for embedded schemas as well, defaulting to `{:id, :binary_id, autogenerate: true}`. You can customize it by passing a `:primary_key` option with the same arguments as `@primary_key` (see the [Schema attributes](ecto.schema#module-schema-attributes) section for more info).
Defining embedded schema in such a way will define a `Parent.Child` module with the appropriate struct. In order to properly cast the embedded schema. When casting the inline-defined embedded schemas you need to use the `:with` option of `cast_embed/3` to provide the proper function to do the casting. For example:
```
def changeset(schema, params) do
schema
|> cast(params, [:name])
|> cast_embed(:children, with: &child_changeset/2)
end
defp child_changeset(schema, params) do
schema
|> cast(params, [:name, :age])
end
```
### embeds\_many(name, schema, opts, list)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L1843)
Indicates an embedding of many schemas.
For options and examples see documentation of [`embeds_many/3`](#embeds_many/3).
### embeds\_one(name, schema, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L1656)
Indicates an embedding of a schema.
The current schema has zero or one records of the other schema embedded inside of it. It uses a field similar to the `:map` type for storage, but allows embeds to have all the things regular schema can.
You must declare your [`embeds_one/3`](#embeds_one/3) field with type `:map` at the database level.
The embedded may or may not have a primary key. Ecto uses the primary keys to detect if an embed is being updated or not. If a primary key is not present, `:on_replace` should be set to either `:update` or `:delete` if there is a desire to either update or delete the current embed when a new one is set.
#### Options
* `:on_replace` - The action taken on associations when the embed is replaced when casting or manipulating parent changeset. May be `:raise` (default), `:mark_as_invalid`, `:update`, or `:delete`. See [`Ecto.Changeset`](ecto.changeset)'s section on related data for more info.
* `:source` - Defines the name that is to be used in database for this field. This is useful when attaching to an existing database. The value should be an atom.
#### Examples
```
defmodule Order do
use Ecto.Schema
schema "orders" do
embeds_one :item, Item
end
end
defmodule Item do
use Ecto.Schema
embedded_schema do
field :title
end
end
# The item is loaded with the order
order = Repo.get!(Order, 42)
order.item #=> %Item{...}
```
Adding and removal of embeds can only be done via the [`Ecto.Changeset`](ecto.changeset) API so Ecto can properly track the embed life-cycle:
```
order = Repo.get!(Order, 42)
item = %Item{title: "Soap"}
# Generate a changeset
changeset = Ecto.Changeset.change(order)
# Put a new embed to the changeset
changeset = Ecto.Changeset.put_embed(changeset, :item, item)
# Update the order, and fetch the item
item = Repo.update!(changeset).item
# Item is generated with a unique identification
item
# => %Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Soap"}
```
#### Inline embedded schema
The schema module can be defined inline in the parent schema in simple cases:
```
defmodule Parent do
use Ecto.Schema
schema "parents" do
field :name, :string
embeds_one :child, Child do
field :name, :string
field :age, :integer
end
end
end
```
Options should be passed before the `do` block like this:
```
embeds_one :child, Child, on_replace: :delete do
field :name, :string
field :age, :integer
end
```
Primary keys are automatically set up for embedded schemas as well, defaulting to `{:id, :binary_id, autogenerate: true}`. You can customize it by passing a `:primary_key` option with the same arguments as `@primary_key` (see the [Schema attributes](ecto.schema#module-schema-attributes) section for more info).
Defining embedded schema in such a way will define a `Parent.Child` module with the appropriate struct. In order to properly cast the embedded schema. When casting the inline-defined embedded schemas you need to use the `:with` option of [`Ecto.Changeset.cast_embed/3`](ecto.changeset#cast_embed/3) to provide the proper function to do the casting. For example:
```
def changeset(schema, params) do
schema
|> cast(params, [:name])
|> cast_embed(:child, with: &child_changeset/2)
end
defp child_changeset(schema, params) do
schema
|> cast(params, [:name, :age])
end
```
#### Encoding and decoding
Because many databases do not support direct encoding and decoding of embeds, it is often emulated by Ecto by using specific encoding and decoding rules.
For example, PostgreSQL will store embeds on top of JSONB columns, which means types in embedded schemas won't go through the usual dump->DB->load cycle but rather encode->DB->decode->cast. This means that, when using embedded schemas with databases like PG or MySQL, make sure all of your types can be JSON encoded/decoded correctly. Ecto provides this guarantee for all built-in types.
### embeds\_one(name, schema, opts, list)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L1676)
Indicates an embedding of a schema.
For options and examples see documentation of [`embeds_one/3`](#embeds_one/3).
### field(name, type \\ :string, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L720)
Defines a field on the schema with given name and type.
The field name will be used as is to read and write to the database by all of the built-in adapters unless overridden with the `:source` option.
#### Options
* `:default` - Sets the default value on the schema and the struct.
The default value is calculated at compilation time, so don't use expressions like `DateTime.utc_now` or `Ecto.UUID.generate` as they would then be the same for all records: in this scenario you can use the `:autogenerate` option to generate at insertion time.
The default value is validated against the field's type at compilation time and it will raise an ArgumentError if there is a type mismatch. If you cannot infer the field's type at compilation time, you can use the `:skip_default_validation` option on the field to skip validations.
Once a default value is set, if you send changes to the changeset that contains the same value defined as default, validations will not be performed since there are no changes after all.
* `:source` - Defines the name that is to be used in database for this field. This is useful when attaching to an existing database. The value should be an atom.
* `:autogenerate` - a `{module, function, args}` tuple for a function to call to generate the field value before insertion if value is not set. A shorthand value of `true` is equivalent to `{type, :autogenerate, []}`.
* `:read_after_writes` - When true, the field is always read back from the database after insert and updates.
For relational databases, this means the RETURNING option of those statements is used. For this reason, MySQL does not support this option and will raise an error if a schema is inserted/updated with read after writes fields.
* `:virtual` - When true, the field is not persisted to the database. Notice virtual fields do not support `:autogenerate` nor `:read_after_writes`.
* `:primary_key` - When true, the field is used as part of the composite primary key.
* `:load_in_query` - When false, the field will not be loaded when selecting the whole struct in a query, such as `from p in Post, select: p`. Defaults to `true`.
* `:redact` - When true, it will display a value of `**redacted**` when inspected in changes inside a [`Ecto.Changeset`](ecto.changeset) and be excluded from inspect on the schema. Defaults to `false`.
* `:skip_default_validation` - When true, it will skip the type validation step at compile time.
### has\_many(name, queryable, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L989)
Indicates a one-to-many association with another schema.
The current schema has zero or more records of the other schema. The other schema often has a `belongs_to` field with the reverse association.
#### Options
* `:foreign_key` - Sets the foreign key, this should map to a field on the other schema, defaults to the underscored name of the current schema suffixed by `_id`
* `:references` - Sets the key on the current schema to be used for the association, defaults to the primary key on the schema
* `:through` - Allow this association to be defined in terms of existing associations. Read the section on `:through` associations for more info
* `:on_delete` - The action taken on associations when parent record is deleted. May be `:nothing` (default), `:nilify_all` and `:delete_all`. Using this option is DISCOURAGED for most relational databases. Instead, in your migration, set `references(:parent_id, on_delete: :delete_all)`. Opposite to the migration option, this option cannot guarantee integrity and it is only triggered for [`Ecto.Repo.delete/2`](ecto.repo#c:delete/2) (and not on [`Ecto.Repo.delete_all/2`](ecto.repo#c:delete_all/2)) and it never cascades. If posts has many comments, which has many tags, and you delete a post, only comments will be deleted. If your database does not support references, cascading can be manually implemented by using [`Ecto.Multi`](ecto.multi) or [`Ecto.Changeset.prepare_changes/2`](ecto.changeset#prepare_changes/2).
* `:on_replace` - The action taken on associations when the record is replaced when casting or manipulating parent changeset. May be `:raise` (default), `:mark_as_invalid`, `:nilify`, `:delete` or `:delete_if_exists`. See [`Ecto.Changeset`](ecto.changeset)'s section about `:on_replace` for more info.
* `:defaults` - Default values to use when building the association. It may be a keyword list of options that override the association schema or a atom/`{module, function, args}` that receives the struct and the owner as arguments. For example, if you set `Post.has_many :comments, defaults: [public: true]`, then when using `Ecto.build_assoc(post, :comments)`, the comment will have `comment.public == true`. Alternatively, you can set it to `Post.has_many :comments, defaults: :update_comment`, which will invoke `Post.update_comment(comment, post)`, or set it to a MFA tuple such as `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(comment, post, arg3, arg4)`
* `:where` - A filter for the association. See "Filtering associations" below. It does not apply to `:through` associations.
* `:preload_order` - Sets the default `order_by` of the association. It is used when the association is preloaded. For example, if you set `Post.has_many :comments, preload_order: [asc: :content]`, whenever the `:comments` associations is preloaded, the comments will be order by the `:content` field. See [`Ecto.Query.order_by/3`](ecto.query#order_by/3) for more examples.
#### Examples
```
defmodule Post do
use Ecto.Schema
schema "posts" do
has_many :comments, Comment
end
end
# Get all comments for a given post
post = Repo.get(Post, 42)
comments = Repo.all assoc(post, :comments)
# The comments can come preloaded on the post struct
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments))
post.comments #=> [%Comment{...}, ...]
```
`has_many` can be used to define hierarchical relationships within a single schema, for example threaded comments.
```
defmodule Comment do
use Ecto.Schema
schema "comments" do
field :content, :string
field :parent_id, :integer
belongs_to :parent, Comment, foreign_key: :parent_id, references: :id, define_field: false
has_many :children, Comment, foreign_key: :parent_id, references: :id
end
end
```
#### Filtering associations
It is possible to specify a `:where` option that will filter the records returned by the association. Querying, joining or preloading the association will use the given conditions as shown next:
```
defmodule Post do
use Ecto.Schema
schema "posts" do
has_many :public_comments, Comment,
where: [public: true]
end
end
```
The `:where` option expects a keyword list where the key is an atom representing the field and the value is either:
* `nil` - which specifies the field must be nil
* `{:not, nil}` - which specifies the field must not be nil
* `{:in, list}` - which specifies the field must be one of the values in a list
* `{:fragment, expr}` - which specifies a fragment string as the filter (see [`Ecto.Query.API.fragment/1`](ecto.query.api#fragment/1)) with the field's value given to it as the only argument
* or any other value which the field is compared directly against
Note the values above are distinctly different from the values you would pass to `where` when building a query. For example, if you attempt to build a query such as
```
from Post, where: [id: nil]
```
it will emit an error. This is because queries can be built dynamically, and therefore passing `nil` can lead to security errors. However, the `:where` values for an association are given at compile-time, which is less dynamic and cannot leverage the full power of Ecto queries, which explains why they have different APIs.
**Important!** Please use this feature only when strictly necessary, otherwise it is very easy to end-up with large schemas with dozens of different associations polluting your schema and affecting your application performance. For instance, if you are using associations only for different querying purposes, then it is preferable to build and compose queries. For instance, instead of having two associations, one for comments and another for deleted comments, you might have a single comments association and filter it instead:
```
posts
|> Ecto.assoc(:comments)
|> Comment.deleted()
```
Or when preloading:
```
from posts, preload: [comments: ^Comment.deleted()]
```
#### has\_many/has\_one :through
Ecto also supports defining associations in terms of other associations via the `:through` option. Let's see an example:
```
defmodule Post do
use Ecto.Schema
schema "posts" do
has_many :comments, Comment
has_one :permalink, Permalink
# In the has_many :through example below, the `:comments`
# in the list [:comments, :author] refers to the
# `has_many :comments` in the Post own schema and the
# `:author` refers to the `belongs_to :author` of the
# Comment's schema (the module below).
# (see the description below for more details)
has_many :comments_authors, through: [:comments, :author]
# Specify the association with custom source
has_many :tags, {"posts_tags", Tag}
end
end
defmodule Comment do
use Ecto.Schema
schema "comments" do
belongs_to :author, Author
belongs_to :post, Post
has_one :post_permalink, through: [:post, :permalink]
end
end
```
In the example above, we have defined a `has_many :through` association named `:comments_authors`. A `:through` association always expects a list and the first element of the list must be a previously defined association in the current module. For example, `:comments_authors` first points to `:comments` in the same module (Post), which then points to `:author` in the next schema, `Comment`.
This `:through` association will return all authors for all comments that belongs to that post:
```
# Get all comments authors for a given post
post = Repo.get(Post, 42)
authors = Repo.all assoc(post, :comments_authors)
```
`:through` associations can also be preloaded. In such cases, not only the `:through` association is preloaded but all intermediate steps are preloaded too:
```
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments_authors))
post.comments_authors #=> [%Author{...}, ...]
# The comments for each post will be preloaded too
post.comments #=> [%Comment{...}, ...]
# And the author for each comment too
hd(post.comments).author #=> %Author{...}
```
When the `:through` association is expected to return one or zero items, `has_one :through` should be used instead, as in the example at the beginning of this section:
```
# How we defined the association above
has_one :post_permalink, through: [:post, :permalink]
# Get a preloaded comment
[comment] = Repo.all(Comment) |> Repo.preload(:post_permalink)
comment.post_permalink #=> %Permalink{...}
```
Note `:through` associations are read-only. For example, you cannot use [`Ecto.Changeset.cast_assoc/3`](ecto.changeset#cast_assoc/3) to modify through associations.
### has\_one(name, queryable, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L1060)
Indicates a one-to-one association with another schema.
The current schema has zero or one records of the other schema. The other schema often has a `belongs_to` field with the reverse association.
#### Options
* `:foreign_key` - Sets the foreign key, this should map to a field on the other schema, defaults to the underscored name of the current module suffixed by `_id`
* `:references` - Sets the key on the current schema to be used for the association, defaults to the primary key on the schema
* `:through` - If this association must be defined in terms of existing associations. Read the section in [`has_many/3`](#has_many/3) for more information
* `:on_delete` - The action taken on associations when parent record is deleted. May be `:nothing` (default), `:nilify_all` and `:delete_all`. Using this option is DISCOURAGED for most relational databases. Instead, in your migration, set `references(:parent_id, on_delete: :delete_all)`. Opposite to the migration option, this option cannot guarantee integrity and it is only triggered for [`Ecto.Repo.delete/2`](ecto.repo#c:delete/2) (and not on [`Ecto.Repo.delete_all/2`](ecto.repo#c:delete_all/2)) and it never cascades. If posts has many comments, which has many tags, and you delete a post, only comments will be deleted. If your database does not support references, cascading can be manually implemented by using [`Ecto.Multi`](ecto.multi) or [`Ecto.Changeset.prepare_changes/2`](ecto.changeset#prepare_changes/2)
* `:on_replace` - The action taken on associations when the record is replaced when casting or manipulating parent changeset. May be `:raise` (default), `:mark_as_invalid`, `:nilify`, `:update`, or `:delete`. See [`Ecto.Changeset`](ecto.changeset)'s section on related data for more info.
* `:defaults` - Default values to use when building the association. It may be a keyword list of options that override the association schema or as a atom/`{module, function, args}` that receives the struct and the owner as arguments. For example, if you set `Post.has_one :banner, defaults: [public: true]`, then when using `Ecto.build_assoc(post, :banner)`, the banner will have `banner.public == true`. Alternatively, you can set it to `Post.has_one :banner, defaults: :update_banner`, which will invoke `Post.update_banner(banner, post)`, or set it to a MFA tuple such as `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(banner, post, arg3, arg4)`
* `:where` - A filter for the association. See "Filtering associations" in [`has_many/3`](#has_many/3). It does not apply to `:through` associations.
#### Examples
```
defmodule Post do
use Ecto.Schema
schema "posts" do
has_one :permalink, Permalink
# Specify the association with custom source
has_one :category, {"posts_categories", Category}
end
end
# The permalink can come preloaded on the post struct
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :permalink))
post.permalink #=> %Permalink{...}
```
### many\_to\_many(name, queryable, opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L1517)
Indicates a many-to-many association with another schema.
The association happens through a join schema or source, containing foreign keys to the associated schemas. For example, the association below:
```
# from MyApp.Post
many_to_many :tags, MyApp.Tag, join_through: "posts_tags"
```
is backed by relational databases through a join table as follows:
```
[Post] <-> [posts_tags] <-> [Tag]
id <-- post_id
tag_id --> id
```
More information on the migration for creating such a schema is shown below.
#### Options
* `:join_through` - Specifies the source of the associated data. It may be a string, like "posts\_tags", representing the underlying storage table or an atom, like `MyApp.PostTag`, representing a schema. This option is required.
* `:join_keys` - Specifies how the schemas are associated. It expects a keyword list with two entries, the first being how the join table should reach the current schema and the second how the join table should reach the associated schema. In the example above, it defaults to: `[post_id: :id, tag_id: :id]`. The keys are inflected from the schema names.
* `:on_delete` - The action taken on associations when the parent record is deleted. May be `:nothing` (default) or `:delete_all`. Using this option is DISCOURAGED for most relational databases. Instead, in your migration, set `references(:parent_id, on_delete: :delete_all)`. Opposite to the migration option, this option cannot guarantee integrity and it is only triggered for [`Ecto.Repo.delete/2`](ecto.repo#c:delete/2) (and not on [`Ecto.Repo.delete_all/2`](ecto.repo#c:delete_all/2)). This option can only remove data from the join source, never the associated records, and it never cascades.
* `:on_replace` - The action taken on associations when the record is replaced when casting or manipulating parent changeset. May be `:raise` (default), `:mark_as_invalid`, or `:delete`. `:delete` will only remove data from the join source, never the associated records. See [`Ecto.Changeset`](ecto.changeset)'s section on related data for more info.
* `:defaults` - Default values to use when building the association. It may be a keyword list of options that override the association schema or a atom/`{module, function, args}` that receives the struct and the owner as arguments. For example, if you set `Post.many_to_many :tags, defaults: [public: true]`, then when using `Ecto.build_assoc(post, :tags)`, the tag will have `tag.public == true`. Alternatively, you can set it to `Post.many_to_many :tags, defaults: :update_tag`, which will invoke `Post.update_tag(tag, post)`, or set it to a MFA tuple such as `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(tag, post, arg3, arg4)`
* `:join_defaults` - The same as `:defaults` but it applies to the join schema instead. This option will raise if it is given and the `:join_through` value is not a schema.
* `:unique` - When true, checks if the associated entries are unique whenever the association is cast or changed via the parent record. For instance, it would verify that a given tag cannot be attached to the same post more than once. This exists mostly as a quick check for user feedback, as it does not guarantee uniqueness at the database level. Therefore, you should also set a unique index in the database join table, such as: `create unique_index(:posts_tags, [:post_id, :tag_id])`
* `:where` - A filter for the association. See "Filtering associations" in [`has_many/3`](#has_many/3)
* `:join_where` - A filter for the join table. See "Filtering associations" in [`has_many/3`](#has_many/3)
* `:preload_order` - Sets the default `order_by` of the association. It is used when the association is preloaded. For example, if you set `Post.many_to_many :tags, Tag, join_through: "posts_tags", preload_order: [asc: :foo]`, whenever the `:tags` associations is preloaded, the tags will be order by the `:foo` field. See [`Ecto.Query.order_by/3`](ecto.query#order_by/3) for more examples.
#### Using Ecto.assoc/2
One of the benefits of using `many_to_many` is that Ecto will avoid loading the intermediate whenever possible, making your queries more efficient. For this reason, developers should not refer to the join table of `many_to_many` in queries. The join table is accessible in few occasions, such as in [`Ecto.assoc/2`](ecto#assoc/2). For example, if you do this:
```
post
|> Ecto.assoc(:tags)
|> where([t, _pt, p], p.public == t.public)
```
It may not work as expected because the `posts_tags` table may not be included in the query. You can address this problem in multiple ways. One option is to use `...`:
```
post
|> Ecto.assoc(:tags)
|> where([t, ..., p], p.public == t.public)
```
Another and preferred option is to rewrite to an explicit `join`, which leaves out the intermediate bindings as they are resolved only later on:
```
# keyword syntax
from t in Tag,
join: p in assoc(t, :post), on: p.id == ^post.id
# pipe syntax
Tag
|> join(:inner, [t], p in assoc(t, :post), on: p.id == ^post.id)
```
If you need to access the join table, then you likely want to use [`has_many/3`](#has_many/3) with the `:through` option instead.
#### Removing data
If you attempt to remove associated `many_to_many` data, **Ecto will always remove data from the join schema and never from the target associations** be it by setting `:on_replace` to `:delete`, `:on_delete` to `:delete_all` or by using changeset functions such as [`Ecto.Changeset.put_assoc/3`](ecto.changeset#put_assoc/3). For example, if a `Post` has a many to many relationship with `Tag`, setting `:on_delete` to `:delete_all` will only delete entries from the "posts\_tags" table in case `Post` is deleted.
#### Migration
How your migration should be structured depends on the value you pass in `:join_through`. If `:join_through` is simply a string, representing a table, you may define a table without primary keys and you must not include any further columns, as those values won't be set by Ecto:
```
create table(:posts_tags, primary_key: false) do
add :post_id, references(:posts)
add :tag_id, references(:tags)
end
```
However, if your `:join_through` is a schema, like `MyApp.PostTag`, your join table may be structured as any other table in your codebase, including timestamps:
```
create table(:posts_tags) do
add :post_id, references(:posts)
add :tag_id, references(:tags)
timestamps()
end
```
Because `:join_through` contains a schema, in such cases, autogenerated values and primary keys will be automatically handled by Ecto.
#### Examples
```
defmodule Post do
use Ecto.Schema
schema "posts" do
many_to_many :tags, Tag, join_through: "posts_tags"
end
end
# Let's create a post and a tag
post = Repo.insert!(%Post{})
tag = Repo.insert!(%Tag{name: "introduction"})
# We can associate at any time post and tags together using changesets
post
|> Repo.preload(:tags) # Load existing data
|> Ecto.Changeset.change() # Build the changeset
|> Ecto.Changeset.put_assoc(:tags, [tag]) # Set the association
|> Repo.update!
# In a later moment, we may get all tags for a given post
post = Repo.get(Post, 42)
tags = Repo.all(assoc(post, :tags))
# The tags may also be preloaded on the post struct for reading
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :tags))
post.tags #=> [%Tag{...}, ...]
```
#### Join Schema Example
You may prefer to use a join schema to handle many\_to\_many associations. The decoupled nature of Ecto allows us to create a "join" struct which `belongs_to` both sides of the many to many association.
In our example, a `User` has and belongs to many `Organization`s:
```
defmodule MyApp.Repo.Migrations.CreateUserOrganization do
use Ecto.Migration
def change do
create table(:users_organizations) do
add :user_id, references(:users)
add :organization_id, references(:organizations)
timestamps()
end
end
end
defmodule UserOrganization do
use Ecto.Schema
@primary_key false
schema "users_organizations" do
belongs_to :user, User
belongs_to :organization, Organization
timestamps() # Added bonus, a join schema will also allow you to set timestamps
end
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:user_id, :organization_id])
|> Ecto.Changeset.validate_required([:user_id, :organization_id])
# Maybe do some counter caching here!
end
end
defmodule User do
use Ecto.Schema
schema "users" do
many_to_many :organizations, Organization, join_through: UserOrganization
end
end
defmodule Organization do
use Ecto.Schema
schema "organizations" do
many_to_many :users, User, join_through: UserOrganization
end
end
# Then to create the association, pass in the ID's of an existing
# User and Organization to UserOrganization.changeset
changeset = UserOrganization.changeset(%UserOrganization{}, %{user_id: id, organization_id: id})
case Repo.insert(changeset) do
{:ok, assoc} -> # Assoc was created!
{:error, changeset} -> # Handle the error
end
```
### schema(source, list)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L532)
Defines a schema struct with a source name and field definitions.
An additional field called `__meta__` is added to the struct for storing internal Ecto state. This field always has a [`Ecto.Schema.Metadata`](ecto.schema.metadata) struct as value and can be manipulated with the [`Ecto.put_meta/2`](ecto#put_meta/2) function.
### timestamps(opts \\ [])[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/schema.ex#L744)
Generates `:inserted_at` and `:updated_at` timestamp fields.
The fields generated by this macro will automatically be set to the current time when inserting and updating values in a repository.
#### Options
* `:inserted_at` - the Ecto schema name of the field for insertion times or `false`
* `:updated_at` - the Ecto schema name of the field for update times or `false`
* `:inserted_at_source` - the name of the database column for insertion times or `false`
* `:updated_at_source` - the name of the database column for update times or `false`
* `:type` - the timestamps type, defaults to `:naive_datetime`.
* `:autogenerate` - a module-function-args tuple used for generating both `inserted_at` and `updated_at` timestamps
All options can be pre-configured by setting `@timestamps_opts`.
| programming_docs |
phoenix Ecto.NoPrimaryKeyFieldError exception Ecto.NoPrimaryKeyFieldError exception
======================================
Raised at runtime when an operation that requires a primary key is invoked with a schema that does not define a primary key by using `@primary_key false`
phoenix Ecto.Association.Has Ecto.Association.Has
=====================
The association struct for `has_one` and `has_many` associations.
Its fields are:
* `cardinality` - The association cardinality
* `field` - The name of the association field on the schema
* `owner` - The schema where the association was defined
* `related` - The schema that is associated
* `owner_key` - The key on the `owner` schema used for the association
* `related_key` - The key on the `related` schema used for the association
* `queryable` - The real query to use for querying association
* `on_delete` - The action taken on associations when schema is deleted
* `on_replace` - The action taken on associations when schema is replaced
* `defaults` - Default fields used when building the association
* `relationship` - The relationship to the specified schema, default is `:child`
* `preload_order` - Default `order_by` of the association, used only by preload
phoenix Ecto.Query.WindowAPI Ecto.Query.WindowAPI
=====================
Lists all windows functions.
Windows functions must always be used as the first argument of [`over/2`](#over/2) where the second argument is the name of a window:
```
from e in Employee,
select: {e.depname, e.empno, e.salary, over(avg(e.salary), :department)},
windows: [department: [partition_by: e.depname]]
```
In the example above, we get the average salary per department. `:department` is the window name, partitioned by `e.depname` and [`avg/1`](#avg/1) is the window function.
However, note that defining a window is not necessary, as the window definition can be given as the second argument to `over`:
```
from e in Employee,
select: {e.depname, e.empno, e.salary, over(avg(e.salary), partition_by: e.depname)}
```
Both queries are equivalent. However, if you are using the same partitioning over and over again, defining a window will reduce the query size. See [`Ecto.Query.windows/3`](ecto.query#windows/3) for all possible window expressions, such as `:partition_by` and `:order_by`.
Summary
========
Functions
----------
[avg(value)](#avg/1) Calculates the average for the given entry.
[count()](#count/0) Counts the entries in the table.
[count(value)](#count/1) Counts the given entry.
[cume\_dist()](#cume_dist/0) Returns relative rank of the current row: (number of rows preceding or peer with current row) / (total rows).
[dense\_rank()](#dense_rank/0) Returns rank of the current row without gaps; this function counts peer groups.
[filter(value, filter)](#filter/2) Applies the given expression as a FILTER clause against an aggregate. This is currently only supported by Postgres.
[first\_value(value)](#first_value/1) Returns value evaluated at the row that is the first row of the window frame.
[lag(value, offset \\ 1, default \\ nil)](#lag/3) Returns value evaluated at the row that is offset rows before the current row within the partition.
[last\_value(value)](#last_value/1) Returns value evaluated at the row that is the last row of the window frame.
[lead(value, offset \\ 1, default \\ nil)](#lead/3) Returns value evaluated at the row that is offset rows after the current row within the partition.
[max(value)](#max/1) Calculates the maximum for the given entry.
[min(value)](#min/1) Calculates the minimum for the given entry.
[nth\_value(value, nth)](#nth_value/2) Returns value evaluated at the row that is the nth row of the window frame (counting from 1); `nil` if no such row.
[ntile(num\_buckets)](#ntile/1) Returns integer ranging from 1 to the argument value, dividing the partition as equally as possible.
[over(window\_function, window\_name)](#over/2) Defines a value based on the function and the window. See moduledoc for more information.
[percent\_rank()](#percent_rank/0) Returns relative rank of the current row: (rank - 1) / (total rows - 1).
[rank()](#rank/0) Returns rank of the current row with gaps; same as [`row_number/0`](#row_number/0) of its first peer.
[row\_number()](#row_number/0) Returns number of the current row within its partition, counting from 1.
[sum(value)](#sum/1) Calculates the sum for the given entry.
Functions
==========
### avg(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L49)
Calculates the average for the given entry.
```
from p in Payment, select: avg(p.value)
```
### count()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L35)
Counts the entries in the table.
```
from p in Post, select: count()
```
### count(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L42)
Counts the given entry.
```
from p in Post, select: count(p.id)
```
### cume\_dist()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L128)
Returns relative rank of the current row: (number of rows preceding or peer with current row) / (total rows).
```
from p in Post,
select: cume_dist() |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### dense\_rank()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L107)
Returns rank of the current row without gaps; this function counts peer groups.
```
from p in Post,
select: dense_rank() |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### filter(value, filter)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L171)
Applies the given expression as a FILTER clause against an aggregate. This is currently only supported by Postgres.
```
from p in Post,
select: avg(p.value)
|> filter(p.value > 0 and p.value < 100)
|> over(partition_by: p.category_id, order_by: p.date)
```
### first\_value(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L148)
Returns value evaluated at the row that is the first row of the window frame.
```
from p in Post,
select: first_value(p.id) |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### lag(value, offset \\ 1, default \\ nil)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L204)
Returns value evaluated at the row that is offset rows before the current row within the partition.
If there is no such row, instead return default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to `nil`.
```
from e in Events,
windows: [w: [partition_by: e.name, order_by: e.tick]],
select: {
e.tick,
e.action,
e.name,
lag(e.action) |> over(:w), # previous_action
lead(e.action) |> over(:w) # next_action
}
```
Note that this function must be invoked using window function syntax.
### last\_value(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L158)
Returns value evaluated at the row that is the last row of the window frame.
```
from p in Post,
select: last_value(p.id) |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### lead(value, offset \\ 1, default \\ nil)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L226)
Returns value evaluated at the row that is offset rows after the current row within the partition.
If there is no such row, instead return default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to `nil`.
```
from e in Events,
windows: [w: [partition_by: e.name, order_by: e.tick]],
select: {
e.tick,
e.action,
e.name,
lag(e.action) |> over(:w), # previous_action
lead(e.action) |> over(:w) # next_action
}
```
Note that this function must be invoked using window function syntax.
### max(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L70)
Calculates the maximum for the given entry.
```
from p in Payment, select: max(p.value)
```
### min(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L63)
Calculates the minimum for the given entry.
```
from p in Payment, select: min(p.value)
```
### nth\_value(value, nth)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L182)
Returns value evaluated at the row that is the nth row of the window frame (counting from 1); `nil` if no such row.
```
from p in Post,
select: nth_value(p.id, 4) |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### ntile(num\_buckets)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L138)
Returns integer ranging from 1 to the argument value, dividing the partition as equally as possible.
```
from p in Post,
select: ntile(10) |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### over(window\_function, window\_name)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L77)
Defines a value based on the function and the window. See moduledoc for more information.
```
from e in Employee, select: over(avg(e.salary), partition_by: e.depname)
```
### percent\_rank()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L117)
Returns relative rank of the current row: (rank - 1) / (total rows - 1).
```
from p in Post,
select: percent_rank() |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### rank()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L97)
Returns rank of the current row with gaps; same as [`row_number/0`](#row_number/0) of its first peer.
```
from p in Post,
select: rank() |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### row\_number()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L87)
Returns number of the current row within its partition, counting from 1.
```
from p in Post,
select: row_number() |> over(partition_by: p.category_id, order_by: p.date)
```
Note that this function must be invoked using window function syntax.
### sum(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/query/window_api.ex#L56)
Calculates the sum for the given entry.
```
from p in Payment, select: sum(p.value)
```
phoenix Ecto.Association.ManyToMany Ecto.Association.ManyToMany
============================
The association struct for `many_to_many` associations.
Its fields are:
* `cardinality` - The association cardinality
* `field` - The name of the association field on the schema
* `owner` - The schema where the association was defined
* `related` - The schema that is associated
* `owner_key` - The key on the `owner` schema used for the association
* `queryable` - The real query to use for querying association
* `on_delete` - The action taken on associations when schema is deleted
* `on_replace` - The action taken on associations when schema is replaced
* `defaults` - Default fields used when building the association
* `relationship` - The relationship to the specified schema, default `:child`
* `join_keys` - The keyword list with many to many join keys
* `join_through` - Atom (representing a schema) or a string (representing a table) for many to many associations
* `join_defaults` - A list of defaults for join associations
* `preload_order` - Default `order_by` of the association, used only by preload
Summary
========
Functions
----------
[assoc\_query(refl, values)](#assoc_query/2) Functions
==========
### assoc\_query(refl, values)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/association.ex#L1256)
phoenix Ecto.Adapter.Schema behaviour Ecto.Adapter.Schema behaviour
==============================
Specifies the schema API required from adapters.
Summary
========
Types
------
[adapter\_meta()](#t:adapter_meta/0) Proxy type to the adapter meta
[constraints()](#t:constraints/0) [fields()](#t:fields/0) [filters()](#t:filters/0) [on\_conflict()](#t:on_conflict/0) [options()](#t:options/0) [placeholders()](#t:placeholders/0) [returning()](#t:returning/0) [schema\_meta()](#t:schema_meta/0) Ecto.Schema metadata fields
Callbacks
----------
[autogenerate(field\_type)](#c:autogenerate/1) Called to autogenerate a value for id/embed\_id/binary\_id.
[delete(adapter\_meta, schema\_meta, filters, options)](#c:delete/4) Deletes a single struct with the given filters.
[insert(adapter\_meta, schema\_meta, fields, on\_conflict, returning, options)](#c:insert/6) Inserts a single new struct in the data store.
[insert\_all( adapter\_meta, schema\_meta, header, list, on\_conflict, returning, placeholders, options )](#c:insert_all/8) Inserts multiple entries into the data store.
[update(adapter\_meta, schema\_meta, fields, filters, returning, options)](#c:update/6) Updates a single struct with the given filters.
Types
======
### adapter\_meta()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L7)
```
@type adapter_meta() :: Ecto.Adapter.adapter_meta()
```
Proxy type to the adapter meta
### constraints()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L20)
```
@type constraints() :: Keyword.t()
```
### fields()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L18)
```
@type fields() :: Keyword.t()
```
### filters()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L19)
```
@type filters() :: Keyword.t()
```
### on\_conflict()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L25)
```
@type on_conflict() ::
{:raise, list(), []}
| {:nothing, list(), [atom()]}
| {[atom()], list(), [atom()]}
| {Ecto.Query.t(), list(), [atom()]}
```
### options()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L23)
```
@type options() :: Keyword.t()
```
### placeholders()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L22)
```
@type placeholders() :: [term()]
```
### returning()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L21)
```
@type returning() :: [atom()]
```
### schema\_meta()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L10)
```
@type schema_meta() :: %{
autogenerate_id:
{schema_field :: atom(), source_field :: atom(), Ecto.Type.t()},
context: term(),
prefix: binary() | nil,
schema: atom(),
source: binary()
}
```
Ecto.Schema metadata fields
Callbacks
==========
### autogenerate(field\_type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L37)
```
@callback autogenerate(field_type :: :id | :binary_id | :embed_id) :: term() | nil
```
Called to autogenerate a value for id/embed\_id/binary\_id.
Returns the autogenerated value, or nil if it must be autogenerated inside the storage or raise if not supported.
### delete(adapter\_meta, schema\_meta, filters, options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L90)
```
@callback delete(adapter_meta(), schema_meta(), filters(), options()) ::
{:ok, fields()} | {:invalid, constraints()} | {:error, :stale}
```
Deletes a single struct with the given filters.
While `filters` can be any record column, it is expected that at least the primary key (or any other key that uniquely identifies an existing record) be given as a filter. Therefore, in case there is no record matching the given filters, `{:error, :stale}` is returned.
### insert(adapter\_meta, schema\_meta, fields, on\_conflict, returning, options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L66)
```
@callback insert(
adapter_meta(),
schema_meta(),
fields(),
on_conflict(),
returning(),
options()
) ::
{:ok, fields()} | {:invalid, constraints()}
```
Inserts a single new struct in the data store.
#### Autogenerate
The primary key will be automatically included in `returning` if the field has type `:id` or `:binary_id` and no value was set by the developer or none was autogenerated by the adapter.
### insert\_all( adapter\_meta, schema\_meta, header, list, on\_conflict, returning, placeholders, options )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L55)
```
@callback insert_all(
adapter_meta(),
schema_meta(),
header :: [atom()],
[[{atom(), term() | {Ecto.Query.t(), list()}}]],
on_conflict(),
returning(),
placeholders(),
options()
) :: {non_neg_integer(), [[term()]] | nil}
```
Inserts multiple entries into the data store.
In case an [`Ecto.Query`](ecto.query) given as any of the field values by the user, it will be sent to the adapter as a tuple with in the shape of `{query, params}`.
### update(adapter\_meta, schema\_meta, fields, filters, returning, options)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter/schema.ex#L78)
```
@callback update(
adapter_meta(),
schema_meta(),
fields(),
filters(),
returning(),
options()
) ::
{:ok, fields()} | {:invalid, constraints()} | {:error, :stale}
```
Updates a single struct with the given filters.
While `filters` can be any record column, it is expected that at least the primary key (or any other key that uniquely identifies an existing record) be given as a filter. Therefore, in case there is no record matching the given filters, `{:error, :stale}` is returned.
phoenix Data mapping and validation Data mapping and validation
============================
We will take a look at the role schemas play when validating and casting data through changesets. As we will see, sometimes the best solution is not to completely avoid schemas, but break a large schema into smaller ones. Maybe one for reading data, another for writing. Maybe one for your database, another for your forms.
Schemas are mappers
--------------------
The [`Ecto.Schema`](ecto.schema) moduledoc says:
> An Ecto schema is used to map *any* data source into an Elixir struct.
>
>
We put emphasis on *any* because it is a common misconception to think Ecto schemas map only to your database tables.
For instance, when you write a web application using Phoenix and you use Ecto to receive external changes and apply such changes to your database, we have this mapping:
```
Database <-> Ecto schema <-> Forms / API
```
Although there is a single Ecto schema mapping to both your database and your API, in many situations it is better to break this mapping in two. Let's see some practical examples.
Imagine you are working with a client that wants the "Sign Up" form to contain the fields "First name", "Last name" along side "E-mail" and other information. You know there are a couple problems with this approach.
First of all, not everyone has a first and last name. Although your client is decided on presenting both fields, they are a UI concern, and you don't want the UI to dictate the shape of your data. Furthermore, you know it would be useful to break the "Sign Up" information across two tables, the "accounts" and "profiles" tables.
Given the requirements above, how would we implement the Sign Up feature in the backend?
One approach would be to have two schemas, Account and Profile, with virtual fields such as `first_name` and `last_name`, and [use associations along side nested forms](https://dashbit.co/blog/working-with-ecto-associations-and-embeds) to tie the schemas to your UI. One of such schemas would be:
```
defmodule Profile do
use Ecto.Schema
schema "profiles" do
field :name
field :first_name, :string, virtual: true
field :last_name, :string, virtual: true
...
end
end
```
It is not hard to see how we are polluting our Profile schema with UI requirements by adding fields such `first_name` and `last_name`. If the Profile schema is used for both reading and writing data, it may end-up in an awkward place where it is not useful for any, as it contains fields that map just to one or the other operation.
One alternative solution is to break the "Database <-> Ecto schema <-> Forms / API" mapping in two parts. The first will cast and validate the external data with its own structure which you then transform and write to the database. For such, let's define a schema named `Registration` that will take care of casting and validating the form data exclusively, mapping directly to the UI fields:
```
defmodule Registration do
use Ecto.Schema
embedded_schema do
field :first_name
field :last_name
field :email
end
end
```
We used `embedded_schema` because it is not our intent to persist it anywhere. With the schema in hand, we can use Ecto changesets and validations to process the data:
```
fields = [:first_name, :last_name, :email]
changeset =
%Registration{}
|> Ecto.Changeset.cast(params["sign_up"], fields)
|> validate_required(...)
|> validate_length(...)
```
Now that the registration changes are mapped and validated, we can check if the resulting changeset is valid and act accordingly:
```
if changeset.valid? do
# Get the modified registration struct from changeset
registration = Ecto.Changeset.apply_changes(changeset)
account = Registration.to_account(registration)
profile = Registration.to_profile(registration)
MyApp.Repo.transaction fn ->
MyApp.Repo.insert_all "accounts", [account]
MyApp.Repo.insert_all "profiles", [profile]
end
{:ok, registration}
else
# Annotate the action so the UI shows errors
changeset = %{changeset | action: :registration}
{:error, changeset}
end
```
The `to_account/1` and `to_profile/1` functions in `Registration` would receive the registration struct and split the attributes apart accordingly:
```
def to_account(registration) do
Map.take(registration, [:email])
end
def to_profile(%{first_name: first, last_name: last}) do
%{name: "#{first} #{last}"}
end
```
In the example above, by breaking apart the mapping between the database and Elixir and between Elixir and the UI, our code becomes clearer and our data structures simpler.
Note we have used `MyApp.Repo.insert_all/2` to add data to both "accounts" and "profiles" tables directly. We have chosen to bypass schemas altogether. However, there is nothing stopping you from also defining both `Account` and `Profile` schemas and changing `to_account/1` and `to_profile/1` to respectively return `%Account{}` and `%Profile{}` structs. Once structs are returned, they could be inserted through the usual `MyApp.Repo.insert/2` operation. Doing so can be especially useful if there are uniqueness or other constraints that you want to check during insertion.
Schemaless changesets
----------------------
Although we chose to define a `Registration` schema to use in the changeset, Ecto also allows developers to use changesets without schemas. We can dynamically define the data and their types. Let's rewrite the registration changeset above to bypass schemas:
```
data = %{}
types = %{name: :string, email: :string}
# The data+types tuple is equivalent to %Registration{}
changeset =
{data, types}
|> Ecto.Changeset.cast(params["sign_up"], Map.keys(types))
|> validate_required(...)
|> validate_length(...)
```
You can use this technique to validate API endpoints, search forms, and other sources of data. The choice of using schemas depends mostly if you want to use the same mapping in different places or if you desire the compile-time guarantees Elixir structs gives you. Otherwise, you can bypass schemas altogether, be it when using changesets or interacting with the repository.
However, the most important lesson in this guide is not when to use or not to use schemas, but rather understand when a big problem can be broken into smaller problems that can be solved independently leading to an overall cleaner solution. The choice of using schemas or not above didn't affect the solution as much as the choice of breaking the registration problem apart.
[← Previous Page Constraints and Upserts](constraints-and-upserts) [Next Page → Dynamic queries](dynamic-queries)
| programming_docs |
phoenix Multi tenancy with query prefixes Multi tenancy with query prefixes
==================================
With Ecto we can run queries in different prefixes using a single pool of database connections. For databases engines such as Postgres, Ecto's prefix [maps to Postgres' DDL schemas](https://www.postgresql.org/docs/current/static/ddl-schemas.html). For MySQL, each prefix is a different database on its own.
Query prefixes may be useful in different scenarios. For example, multi tenant apps running on PostgreSQL would define multiple prefixes, usually one per client, under a single database. The idea is that prefixes will provide data isolation between the different users of the application, guaranteeing either globally or at the data level that queries and commands act on a specific tenants.
Prefixes may also be useful on high-traffic applications where data is partitioned upfront. For example, a gaming platform may break game data into isolated partitions, each named after a different prefix. A partition for a given player is either chosen at random or calculated based on the player information.
Given each tenant has its own database structure, multi tenancy with query prefixes is expensive to setup. For example, migrations have to run individually for each prefix. Therefore this approach is useful when there is a limited or a slowly growing number of tenants.
Let's get started. Note all the examples below assume you are using PostgreSQL. Other databases engines may require slightly different solutions.
Connection prefixes
--------------------
As a starting point, let's start with a simple scenario: your application must connect to a particular prefix when running in production. This may be due to infrastructure conditions, database administration rules or others.
Let's define a repository and a schema to get started:
```
# lib/repo.ex
defmodule MyApp.Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
end
# lib/sample.ex
defmodule MyApp.Sample do
use Ecto.Schema
schema "samples" do
field :name
timestamps
end
end
```
Now let's configure the repository:
```
# config/config.exs
config :my_app, MyApp.Repo,
username: "postgres",
password: "postgres",
database: "demo",
hostname: "localhost",
pool_size: 10
```
And define a migration:
```
# priv/repo/migrations/20160101000000_create_sample.exs
defmodule MyApp.Repo.Migrations.CreateSample do
use Ecto.Migration
def change do
create table(:samples) do
add :name, :string
timestamps()
end
end
end
```
Now let's create the database, migrate it and then start an IEx session:
```
$ mix ecto.create
$ mix ecto.migrate
$ iex -S mix
Interactive Elixir - press Ctrl+C to exit
iex(1)> MyApp.Repo.all MyApp.Sample
[]
```
We haven't done anything unusual so far. We created our database instance, made it up to date by running migrations and then successfully made a query against the "samples" table, which returned an empty list.
By default, connections to Postgres' databases run on the "public" prefix. When we run migrations and queries, they are all running against the "public" prefix. However imagine your application has a requirement to run on a particular prefix in production, let's call it "connection\_prefix".
Luckily Postgres allows us to change the prefix our database connections run on by setting the "schema search path". The best moment to change the search path is right after we setup the database connection, ensuring all of our queries will run on that particular prefix, throughout the connection life-cycle.
To do so, let's change our database configuration in "config/config.exs" and specify an `:after_connect` option. `:after_connect` expects a tuple with module, function and arguments it will invoke with the connection process, as soon as a database connection is established:
```
query_args = ["SET search_path TO connection_prefix", []]
config :my_app, MyApp.Repo,
username: "postgres",
password: "postgres",
database: "demo_dev",
hostname: "localhost",
pool_size: 10,
after_connect: {Postgrex, :query!, query_args}
```
Now let's try to run the same query as before:
```
$ iex -S mix
Interactive Elixir - press Ctrl+C to exit
iex(1)> MyApp.Repo.all MyApp.Sample
** (Postgrex.Error) ERROR (undefined_table):
relation "samples" does not exist
```
Our previously successful query now fails because there is no table "samples" under the new prefix. Let's try to fix that by running migrations:
```
$ mix ecto.migrate
** (Postgrex.Error) ERROR (invalid_schema_name):
no schema has been selected to create in
```
Oops. Now migration says there is no such schema name. That's because Postgres automatically creates the "public" prefix every time we create a new database. If we want to use a different prefix, we must explicitly create it on the database we are running on:
```
$ psql -d demo_dev -c "CREATE SCHEMA connection_prefix"
```
Now we are ready to migrate and run our queries:
```
$ mix ecto.migrate
$ iex -S mix
Interactive Elixir - press Ctrl+C to exit
iex(1)> MyApp.Repo.all MyApp.Sample
[]
```
Data in different prefixes are isolated. Writing to the "samples" table in one prefix cannot be accessed by the other unless we change the prefix in the connection or use the Ecto conveniences we will discuss next.
Schema prefixes
----------------
Ecto also allows you to set a particular schema to run on a specific prefix. Imagine you are building a multi-tenant application. Each client data belongs to a particular prefix, such as "client\_foo", "client\_bar" and so forth. Yet your application may still rely on a set of tables that are shared across all clients. One of such tables may be exactly the table that maps the Client ID to its database prefix. Let's assume we want to store this data in a prefix named "main":
```
defmodule MyApp.Mapping do
use Ecto.Schema
@schema_prefix "main"
schema "mappings" do
field :client_id, :integer
field :db_prefix
timestamps
end
end
```
Now running `MyApp.Repo.all MyApp.Mapping` will by default run on the "main" prefix, regardless of the value configured for the connection on the `:after_connect` callback. However, we may want to override the schema prefix too and Ecto gives us the opportunity to do so, let's see how.
Per-query and per-struct prefixes
----------------------------------
Now, suppose that while still configured to connect to the "connection\_prefix" on `:after_connect`, we run the following queries:
```
iex(1)> alias MyApp.Sample
MyApp.Sample
iex(2)> MyApp.Repo.all(Sample)
[]
iex(3)> MyApp.Repo.insert(%Sample{name: "mary"})
{:ok, %MyApp.Sample{...}}
iex(4)> MyApp.Repo.all(Sample)
[%MyApp.Sample{...}]
```
The operations above ran on the "connection\_prefix". So what happens if we try to run the sample query on the "public" prefix? All Ecto repository operations support the `:prefix` option. So let's set it to public.
```
iex(7)> MyApp.Repo.all(Sample)
[%MyApp.Sample{...}]
iex(8)> MyApp.Repo.all(Sample, prefix: "public")
[]
```
Notice how we were able to change the prefix the query runs on. Back in the default "public" prefix, there is no data.
One interesting aspect of prefixes in Ecto is that the prefix information is carried along each struct returned by a query:
```
iex(9)> [sample] = MyApp.Repo.all(Sample)
[%MyApp.Sample{}]
iex(10)> Ecto.get_meta(sample, :prefix)
nil
```
The example above returned nil, which means no prefix was specified by Ecto, and therefore the database connection default will be used. In this case, "connection\_prefix" will be used because of the `:after_connect` callback we added at the beginning of this guide.
Since the prefix data is carried in the struct, we can use such to copy data from one prefix to the other. Let's copy the sample above from the "connection\_prefix" to the "public" one:
```
iex(11)> new_sample = Ecto.put_meta(sample, prefix: "public")
%MyApp.Sample{}
iex(12)> MyApp.Repo.insert(new_sample)
{:ok, %MyApp.Sample{}}
iex(13)> [sample] = MyApp.Repo.all(Sample, prefix: "public")
[%MyApp.Sample{}]
iex(14)> Ecto.get_meta(sample, :prefix)
"public"
```
Now we have data inserted in both prefixes. Note how we passed the `:prefix` option to `MyApp.Repo.all`. Almost all Repo operations accept `:prefix` as an option, with one important distinction:
* the `:prefix` option in query operations (`all/2`, `update_all/2`, and `delete_all/2`) is a fallback. It will only be used when a `@schema_prefix` or a query prefix was not previously specified
* the `:prefix` option in schema operations (`insert_all/3`, `insert/2`, `update/2`, etc) will override the `@schema_prefix` as well as any prefix in the struct/changeset
This difference in behaviour is by design: we want to allow flexibility when writing queries but we want to enforce struct/changeset operations to always work isolated within a given prefix. In fact, if call `MyApp.Repo.insert(post)` or `MyApp.Repo.update(post)`, and the post includes associations, the associated data will also be inserted/updated in the same prefix as `post`.
Per from/join prefixes
-----------------------
Finally, Ecto allows you to set the prefix individually for each `from` and `join` expression. Here's an example:
```
from p in Post, prefix: "foo",
join: c in Comment, prefix: "bar"
```
Those will take precedence over all other prefixes we have defined so far. For each join/from in the query, the prefix used will be determined by the following order:
1. If the prefix option is given exclusively to join/from
2. If the `@schema_prefix` is set in the related schema
3. If the `:prefix` field given to the repo operation (i.e. `Repo.all(query, prefix: prefix)`)
4. The connection prefix
Migration prefixes
-------------------
When the connection prefix is set, it also changes the prefix migrations run on. However it is also possible to set the prefix through the command line or per table in the migration itself.
For example, imagine you are a gaming company where the game is broken in 128 partitions, named "prefix\_1", "prefix\_2", "prefix\_3" up to "prefix\_128". Now, whenever you need to migrate data, you need to migrate data on all different 128 prefixes. There are two ways of achieve that.
The first mechanism is to invoke `mix ecto.migrate` multiple times, once per prefix, passing the `--prefix` option:
```
$ mix ecto.migrate --prefix "prefix_1"
$ mix ecto.migrate --prefix "prefix_2"
$ mix ecto.migrate --prefix "prefix_3"
...
$ mix ecto.migrate --prefix "prefix_128"
```
The other approach is by changing each desired migration to run across multiple prefixes. For example:
```
defmodule MyApp.Repo.Migrations.CreateSample do
use Ecto.Migration
def change do
for i <- 1..128 do
prefix = "prefix_#{i}"
create table(:samples, prefix: prefix) do
add :name, :string
timestamps()
end
# Execute the commands on the current prefix
# before moving on to the next prefix
flush()
end
end
end
```
Summing up
-----------
Ecto provides many conveniences for working with querying prefixes. Those conveniences allow developers to configure prefixes with different precedence, starting with the highest one. When executing queries with `all`, `update_all` or `delete_all`, the prefix is computed as follows:
1. from/join prefixes
2. schema prefixes
3. the `:prefix` option
4. connection prefixes
When working with schemas and changesets in `insert_all`, `insert`, `update`, and so forth, the precedence is:
1. the `:prefix` option
2. changeset prefixes
3. schema prefixes
4. connection prefixes
This way developers can tackle different scenarios from production requirements to multi-tenant applications.
[← Previous Page Dynamic queries](dynamic-queries) [Next Page → Multi tenancy with foreign keys](multi-tenancy-with-foreign-keys)
phoenix Polymorphic associations with many to many Polymorphic associations with many to many
===========================================
Besides `belongs_to`, `has_many`, `has_one` and `:through` associations, Ecto also includes `many_to_many`. `many_to_many` relationships, as the name says, allows a record from table X to have many associated entries from table Y and vice-versa. Although `many_to_many` associations can be written as `has_many :through`, using `many_to_many` may considerably simplify some workflows.
In this guide, we will talk about polymorphic associations and how `many_to_many` can remove boilerplate from certain approaches compared to `has_many :through`.
Todo lists v65131
------------------
The internet has seen its share of todo list applications. But that won't stop us from creating our own!
In our case, there is one aspect of todo list applications we are interested in, which is the relationship where the todo list has many todo items. This exact scenario is explored in detail in a post about [nested associations and embeds](https://dashbit.co/blog/working-with-ecto-associations-and-embeds) from Dashbit's blog. Let's recap the important points.
Our todo list app has two schemas, `Todo.List` and `Todo.Item`:
```
defmodule MyApp.TodoList do
use Ecto.Schema
schema "todo_lists" do
field :title
has_many :todo_items, MyApp.TodoItem
timestamps()
end
end
defmodule MyApp.TodoItem do
use Ecto.Schema
schema "todo_items" do
field :description
timestamps()
end
end
```
One of the ways to introduce a todo list with multiple items into the database is to couple our UI representation to our schemas. That's the approach we took in the blog post with Phoenix. Roughly:
```
<%= form_for @todo_list_changeset,
todo_list_path(@conn, :create),
fn f -> %>
<%= text_input f, :title %>
<%= inputs_for f, :todo_items, fn i -> %>
...
<% end %>
<% end %>
```
When such a form is submitted in Phoenix, it will send parameters with the following shape:
```
%{
"todo_list" => %{
"title" => "shopping list",
"todo_items" => %{
0 => %{"description" => "bread"},
1 => %{"description" => "eggs"}
}
}
}
```
We could then retrieve those parameters and pass it to an Ecto changeset and Ecto would automatically figure out what to do:
```
# In MyApp.TodoList
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title])
|> Ecto.Changeset.cast_assoc(:todo_items, required: true)
end
# And then in MyApp.TodoItem
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:description])
end
```
By calling [`Ecto.Changeset.cast_assoc/3`](ecto.changeset#cast_assoc/3), Ecto will look for a "todo\_items" key inside the parameters given on cast, and compare those parameters with the items stored in the todo list struct. Ecto will automatically generate instructions to insert, update or delete todo items such that:
* if a todo item sent as parameter has an ID and it matches an existing associated todo item, we consider that todo item should be updated
* if a todo item sent as parameter does not have an ID (nor a matching ID), we consider that todo item should be inserted
* if a todo item is currently associated but its ID was not sent as parameter, we consider the todo item is being replaced and we act according to the `:on_replace` callback. By default `:on_replace` will raise so you choose a behaviour between replacing, deleting, ignoring or nilifying the association
The advantage of using `cast_assoc/3` is that Ecto is able to do all of the hard work of keeping the entries associated, **as long as we pass the data exactly in the format that Ecto expects**. However, such approach is not always preferable and in many situations it is better to design our associations differently or decouple our UIs from our database representation.
Polymorphic todo items
-----------------------
To show an example of where using `cast_assoc/3` is just too complicated to be worth it, let's imagine you want your "todo items" to be polymorphic. For example, you want to be able to add todo items not only to "todo lists" but to many other parts of your application, such as projects, milestones, you name it.
First of all, it is important to remember Ecto does not provide the same type of polymorphic associations available in frameworks such as Rails and Laravel. In such frameworks, a polymorphic association uses two columns, the `parent_id` and `parent_type`. For example, one todo item would have `parent_id` of 1 with `parent_type` of "TodoList" while another would have `parent_id` of 1 with `parent_type` of "Project".
The issue with the design above is that it breaks database references. The database is no longer capable of guaranteeing the item you associate to exists or will continue to exist in the future. This leads to an inconsistent database which end-up pushing workarounds to your application.
The design above is also extremely inefficient, especially if you're working with large tables. Bear in mind that if that's your case, you might be forced to remove such polymorphic references in the future when frequent polymorphic queries start grinding the database to a halt even after adding indexes and optimizing the database.
Luckily, the documentation for the [`Ecto.Schema.belongs_to/3`](ecto.schema#belongs_to/3) macro includes a section named "Polymorphic associations" with some examples on how to design sane and performant associations. One of those approaches consists in using several join tables. Besides the "todo\_lists" and "projects" tables and the "todo\_items" table, we would create "todo\_list\_items" and "project\_items" to associate todo items to todo lists and todo items to projects respectively. In terms of migrations, we are looking at the following:
```
create table(:todo_lists) do
add :title
timestamps()
end
create table(:projects) do
add :name
timestamps()
end
create table(:todo_items) do
add :description
timestamps()
end
create table(:todo_list_items) do
add :todo_item_id, references(:todo_items)
add :todo_list_id, references(:todo_lists)
timestamps()
end
create table(:project_items) do
add :todo_item_id, references(:todo_items)
add :project_id, references(:projects)
timestamps()
end
```
By adding one table per association pair, we keep database references and can efficiently perform queries that relies on indexes.
First let's see how to implement this functionality in Ecto using a `has_many :through` and then use `many_to_many` to remove a lot of the boilerplate we were forced to introduce.
Polymorphism with has\_many :through
-------------------------------------
Given we want our todo items to be polymorphic, we can no longer associate a todo list to todo items directly. Instead we will create an intermediate schema to tie `MyApp.TodoList` and `MyApp.TodoItem` together.
```
defmodule MyApp.TodoList do
use Ecto.Schema
schema "todo_lists" do
field :title
has_many :todo_list_items, MyApp.TodoListItem
has_many :todo_items,
through: [:todo_list_items, :todo_item]
timestamps()
end
end
defmodule MyApp.TodoListItem do
use Ecto.Schema
schema "todo_list_items" do
belongs_to :todo_list, MyApp.TodoList
belongs_to :todo_item, MyApp.TodoItem
timestamps()
end
end
defmodule MyApp.TodoItem do
use Ecto.Schema
schema "todo_items" do
field :description
timestamps()
end
end
```
Although we introduced `MyApp.TodoListItem` as an intermediate schema, `has_many :through` allows us to access all todo items for any todo list transparently:
```
todo_lists |> Repo.preload(:todo_items)
```
The trouble is that `:through` associations are **read-only** since Ecto does not have enough information to fill in the intermediate schema. This means that, if we still want to use `cast_assoc` to insert a todo list with many todo items directly from the UI, we cannot use the `:through` association and instead must go step by step. We would need to first `cast_assoc(:todo_list_items)` from `TodoList` and then call `cast_assoc(:todo_item)` from the `TodoListItem` schema:
```
# In MyApp.TodoList
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title])
|> Ecto.Changeset.cast_assoc(
:todo_list_items,
required: true
)
end
# And then in the MyApp.TodoListItem
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast_assoc(:todo_item, required: true)
end
# And then in MyApp.TodoItem
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:description])
end
```
To further complicate things, remember `cast_assoc` expects a particular shape of data that reflects your associations. In this case, because of the intermediate schema, the data sent through your forms in Phoenix would have to look as follows:
```
%{"todo_list" => %{
"title" => "shipping list",
"todo_list_items" => %{
0 => %{"todo_item" => %{"description" => "bread"}},
1 => %{"todo_item" => %{"description" => "eggs"}},
}
}}
```
To make matters worse, you would have to duplicate this logic for every intermediate schema, and introduce `MyApp.TodoListItem` for todo lists, `MyApp.ProjectItem` for projects, etc.
Luckily, `many_to_many` allows us to remove all of this boilerplate.
Polymorphism with many\_to\_many
---------------------------------
In a way, the idea behind `many_to_many` associations is that it allows us to associate two schemas via an intermediate schema while automatically taking care of all details about the intermediate schema. Let's rewrite the schemas above to use `many_to_many`:
```
defmodule MyApp.TodoList do
use Ecto.Schema
schema "todo_lists" do
field :title
many_to_many :todo_items, MyApp.TodoItem,
join_through: MyApp.TodoListItem
timestamps()
end
end
defmodule MyApp.TodoListItem do
use Ecto.Schema
schema "todo_list_items" do
belongs_to :todo_list, MyApp.TodoList
belongs_to :todo_item, MyApp.TodoItem
timestamps()
end
end
defmodule MyApp.TodoItem do
use Ecto.Schema
schema "todo_items" do
field :description
timestamps()
end
end
```
Notice `MyApp.TodoList` no longer needs to define a `has_many` association pointing to the `MyApp.TodoListItem` schema and instead we can just associate to `:todo_items` using `many_to_many`.
Differently from `has_many :through`, `many_to_many` associations are also writable. This means we can send data through our forms exactly as we did at the beginning of this guide:
```
%{"todo_list" => %{
"title" => "shipping list",
"todo_items" => %{
0 => %{"description" => "bread"},
1 => %{"description" => "eggs"},
}
}}
```
And we no longer need to define a changeset function in the intermediate schema:
```
# In MyApp.TodoList
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title])
|> Ecto.Changeset.cast_assoc(:todo_items, required: true)
end
# And then in MyApp.TodoItem
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:description])
end
```
In other words, we can use exactly the same code we had in the "todo lists has\_many todo items" case. So even when external constraints require us to use a join table, `many_to_many` associations can automatically manage them for us. Everything you know about associations will just work with `many_to_many` associations as well.
Finally, even though we have specified a schema as the `:join_through` option in `many_to_many`, `many_to_many` can also work without intermediate schemas altogether by simply giving it a table name:
```
defmodule MyApp.TodoList do
use Ecto.Schema
schema "todo_lists" do
field :title
many_to_many :todo_items, MyApp.TodoItem,
join_through: "todo_list_items"
timestamps()
end
end
```
In this case, you can completely remove the `MyApp.TodoListItem` schema from your application and the code above will still work. The only difference is that when using tables, any autogenerated value that is filled by Ecto schema, such as timestamps, won't be filled as we no longer have a schema. To solve this, you can either drop those fields from your migrations or set a default at the database level.
Summary
--------
In this guide we used `many_to_many` associations to drastically improve a polymorphic association design that relied on `has_many :through`. Our goal was to allow "todo\_items" to associate to different entities in our code base, such as "todo\_lists" and "projects". We have done this by creating intermediate tables and by using `many_to_many` associations to automatically manage those join tables.
At the end, our schemas may look like:
```
defmodule MyApp.TodoList do
use Ecto.Schema
schema "todo_lists" do
field :title
many_to_many :todo_items, MyApp.TodoItem,
join_through: "todo_list_items"
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:title])
|> Ecto.Changeset.cast_assoc(
:todo_items,
required: true
)
end
end
defmodule MyApp.Project do
use Ecto.Schema
schema "projects" do
field :name
many_to_many :todo_items, MyApp.TodoItem,
join_through: "project_items"
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:name])
|> Ecto.Changeset.cast_assoc(
:todo_items,
required: true
)
end
end
defmodule MyApp.TodoItem do
use Ecto.Schema
schema "todo_items" do
field :description
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:description])
end
end
```
And the database migration:
```
create table("todo_lists") do
add :title
timestamps()
end
create table("projects") do
add :name
timestamps()
end
create table("todo_items") do
add :description
timestamps()
end
# Primary key and timestamps are not required if
# using many_to_many without schemas
create table("todo_list_items", primary_key: false) do
add :todo_item_id, references(:todo_items)
add :todo_list_id, references(:todo_lists)
# timestamps()
end
# Primary key and timestamps are not required if
# using many_to_many without schemas
create table("project_items", primary_key: false) do
add :todo_item_id, references(:todo_items)
add :project_id, references(:projects)
# timestamps()
end
```
Overall our code looks structurally the same as `has_many` would, although at the database level our relationships are expressed with join tables.
While in this guide we changed our code to cope with the parameter format required by `cast_assoc`, in [Constraints and Upserts](constraints-and-upserts) we drop `cast_assoc` altogether and use `put_assoc` which brings more flexibilities when working with associations.
[← Previous Page Self-referencing many to many](self-referencing-many-to-many) [Next Page → Replicas and dynamic repositories](replicas-and-dynamic-repositories)
| programming_docs |
phoenix Ecto.Query.CompileError exception Ecto.Query.CompileError exception
==================================
Raised at compilation time when the query cannot be compiled.
phoenix Ecto.Embedded Ecto.Embedded
==============
The embedding struct for `embeds_one` and `embeds_many`.
Its fields are:
* `cardinality` - The association cardinality
* `field` - The name of the association field on the schema
* `owner` - The schema where the association was defined
* `related` - The schema that is embedded
* `on_cast` - Function name to call by default when casting embeds
* `on_replace` - The action taken on associations when schema is replaced
phoenix Ecto.Enum Ecto.Enum
==========
A custom type that maps atoms to strings or integers.
[`Ecto.Enum`](ecto.enum#content) must be used whenever you want to keep atom values in a field. Since atoms cannot be persisted to the database, [`Ecto.Enum`](ecto.enum#content) converts them to a string or an integer when writing to the database and converts them back to atoms when loading data. It can be used in your schemas as follows:
```
# Stored as strings
field :status, Ecto.Enum, values: [:foo, :bar, :baz]
```
or
```
# Stored as integers
field :status, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5]
```
Therefore, the type to be used in your migrations for enum fields depend on the choice above. For the cases above, one would do, respectively:
```
add :status, :string
```
or
```
add :status, :integer
```
Some databases also support enum types, which you could use in combination with the above.
Composite types, such as `:array`, are also supported which allow selecting multiple values per record:
```
field :roles, {:array, Ecto.Enum}, values: [:author, :editor, :admin]
```
Overall, `:values` must be a list of atoms or a keyword list. Values will be cast to atoms safely and only if the atom exists in the list (otherwise an error will be raised). Attempting to load any string/integer not represented by an atom in the list will be invalid.
The helper function [`mappings/2`](#mappings/2) returns the mappings for a given schema and field, which can be used in places like form drop-downs. For example, given the following schema:
```
defmodule EnumSchema do
use Ecto.Schema
schema "my_schema" do
field :my_enum, Ecto.Enum, values: [:foo, :bar, :baz]
end
end
```
you can call [`mappings/2`](#mappings/2) like this:
```
Ecto.Enum.mappings(EnumSchema, :my_enum)
#=> [foo: "foo", bar: "bar", baz: "baz"]
```
If you want the values only, you can use [`Ecto.Enum.values/2`](#values/2), and if you want the dump values only, you can use [`Ecto.Enum.dump_values/2`](#dump_values/2).
Summary
========
Functions
----------
[dump\_values(schema, field)](#dump_values/2) Returns the possible dump values for a given schema and field
[mappings(schema, field)](#mappings/2) Returns the mappings for a given schema and field
[values(schema, field)](#values/2) Returns the possible values for a given schema and field
Functions
==========
### dump\_values(schema, field)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/enum.ex#L177)
```
@spec dump_values(module(), atom()) :: [String.t()] | [integer()]
```
Returns the possible dump values for a given schema and field
### mappings(schema, field)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/enum.ex#L185)
```
@spec mappings(module(), atom()) :: Keyword.t()
```
Returns the mappings for a given schema and field
### values(schema, field)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/enum.ex#L169)
```
@spec values(module(), atom()) :: [atom()]
```
Returns the possible values for a given schema and field
phoenix Ecto.Queryable protocol Ecto.Queryable protocol
========================
Converts a data structure into an [`Ecto.Query`](ecto.query).
Summary
========
Types
------
[t()](#t:t/0) Functions
----------
[to\_query(data)](#to_query/1) Converts the given `data` into an [`Ecto.Query`](ecto.query).
Types
======
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/queryable.ex#L1)
```
@type t() :: term()
```
Functions
==========
### to\_query(data)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/queryable.ex#L9)
Converts the given `data` into an [`Ecto.Query`](ecto.query).
phoenix Ecto.Repo behaviour Ecto.Repo behaviour
====================
Defines a repository.
A repository maps to an underlying data store, controlled by the adapter. For example, Ecto ships with a Postgres adapter that stores data into a PostgreSQL database.
When used, the repository expects the `:otp_app` and `:adapter` as option. The `:otp_app` should point to an OTP application that has the repository configuration. For example, the repository:
```
defmodule Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
end
```
Could be configured with:
```
config :my_app, Repo,
database: "ecto_simple",
username: "postgres",
password: "postgres",
hostname: "localhost"
```
Most of the configuration that goes into the `config` is specific to the adapter. For this particular example, you can check [`Ecto.Adapters.Postgres`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.Postgres.html) for more information. In spite of this, the following configuration values are shared across all adapters:
* `:name`- The name of the Repo supervisor process
* `:priv` - the directory where to keep repository data, like migrations, schema and more. Defaults to "priv/YOUR\_REPO". It must always point to a subdirectory inside the priv directory
* `:url` - an URL that specifies storage information. Read below for more information
* `:log` - the log level used when logging the query with Elixir's Logger. If false, disables logging for that repository. Defaults to `:debug`
* `:pool_size` - the size of the pool used by the connection module. Defaults to `10`
* `:telemetry_prefix` - we recommend adapters to publish events using the `Telemetry` library. By default, the telemetry prefix is based on the module name, so if your module is called `MyApp.Repo`, the prefix will be `[:my_app, :repo]`. See the "Telemetry Events" section to see which events we recommend adapters to publish. Note that if you have multiple databases, you should keep the `:telemetry_prefix` consistent for each repo and use the `:repo` property in the event metadata for distinguishing between repos.
* `:stacktrace`- when true, publishes the stacktrace in telemetry events and allows more advanced logging.
URLs
-----
Repositories by default support URLs. For example, the configuration above could be rewritten to:
```
config :my_app, Repo,
url: "ecto://postgres:postgres@localhost/ecto_simple"
```
The schema can be of any value. The path represents the database name while options are simply merged in.
URL can include query parameters to override shared and adapter-specific options, like `ssl`, `timeout` and `pool_size`. The following example shows how to pass these configuration values:
```
config :my_app, Repo,
url: "ecto://postgres:postgres@localhost/ecto_simple?ssl=true&pool_size=10"
```
In case the URL needs to be dynamically configured, for example by reading a system environment variable, such can be done via the [`init/2`](#c:init/2) repository callback:
```
def init(_type, config) do
{:ok, Keyword.put(config, :url, System.get_env("DATABASE_URL"))}
end
```
Shared options
---------------
Almost all of the repository functions outlined in this module accept the following options:
* `:timeout` - The time in milliseconds (as an integer) to wait for the query call to finish. `:infinity` will wait indefinitely (default: `15_000`)
* `:log` - When false, does not log the query
* `:telemetry_event` - The telemetry event name to dispatch the event under. See the next section for more information
* `:telemetry_options` - Extra options to attach to telemetry event name. See the next section for more information
Telemetry events
-----------------
There are two types of telemetry events. The ones emitted by Ecto and the ones that are adapter specific.
### Ecto telemetry events
The following events are emitted by all Ecto repositories:
* `[:ecto, :repo, :init]` - it is invoked whenever a repository starts. The measurement is a single `system_time` entry in native unit. The metadata is the `:repo` and all initialization options under `:opts`.
### Adapter-specific events
We recommend adapters to publish certain `Telemetry` events listed below. Those events will use the `:telemetry_prefix` outlined above which defaults to `[:my_app, :repo]`.
For instance, to receive all query events published by a repository called `MyApp.Repo`, one would define a module:
```
defmodule MyApp.Telemetry do
def handle_event([:my_app, :repo, :query], measurements, metadata, config) do
IO.inspect binding()
end
end
```
Then, in the [`Application.start/2`](https://hexdocs.pm/elixir/Application.html#start/2) callback, attach the handler to this event using a unique handler id:
```
:ok = :telemetry.attach("my-app-handler-id", [:my_app, :repo, :query], &MyApp.Telemetry.handle_event/4, %{})
```
For details, see [the telemetry documentation](https://hexdocs.pm/telemetry/).
Below we list all events developers should expect from Ecto. All examples below consider a repository named `MyApp.Repo`:
#### `[:my_app, :repo, :query]`
This event should be invoked on every query sent to the adapter, including queries that are related to the transaction management.
The `:measurements` map will include the following, all given in the `:native` time unit:
* `:idle_time` - the time the connection spent waiting before being checked out for the query
* `:queue_time` - the time spent waiting to check out a database connection
* `:query_time` - the time spent executing the query
* `:decode_time` - the time spent decoding the data received from the database
* `:total_time` - the sum of (`queue_time`, `query_time`, and `decode_time`)️
All measurements are given in the `:native` time unit. You can read more about it in the docs for [`System.convert_time_unit/3`](https://hexdocs.pm/elixir/System.html#convert_time_unit/3).
A telemetry `:metadata` map including the following fields. Each database adapter may emit different information here. For Ecto.SQL databases, it will look like this:
* `:type` - the type of the Ecto query. For example, for Ecto.SQL databases, it would be `:ecto_sql_query`
* `:repo` - the Ecto repository
* `:result` - the query result
* `:params` - the query parameters
* `:query` - the query sent to the database as a string
* `:source` - the source the query was made on (may be nil)
* `:options` - extra options given to the repo operation under `:telemetry_options`
Read-only repositories
-----------------------
You can mark a repository as read-only by passing the `:read_only` flag on `use`:
```
use Ecto.Repo, otp_app: ..., adapter: ..., read_only: true
```
By passing the `:read_only` option, none of the functions that perform write operations, such as [`insert/2`](#c:insert/2), [`insert_all/3`](#c:insert_all/3), [`update_all/3`](#c:update_all/3), and friends will be defined.
Summary
========
Types
------
[t()](#t:t/0) Query API
----------
[aggregate( queryable, aggregate, opts )](#c:aggregate/3) Calculate the given `aggregate`.
[aggregate( queryable, aggregate, field, opts )](#c:aggregate/4) Calculate the given `aggregate` over the given `field`.
[all(queryable, opts)](#c:all/2) Fetches all entries from the data store matching the given query.
[delete\_all(queryable, opts)](#c:delete_all/2) Deletes all entries matching the given query.
[exists?(queryable, opts)](#c:exists?/2) Checks if there exists an entry that matches the given query.
[get!(queryable, id, opts)](#c:get!/3) Similar to [`get/3`](#c:get/3) but raises [`Ecto.NoResultsError`](ecto.noresultserror) if no record was found.
[get(queryable, id, opts)](#c:get/3) Fetches a single struct from the data store where the primary key matches the given id.
[get\_by!( queryable, clauses, opts )](#c:get_by!/3) Similar to [`get_by/3`](#c:get_by/3) but raises [`Ecto.NoResultsError`](ecto.noresultserror) if no record was found.
[get\_by( queryable, clauses, opts )](#c:get_by/3) Fetches a single result from the query.
[one!(queryable, opts)](#c:one!/2) Similar to [`one/2`](#c:one/2) but raises [`Ecto.NoResultsError`](ecto.noresultserror) if no record was found.
[one(queryable, opts)](#c:one/2) Fetches a single result from the query.
[stream(queryable, opts)](#c:stream/2) Returns a lazy enumerable that emits all entries from the data store matching the given query.
[update\_all( queryable, updates, opts )](#c:update_all/3) Updates all entries matching the given query with the given values.
Schema API
-----------
[delete!( struct\_or\_changeset, opts )](#c:delete!/2) Same as [`delete/2`](#c:delete/2) but returns the struct or raises if the changeset is invalid.
[delete( struct\_or\_changeset, opts )](#c:delete/2) Deletes a struct using its primary key.
[insert!( struct\_or\_changeset, opts )](#c:insert!/2) Same as [`insert/2`](#c:insert/2) but returns the struct or raises if the changeset is invalid.
[insert( struct\_or\_changeset, opts )](#c:insert/2) Inserts a struct defined via [`Ecto.Schema`](ecto.schema) or a changeset.
[insert\_all( schema\_or\_source, entries\_or\_query, opts )](#c:insert_all/3) Inserts all entries into the repository.
[insert\_or\_update!(changeset, opts)](#c:insert_or_update!/2) Same as [`insert_or_update/2`](#c:insert_or_update/2) but returns the struct or raises if the changeset is invalid.
[insert\_or\_update(changeset, opts)](#c:insert_or_update/2) Inserts or updates a changeset depending on whether the struct is persisted or not.
[load( schema\_or\_map, data )](#c:load/2) Loads `data` into a schema or a map.
[preload(structs\_or\_struct\_or\_nil, preloads, opts)](#c:preload/3) Preloads all associations on the given struct or structs.
[reload!(struct\_or\_structs, opts)](#c:reload!/2) Similar to [`reload/2`](#c:reload/2), but raises when something is not found.
[reload( struct\_or\_structs, opts )](#c:reload/2) Reloads a given schema or schema list from the database.
[update!(changeset, opts)](#c:update!/2) Same as [`update/2`](#c:update/2) but returns the struct or raises if the changeset is invalid.
[update(changeset, opts)](#c:update/2) Updates a changeset using its primary key.
Transaction API
----------------
[checked\_out?()](#c:checked_out?/0) Returns true if a connection has been checked out.
[checkout(function, opts)](#c:checkout/2) Checks out a connection for the duration of the function.
[in\_transaction?()](#c:in_transaction?/0) Returns true if the current process is inside a transaction.
[rollback(value)](#c:rollback/1) Rolls back the current transaction.
[transaction(fun\_or\_multi, opts)](#c:transaction/2) Runs the given function or [`Ecto.Multi`](ecto.multi) inside a transaction.
Runtime API
------------
[\_\_adapter\_\_()](#c:__adapter__/0) Returns the adapter tied to the repository.
[config()](#c:config/0) Returns the adapter configuration stored in the `:otp_app` environment.
[get\_dynamic\_repo()](#c:get_dynamic_repo/0) Returns the atom name or pid of the current repository.
[put\_dynamic\_repo(name\_or\_pid)](#c:put_dynamic_repo/1) Sets the dynamic repository to be used in further interactions.
[start\_link(opts)](#c:start_link/1) Starts any connection pooling or supervision and return `{:ok, pid}` or just `:ok` if nothing needs to be done.
[stop(timeout)](#c:stop/1) Shuts down the repository.
User callbacks
---------------
[default\_options(operation)](#c:default_options/1) A user customizable callback invoked to retrieve default options for operations.
[init(context, config)](#c:init/2) A callback executed when the repo starts or when configuration is read.
[prepare\_query(operation, query, opts)](#c:prepare_query/3) A user customizable callback invoked for query-based operations.
Functions
----------
[all\_running()](#all_running/0) Returns all running Ecto repositories.
Types
======
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L182)
```
@type t() :: module()
```
Query API
==========
### aggregate( queryable, aggregate, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L833)
```
@callback aggregate(
queryable :: Ecto.Queryable.t(),
aggregate :: :count,
opts :: Keyword.t()
) :: term() | nil
```
Calculate the given `aggregate`.
If the query has a limit, offset, distinct or combination set, it will be automatically wrapped in a subquery in order to return the proper result.
Any preload or select in the query will be ignored in favor of the column being aggregated.
The aggregation will fail if any `group_by` field is set.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Examples
```
# Returns the number of blog posts
Repo.aggregate(Post, :count)
# Returns the number of blog posts in the "private" schema path
# (in Postgres) or database (in MySQL)
Repo.aggregate(Post, :count, prefix: "private")
```
### aggregate( queryable, aggregate, field, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L859)
```
@callback aggregate(
queryable :: Ecto.Queryable.t(),
aggregate :: :avg | :count | :max | :min | :sum,
field :: atom(),
opts :: Keyword.t()
) :: term() | nil
```
Calculate the given `aggregate` over the given `field`.
See [`aggregate/3`](#c:aggregate/3) for general considerations and options.
#### Examples
```
# Returns the number of visits per blog post
Repo.aggregate(Post, :count, :visits)
# Returns the number of visits per blog post in the "private" schema path
# (in Postgres) or database (in MySQL)
Repo.aggregate(Post, :count, :visits, prefix: "private")
# Returns the average number of visits for the top 10
query = from Post, limit: 10
Repo.aggregate(query, :avg, :visits)
```
### all(queryable, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1080)
```
@callback all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: [Ecto.Schema.t()]
```
Fetches all entries from the data store matching the given query.
May raise [`Ecto.QueryError`](ecto.queryerror) if query validation fails.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
# Fetch all post titles
query = from p in Post,
select: p.title
MyRepo.all(query)
```
### delete\_all(queryable, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1192)
```
@callback delete_all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) ::
{non_neg_integer(), nil | [term()]}
```
Deletes all entries matching the given query.
It returns a tuple containing the number of entries and any returned result as second element. The second element is `nil` by default unless a `select` is supplied in the delete query. Note, however, not all databases support returning data from DELETEs.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query and any `@schema_prefix` set in the schema.
See the ["Shared options"](#module-shared-options) section at the module documentation for remaining options.
#### Examples
```
MyRepo.delete_all(Post)
from(p in Post, where: p.id < 10) |> MyRepo.delete_all
```
### exists?(queryable, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L892)
```
@callback exists?(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: boolean()
```
Checks if there exists an entry that matches the given query.
Returns a boolean.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Examples
```
# checks if any posts exist
Repo.exists?(Post)
# checks if any posts exist in the "private" schema path (in Postgres) or
# database (in MySQL)
Repo.exists?(Post, schema: "private")
# checks if any post with a like count greater than 10 exists
query = from p in Post, where: p.like_count > 10
Repo.exists?(query)
```
### get!(queryable, id, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L688)
```
@callback get!(queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t()) ::
Ecto.Schema.t()
```
Similar to [`get/3`](#c:get/3) but raises [`Ecto.NoResultsError`](ecto.noresultserror) if no record was found.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
MyRepo.get!(Post, 42)
MyRepo.get!(Post, 42, prefix: "public")
```
### get(queryable, id, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L662)
```
@callback get(queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t()) ::
Ecto.Schema.t() | nil
```
Fetches a single struct from the data store where the primary key matches the given id.
Returns `nil` if no result was found. If the struct in the queryable has no or more than one primary key, it will raise an argument error.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
MyRepo.get(Post, 42)
MyRepo.get(Post, 42, prefix: "public")
```
### get\_by!( queryable, clauses, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L751)
```
@callback get_by!(
queryable :: Ecto.Queryable.t(),
clauses :: Keyword.t() | map(),
opts :: Keyword.t()
) :: Ecto.Schema.t()
```
Similar to [`get_by/3`](#c:get_by/3) but raises [`Ecto.NoResultsError`](ecto.noresultserror) if no record was found.
Raises if more than one entry.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
MyRepo.get_by!(Post, title: "My post")
MyRepo.get_by!(Post, [title: "My post"], prefix: "public")
```
### get\_by( queryable, clauses, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L720)
```
@callback get_by(
queryable :: Ecto.Queryable.t(),
clauses :: Keyword.t() | map(),
opts :: Keyword.t()
) :: Ecto.Schema.t() | nil
```
Fetches a single result from the query.
Returns `nil` if no result was found. Raises if more than one entry.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
MyRepo.get_by(Post, title: "My post")
MyRepo.get_by(Post, [title: "My post"], prefix: "public")
```
### one!(queryable, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L940)
```
@callback one!(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: Ecto.Schema.t()
```
Similar to [`one/2`](#c:one/2) but raises [`Ecto.NoResultsError`](ecto.noresultserror) if no record was found.
Raises if more than one entry.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
### one(queryable, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L919)
```
@callback one(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) ::
Ecto.Schema.t() | nil
```
Fetches a single result from the query.
Returns `nil` if no result was found. Raises if more than one entry.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Examples
```
Repo.one(from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id)
query = from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id
Repo.one(query, prefix: "private")
```
### stream(queryable, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1117)
```
@callback stream(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: Enum.t()
```
Returns a lazy enumerable that emits all entries from the data store matching the given query.
SQL adapters, such as Postgres and MySQL, can only enumerate a stream inside a transaction.
May raise [`Ecto.QueryError`](ecto.queryerror) if query validation fails.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the "Query Prefix" section of the [`Ecto.Query`](ecto.query) documentation.
* `:max_rows` - The number of rows to load from the database as we stream. It is supported at least by Postgres and MySQL and defaults to 500.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
# Fetch all post titles
query = from p in Post,
select: p.title
stream = MyRepo.stream(query)
MyRepo.transaction(fn ->
Enum.to_list(stream)
end)
```
### update\_all( queryable, updates, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1166)
```
@callback update_all(
queryable :: Ecto.Queryable.t(),
updates :: Keyword.t(),
opts :: Keyword.t()
) :: {non_neg_integer(), nil | [term()]}
```
Updates all entries matching the given query with the given values.
It returns a tuple containing the number of entries and any returned result as second element. The second element is `nil` by default unless a `select` is supplied in the update query. Note, however, not all databases support returning data from UPDATEs.
Keep in mind this `update_all` will not update autogenerated fields like the `updated_at` columns.
See [`Ecto.Query.update/3`](ecto.query#update/3) for update operations that can be performed on fields.
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query and any `@schema_prefix` set in the schema.
See the ["Shared options"](#module-shared-options) section at the module documentation for remaining options.
#### Examples
```
MyRepo.update_all(Post, set: [title: "New title"])
MyRepo.update_all(Post, inc: [visits: 1])
from(p in Post, where: p.id < 10, select: p.visits)
|> MyRepo.update_all(set: [title: "New title"])
from(p in Post, where: p.id < 10, update: [set: [title: "New title"]])
|> MyRepo.update_all([])
from(p in Post, where: p.id < 10, update: [set: [title: ^new_title]])
|> MyRepo.update_all([])
from(p in Post, where: p.id < 10, update: [set: [title: fragment("upper(?)", ^new_title)]])
|> MyRepo.update_all([])
```
Schema API
===========
### delete!( struct\_or\_changeset, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1734)
```
@callback delete!(
struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
opts :: Keyword.t()
) :: Ecto.Schema.t()
```
Same as [`delete/2`](#c:delete/2) but returns the struct or raises if the changeset is invalid.
### delete( struct\_or\_changeset, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1701)
```
@callback delete(
struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
opts :: Keyword.t()
) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
```
Deletes a struct using its primary key.
If the struct has no primary key, [`Ecto.NoPrimaryKeyFieldError`](ecto.noprimarykeyfielderror) will be raised. If the struct has been removed prior to the call, [`Ecto.StaleEntryError`](ecto.staleentryerror) will be raised. If more than one database operation is required, they're automatically wrapped in a transaction.
It returns `{:ok, struct}` if the struct has been successfully deleted or `{:error, changeset}` if there was a validation or a known constraint error. By default, constraint errors will raise the [`Ecto.ConstraintError`](ecto.constrainterror) exception, unless a changeset is given as the first argument with the relevant constraints declared in it (see [`Ecto.Changeset`](ecto.changeset)).
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query and any `@schema_prefix` set in the schema.
* `:stale_error_field` - The field where stale errors will be added in the returning changeset. This option can be used to avoid raising [`Ecto.StaleEntryError`](ecto.staleentryerror).
* `:stale_error_message` - The message to add to the configured `:stale_error_field` when stale errors happen, defaults to "is stale".
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
post = MyRepo.get!(Post, 42)
case MyRepo.delete post do
{:ok, struct} -> # Deleted with success
{:error, changeset} -> # Something went wrong
end
```
### insert!( struct\_or\_changeset, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1710)
```
@callback insert!(
struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
opts :: Keyword.t()
) :: Ecto.Schema.t()
```
Same as [`insert/2`](#c:insert/2) but returns the struct or raises if the changeset is invalid.
### insert( struct\_or\_changeset, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1544)
```
@callback insert(
struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
opts :: Keyword.t()
) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
```
Inserts a struct defined via [`Ecto.Schema`](ecto.schema) or a changeset.
In case a struct is given, the struct is converted into a changeset with all non-nil fields as part of the changeset.
In case a changeset is given, the changes in the changeset are merged with the struct fields, and all of them are sent to the database. If more than one database operation is required, they're automatically wrapped in a transaction.
It returns `{:ok, struct}` if the struct has been successfully inserted or `{:error, changeset}` if there was a validation or a known constraint error.
#### Options
* `:returning` - selects which fields to return. It accepts a list of fields to be returned from the database. When `true`, returns all fields. When `false`, no extra fields are returned. It will always include all fields in `read_after_writes` as well as any autogenerated id. Not all databases support this option and it may not be available during upserts. See the "Upserts" section for more information.
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query and any `@schema_prefix` set any schemas. Also, the `@schema_prefix` for the parent record will override all default `@schema_prefix`s set in any child schemas for associations.
* `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`, a keyword list of update instructions or an [`Ecto.Query`](ecto.query) query for updates. See the "Upserts" section for more information.
* `:conflict_target` - A list of column names to verify for conflicts. It is expected those columns to have unique indexes on them that may conflict. If none is specified, the conflict target is left up to the database. It may also be `{:unsafe_fragment, binary_fragment}` to pass any expression to the database without any sanitization, this is useful for partial index or index with expressions, such as `{:unsafe_fragment, "(coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL"}` for `ON CONFLICT (coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL` SQL query.
* `:stale_error_field` - The field where stale errors will be added in the returning changeset. This option can be used to avoid raising [`Ecto.StaleEntryError`](ecto.staleentryerror).
* `:stale_error_message` - The message to add to the configured `:stale_error_field` when stale errors happen, defaults to "is stale".
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Examples
A typical example is calling `MyRepo.insert/1` with a struct and acting on the return value:
```
case MyRepo.insert %Post{title: "Ecto is great"} do
{:ok, struct} -> # Inserted with success
{:error, changeset} -> # Something went wrong
end
```
#### Upserts
[`insert/2`](#c:insert/2) provides upserts (update or inserts) via the `:on_conflict` option. The `:on_conflict` option supports the following values:
* `:raise` - raises if there is a conflicting primary key or unique index
* `:nothing` - ignores the error in case of conflicts
* `:replace_all` - replace **all** values on the existing row with the values in the schema/changeset, including fields not explicitly set in the changeset, such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`). Do not use this option if you have auto-incrementing primary keys, as they will also be replaced. You most likely want to use `{:replace_all_except, [:id]}` or `{:replace, fields}` explicitly instead. This option requires a schema
* `{:replace_all_except, fields}` - same as above except the given fields are not replaced. This option requires a schema
* `{:replace, fields}` - replace only specific columns. This option requires `:conflict_target`
* a keyword list of update instructions - such as the one given to [`update_all/3`](#c:update_all/3), for example: `[set: [title: "new title"]]`
* an [`Ecto.Query`](ecto.query) that will act as an `UPDATE` statement, such as the one given to [`update_all/3`](#c:update_all/3). Similarly to [`update_all/3`](#c:update_all/3), auto generated values, such as timestamps are not automatically updated. If the struct cannot be found, [`Ecto.StaleEntryError`](ecto.staleentryerror) will be raised.
Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" on databases such as MySQL.
As an example, imagine `:title` is marked as a unique column in the database:
```
{:ok, inserted} = MyRepo.insert(%Post{title: "this is unique"})
```
Now we can insert with the same title but do nothing on conflicts:
```
{:ok, ignored} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: :nothing)
```
Because we used `on_conflict: :nothing`, instead of getting an error, we got `{:ok, struct}`. However the returned struct does not reflect the data in the database. If the primary key is auto-generated by the database, the primary key in the `ignored` record will be nil if there was no insertion. For example, if you use the default primary key (which has name `:id` and a type of `:id`), then `ignored.id` above will be nil if there was no insertion.
If your id is generated by your application (typically the case for `:binary_id`) or if you pass another value for `:on_conflict`, detecting if an insert or update happened is slightly more complex, as the database does not actually inform us what happened. Let's insert a post with the same title but use a query to update the body column in case of conflicts:
```
# In Postgres (it requires the conflict target for updates):
on_conflict = [set: [body: "updated"]]
{:ok, updated} = MyRepo.insert(%Post{title: "this is unique"},
on_conflict: on_conflict, conflict_target: :title)
# In MySQL (conflict target is not supported):
on_conflict = [set: [title: "updated"]]
{:ok, updated} = MyRepo.insert(%Post{id: inserted.id, title: "updated"},
on_conflict: on_conflict)
```
In the examples above, even though it returned `:ok`, we do not know if we inserted new data or if we updated only the `:on_conflict` fields. In case an update happened, the data in the struct most likely does not match the data in the database. For example, autogenerated fields such as `inserted_at` will point to now rather than the time the struct was actually inserted.
If you need to guarantee the data in the returned struct mirrors the database, you have three options:
* Use `on_conflict: :replace_all`, although that will replace all fields in the database with the ones in the struct/changeset, including autogenerated fields such as `inserted_at` and `updated_at`:
```
MyRepo.insert(%Post{title: "this is unique"},
on_conflict: :replace_all, conflict_target: :title)
```
* Specify `read_after_writes: true` in your schema for choosing fields that are read from the database after every operation. Or pass `returning: true` to `insert` to read all fields back:
```
MyRepo.insert(%Post{title: "this is unique"}, returning: true,
on_conflict: on_conflict, conflict_target: :title)
```
* Alternatively, read the data again from the database in a separate query. This option requires the primary key to be generated by the database:
```
{:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: on_conflict)
Repo.get(Post, updated.id)
```
Because of the inability to know if the struct is up to date or not, inserting a struct with associations and using the `:on_conflict` option at the same time is not recommended, as Ecto will be unable to actually track the proper status of the association.
### insert\_all( schema\_or\_source, entries\_or\_query, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1371)
```
@callback insert_all(
schema_or_source :: binary() | {binary(), module()} | module(),
entries_or_query ::
[%{required(atom()) => value} | Keyword.t(value)] | Ecto.Query.t(),
opts :: Keyword.t()
) :: {non_neg_integer(), nil | [term()]}
when value: term() | Ecto.Query.t()
```
Inserts all entries into the repository.
It expects a schema module (`MyApp.User`) or a source (`"users"`) or both (`{"users", MyApp.User}`) as the first argument. The second argument is a list of entries to be inserted, either as keyword lists or as maps. The keys of the entries are the field names as atoms and the value should be the respective value for the field type or, optionally, an [`Ecto.Query`](ecto.query) that returns a single entry with a single value.
It returns a tuple containing the number of entries and any returned result as second element. If the database does not support RETURNING in INSERT statements or no return result was selected, the second element will be `nil`.
When a schema module is given, the entries given will be properly dumped before being sent to the database. If the schema primary key has type `:id` or `:binary_id`, it will be handled either at the adapter or the storage layer. However any other primary key type or autogenerated value, like [`Ecto.UUID`](ecto.uuid) and timestamps, won't be autogenerated when using [`insert_all/3`](#c:insert_all/3). You must set those fields explicitly. This is by design as this function aims to be a more direct way to insert data into the database without the conveniences of [`insert/2`](#c:insert/2). This is also consistent with [`update_all/3`](#c:update_all/3) that does not handle auto generated values as well.
It is also not possible to use `insert_all` to insert across multiple tables, therefore associations are not supported.
If a source is given, without a schema module, the given fields are passed as is to the adapter.
#### Options
* `:returning` - selects which fields to return. When `true`, returns all fields in the given schema. May be a list of fields, where a struct is still returned but only with the given fields. Or `false`, where nothing is returned (the default). This option is not supported by all databases.
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query and any `@schema_prefix` set in the schema.
* `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`, a keyword list of update instructions or an [`Ecto.Query`](ecto.query) query for updates. See the "Upserts" section for more information.
* `:conflict_target` - A list of column names to verify for conflicts. It is expected those columns to have unique indexes on them that may conflict. If none is specified, the conflict target is left up to the database. It may also be `{:unsafe_fragment, binary_fragment}` to pass any expression to the database without any sanitization, this is useful for partial index or index with expressions, such as `{:unsafe_fragment, "(coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL"}` for `ON CONFLICT (coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL` SQL query.
* `:placeholders` - A map with placeholders. This feature is not supported by all databases. See the "Placeholders" section for more information.
See the ["Shared options"](#module-shared-options) section at the module documentation for remaining options.
#### Source query
A query can be given instead of a list with entries. This query needs to select into a map containing only keys that are available as writeable columns in the schema.
#### Examples
```
MyRepo.insert_all(Post, [[title: "My first post"], [title: "My second post"]])
MyRepo.insert_all(Post, [%{title: "My first post"}, %{title: "My second post"}])
query = from p in Post,
join: c in assoc(p, :comments),
select: %{
author_id: p.author_id,
posts: count(p.id, :distinct),
interactions: sum(p.likes) + count(c.id)
},
group_by: p.author_id
MyRepo.insert_all(AuthorStats, query)
```
#### Upserts
[`insert_all/3`](#c:insert_all/3) provides upserts (update or inserts) via the `:on_conflict` option. The `:on_conflict` option supports the following values:
* `:raise` - raises if there is a conflicting primary key or unique index
* `:nothing` - ignores the error in case of conflicts
* `:replace_all` - replace **all** values on the existing row with the values in the schema/changeset, including fields not explicitly set in the changeset, such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`). Do not use this option if you have auto-incrementing primary keys, as they will also be replaced. You most likely want to use `{:replace_all_except, [:id]}` or `{:replace, fields}` explicitly instead. This option requires a schema
* `{:replace_all_except, fields}` - same as above except the given fields are not replaced. This option requires a schema
* `{:replace, fields}` - replace only specific columns. This option requires `:conflict_target`
* a keyword list of update instructions - such as the one given to [`update_all/3`](#c:update_all/3), for example: `[set: [title: "new title"]]`
* an [`Ecto.Query`](ecto.query) that will act as an `UPDATE` statement, such as the one given to [`update_all/3`](#c:update_all/3)
Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" on databases such as MySQL.
#### Return values
By default, both Postgres and MySQL will return the number of entries inserted on [`insert_all/3`](#c:insert_all/3). However, when the `:on_conflict` option is specified, Postgres and MySQL will return different results.
Postgres will only count a row if it was affected and will return 0 if no new entry was added.
MySQL will return, at a minimum, the number of entries attempted. For example, if `:on_conflict` is set to `:nothing`, MySQL will return the number of entries attempted to be inserted, even when no entry was added.
Also note that if `:on_conflict` is a query, MySQL will return the number of attempted entries plus the number of entries modified by the UPDATE query.
#### Placeholders
Passing in a map for the `:placeholders` allows you to send less data over the wire when you have many entries with the same value for a field. To use a placeholder, replace its value in each of your entries with `{:placeholder, key}`, where `key` is the key you are using in the `:placeholders` option map. For example:
```
placeholders = %{blob: large_blob_of_text(...)}
entries = [
%{title: "v1", body: {:placeholder, :blob}},
%{title: "v2", body: {:placeholder, :blob}}
]
Repo.insert_all(Post, entries, placeholders: placeholders)
```
Keep in mind that:
* placeholders cannot be nested in other values. For example, you cannot put a placeholder inside an array. Instead, the whole array has to be the placeholder
* a placeholder key can only be used with columns of the same type
* placeholders require a database that supports index parameters, so they are not currently compatible with MySQL
### insert\_or\_update!(changeset, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1724)
```
@callback insert_or_update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) ::
Ecto.Schema.t()
```
Same as [`insert_or_update/2`](#c:insert_or_update/2) but returns the struct or raises if the changeset is invalid.
### insert\_or\_update(changeset, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1654)
```
@callback insert_or_update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) ::
{:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
```
Inserts or updates a changeset depending on whether the struct is persisted or not.
The distinction whether to insert or update will be made on the [`Ecto.Schema.Metadata`](ecto.schema.metadata) field `:state`. The `:state` is automatically set by Ecto when loading or building a schema.
Please note that for this to work, you will have to load existing structs from the database. So even if the struct exists, this won't work:
```
struct = %Post{id: "existing_id", ...}
MyRepo.insert_or_update changeset
# => {:error, changeset} # id already exists
```
#### Options
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query and any `@schema_prefix` set any schemas. Also, the `@schema_prefix` for the parent record will override all default `@schema_prefix`s set in any child schemas for associations.
* `:stale_error_field` - The field where stale errors will be added in the returning changeset. This option can be used to avoid raising [`Ecto.StaleEntryError`](ecto.staleentryerror). Only applies to updates.
* `:stale_error_message` - The message to add to the configured `:stale_error_field` when stale errors happen, defaults to "is stale". Only applies to updates.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
result =
case MyRepo.get(Post, id) do
nil -> %Post{id: id} # Post not found, we build one
post -> post # Post exists, let's use it
end
|> Post.changeset(changes)
|> MyRepo.insert_or_update
case result do
{:ok, struct} -> # Inserted or updated with success
{:error, changeset} -> # Something went wrong
end
```
### load( schema\_or\_map, data )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L586)
```
@callback load(
schema_or_map :: module() | map(),
data :: map() | Keyword.t() | {list(), list()}
) :: Ecto.Schema.t() | map()
```
Loads `data` into a schema or a map.
The first argument can be a a schema module or a map (of types). The first argument determines the return value: a struct or a map, respectively.
The second argument `data` specifies fields and values that are to be loaded. It can be a map, a keyword list, or a `{fields, values}` tuple. Fields can be atoms or strings.
Fields that are not present in the schema (or `types` map) are ignored. If any of the values has invalid type, an error is raised.
To load data from non-database sources, use [`Ecto.embedded_load/3`](ecto#embedded_load/3).
#### Examples
```
iex> MyRepo.load(User, %{name: "Alice", age: 25})
%User{name: "Alice", age: 25}
iex> MyRepo.load(User, [name: "Alice", age: 25])
%User{name: "Alice", age: 25}
```
`data` can also take form of `{fields, values}`:
```
iex> MyRepo.load(User, {[:name, :age], ["Alice", 25]})
%User{name: "Alice", age: 25, ...}
```
The first argument can also be a `types` map:
```
iex> types = %{name: :string, age: :integer}
iex> MyRepo.load(types, %{name: "Alice", age: 25})
%{name: "Alice", age: 25}
```
This function is especially useful when parsing raw query results:
```
iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT * FROM users", [])
iex> Enum.map(result.rows, &MyRepo.load(User, {result.columns, &1}))
[%User{...}, ...]
```
### preload(structs\_or\_struct\_or\_nil, preloads, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L992)
```
@callback preload(structs_or_struct_or_nil, preloads :: term(), opts :: Keyword.t()) ::
structs_or_struct_or_nil
when structs_or_struct_or_nil: [Ecto.Schema.t()] | Ecto.Schema.t() | nil
```
Preloads all associations on the given struct or structs.
This is similar to [`Ecto.Query.preload/3`](ecto.query#preload/3) except it allows you to preload structs after they have been fetched from the database.
In case the association was already loaded, preload won't attempt to reload it.
#### Options
* `:force` - By default, Ecto won't preload associations that are already loaded. By setting this option to true, any existing association will be discarded and reloaded.
* `:in_parallel` - If the preloads must be done in parallel. It can only be performed when we have more than one preload and the repository is not in a transaction. Defaults to `true`.
* `:prefix` - the prefix to fetch preloads from. By default, queries will use the same prefix as the first struct in the given collection. This option allows the prefix to be changed.
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Examples
```
# Use a single atom to preload an association
posts = Repo.preload posts, :comments
# Use a list of atoms to preload multiple associations
posts = Repo.preload posts, [:comments, :authors]
# Use a keyword list to preload nested associations as well
posts = Repo.preload posts, [comments: [:replies, :likes], authors: []]
# You can mix atoms and keywords, but the atoms must come first
posts = Repo.preload posts, [:authors, comments: [:likes, replies: [:reactions]]]
# Use a keyword list to customize how associations are queried
posts = Repo.preload posts, [comments: from(c in Comment, order_by: c.published_at)]
# Use a two-element tuple for a custom query and nested association definition
query = from c in Comment, order_by: c.published_at
posts = Repo.preload posts, [comments: {query, [:replies, :likes]}]
```
The query given to preload may also preload its own associations.
### reload!(struct\_or\_structs, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L791)
```
@callback reload!(struct_or_structs, opts :: Keyword.t()) :: struct_or_structs
when struct_or_structs: Ecto.Schema.t() | [Ecto.Schema.t()]
```
Similar to [`reload/2`](#c:reload/2), but raises when something is not found.
When using with lists, ordering is guaranteed to be kept.
#### Example
```
MyRepo.reload!(post)
%Post{}
MyRepo.reload!([post1, post2])
[%Post{}, %Post{}]
```
### reload( struct\_or\_structs, opts )[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L775)
```
@callback reload(
struct_or_structs :: Ecto.Schema.t() | [Ecto.Schema.t()],
opts :: Keyword.t()
) :: Ecto.Schema.t() | [Ecto.Schema.t() | nil] | nil
```
Reloads a given schema or schema list from the database.
When using with lists, it is expected that all of the structs in the list belong to the same schema. Ordering is guaranteed to be kept. Results not found in the database will be returned as `nil`.
#### Example
```
MyRepo.reload(post)
%Post{}
MyRepo.reload([post1, post2])
[%Post{}, %Post{}]
MyRepo.reload([deleted_post, post1])
[nil, %Post{}]
```
### update!(changeset, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1716)
```
@callback update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: Ecto.Schema.t()
```
Same as [`update/2`](#c:update/2) but returns the struct or raises if the changeset is invalid.
### update(changeset, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1603)
```
@callback update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) ::
{:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
```
Updates a changeset using its primary key.
A changeset is required as it is the only mechanism for tracking dirty changes. Only the fields present in the `changes` part of the changeset are sent to the database. Any other, in-memory changes done to the schema are ignored. If more than one database operation is required, they're automatically wrapped in a transaction.
If the struct has no primary key, [`Ecto.NoPrimaryKeyFieldError`](ecto.noprimarykeyfielderror) will be raised.
If the struct cannot be found, [`Ecto.StaleEntryError`](ecto.staleentryerror) will be raised.
It returns `{:ok, struct}` if the struct has been successfully updated or `{:error, changeset}` if there was a validation or a known constraint error.
#### Options
* `:returning` - selects which fields to return. It accepts a list of fields to be returned from the database. When `true`, returns all fields. When `false`, no extra fields are returned. It will always include all fields in `read_after_writes`. Not all databases support this option.
* `:force` - By default, if there are no changes in the changeset, [`update/2`](#c:update/2) is a no-op. By setting this option to true, update callbacks will always be executed, even if there are no changes (including timestamps).
* `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query and any `@schema_prefix` set any schemas. Also, the `@schema_prefix` for the parent record will override all default `@schema_prefix`s set in any child schemas for associations.
* `:stale_error_field` - The field where stale errors will be added in the returning changeset. This option can be used to avoid raising [`Ecto.StaleEntryError`](ecto.staleentryerror).
* `:stale_error_message` - The message to add to the configured `:stale_error_field` when stale errors happen, defaults to "is stale".
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
#### Example
```
post = MyRepo.get!(Post, 42)
post = Ecto.Changeset.change post, title: "New title"
case MyRepo.update post do
{:ok, struct} -> # Updated with success
{:error, changeset} -> # Something went wrong
end
```
Transaction API
================
### checked\_out?()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L538)
```
@callback checked_out?() :: boolean()
```
Returns true if a connection has been checked out.
This is true if inside a [`Ecto.Repo.checkout/2`](#c:checkout/2) or [`Ecto.Repo.transaction/2`](#c:transaction/2).
#### Examples
```
MyRepo.checked_out?
#=> false
MyRepo.transaction(fn ->
MyRepo.checked_out? #=> true
end)
MyRepo.checkout(fn ->
MyRepo.checked_out? #=> true
end)
```
### checkout(function, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L515)
```
@callback checkout((() -> result), opts :: Keyword.t()) :: result when result: var
```
Checks out a connection for the duration of the function.
It returns the result of the function. This is useful when you need to perform multiple operations against the repository in a row and you want to avoid checking out the connection multiple times.
`checkout/2` and `transaction/2` can be combined and nested multiple times. If `checkout/2` is called inside the function of another `checkout/2` call, the function is simply executed, without checking out a new connection.
#### Options
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
### in\_transaction?()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1864)
```
@callback in_transaction?() :: boolean()
```
Returns true if the current process is inside a transaction.
If you are using the `Ecto.Adapters.SQL.Sandbox` in tests, note that even though each test is inside a transaction, `in_transaction?/0` will only return true inside transactions explicitly created with `transaction/2`. This is done so the test environment mimics dev and prod.
#### Examples
```
MyRepo.in_transaction?
#=> false
MyRepo.transaction(fn ->
MyRepo.in_transaction? #=> true
end)
```
### rollback(value)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1874)
```
@callback rollback(value :: any()) :: no_return()
```
Rolls back the current transaction.
The transaction will return the value given as `{:error, value}`.
Note that calling `rollback` causes the code in the transaction to stop executing.
### transaction(fun\_or\_multi, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1840)
```
@callback transaction(
fun_or_multi :: (... -> any()) | Ecto.Multi.t(),
opts :: Keyword.t()
) ::
{:ok, any()}
| {:error, any()}
| {:error, Ecto.Multi.name(), any(), %{required(Ecto.Multi.name()) => any()}}
```
Runs the given function or [`Ecto.Multi`](ecto.multi) inside a transaction.
#### Use with function
[`transaction/2`](#c:transaction/2) can be called with both a function of arity zero or one. The arity zero function will just be executed as is:
```
import Ecto.Changeset, only: [change: 2]
MyRepo.transaction(fn ->
MyRepo.update!(change(alice, balance: alice.balance - 10))
MyRepo.update!(change(bob, balance: bob.balance + 10))
end)
```
While the arity one function will receive the repo of the transaction as its first argument:
```
MyRepo.transaction(fn repo ->
repo.insert!(%Post{})
end)
```
If an unhandled error occurs the transaction will be rolled back and the error will bubble up from the transaction function. If no error occurred the transaction will be committed when the function returns. A transaction can be explicitly rolled back by calling [`rollback/1`](#c:rollback/1), this will immediately leave the function and return the value given to `rollback` as `{:error, value}`.
A successful transaction returns the value returned by the function wrapped in a tuple as `{:ok, value}`.
If [`transaction/2`](#c:transaction/2) is called inside another transaction, the function is simply executed, without wrapping the new transaction call in any way. If there is an error in the inner transaction and the error is rescued, or the inner transaction is rolled back, the whole outer transaction is marked as tainted, guaranteeing nothing will be committed.
Below is an example of how rollbacks work with nested transactions:
```
{:error, :rollback} =
MyRepo.transaction(fn ->
{:error, :posting_not_allowed} =
MyRepo.transaction(fn ->
# This function call causes the following to happen:
#
# * the transaction is rolled back in the database,
# * code execution is stopped within the current function,
# * and the value, passed to `rollback/1` is returned from
# `MyRepo.transaction/1` as the second element in the error
# tuple.
#
MyRepo.rollback(:posting_not_allowed)
# `rollback/1` stops execution, so code here won't be run
end)
# When the inner transaction was rolled back, execution in this outer
# transaction is also stopped immediately. When this occurs, the
# outer transaction(s) return `{:error, :rollback}`.
end)
```
#### Use with Ecto.Multi
Besides functions, transactions can be used with an [`Ecto.Multi`](ecto.multi) struct. A transaction will be started, all operations applied and in case of success committed returning `{:ok, changes}`:
```
# With Ecto.Multi
Ecto.Multi.new()
|> Ecto.Multi.insert(:post, %Post{})
|> MyRepo.transaction
```
In case of any errors the transaction will be rolled back and `{:error, failed_operation, failed_value, changes_so_far}` will be returned.
You can read more about using transactions with [`Ecto.Multi`](ecto.multi) as well as see some examples in the [`Ecto.Multi`](ecto.multi) documentation.
#### Working with processes
The transaction is per process. A separate process started inside a transaction won't be part of the same transaction and will use a separate connection altogether.
When using the the `Ecto.Adapters.SQL.Sandbox` in tests, while it may be possible to share the connection between processes, the parent process will typically hold the connection until the transaction completes. This may lead to a deadlock if the child process attempts to use the same connection. See the docs for [`Ecto.Adapters.SQL.Sandbox`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html) for more information.
#### Options
See the ["Shared options"](#module-shared-options) section at the module documentation for more options.
Runtime API
============
### \_\_adapter\_\_()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L461)
```
@callback __adapter__() :: Ecto.Adapter.t()
```
Returns the adapter tied to the repository.
### config()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L470)
```
@callback config() :: Keyword.t()
```
Returns the adapter configuration stored in the `:otp_app` environment.
If the [`init/2`](#c:init/2) callback is implemented in the repository, it will be invoked with the first argument set to `:runtime`.
### get\_dynamic\_repo()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L594)
```
@callback get_dynamic_repo() :: atom() | pid()
```
Returns the atom name or pid of the current repository.
See [`put_dynamic_repo/1`](#c:put_dynamic_repo/1) for more information.
### put\_dynamic\_repo(name\_or\_pid)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L627)
```
@callback put_dynamic_repo(name_or_pid :: atom() | pid()) :: atom() | pid()
```
Sets the dynamic repository to be used in further interactions.
Sometimes you may want a single Ecto repository to talk to many different database instances. By default, when you call `MyApp.Repo.start_link/1`, it will start a repository with name `MyApp.Repo`. But if you want to start multiple repositories, you can give each of them a different name:
```
MyApp.Repo.start_link(name: :tenant_foo, hostname: "foo.example.com")
MyApp.Repo.start_link(name: :tenant_bar, hostname: "bar.example.com")
```
You can also start repositories without names by explicitly setting the name to nil:
```
MyApp.Repo.start_link(name: nil, hostname: "temp.example.com")
```
However, once the repository is started, you can't directly interact with it, since all operations in `MyApp.Repo` are sent by default to the repository named `MyApp.Repo`. You can change the default repo at compile time with:
```
use Ecto.Repo, default_dynamic_repo: :name_of_repo
```
Or you can change it anytime at runtime by calling `put_dynamic_repo/1`:
```
MyApp.Repo.put_dynamic_repo(:tenant_foo)
```
From this moment on, all future queries done by the current process will run on `:tenant_foo`.
### start\_link(opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L485)
```
@callback start_link(opts :: Keyword.t()) ::
{:ok, pid()} | {:error, {:already_started, pid()}} | {:error, term()}
```
Starts any connection pooling or supervision and return `{:ok, pid}` or just `:ok` if nothing needs to be done.
Returns `{:error, {:already_started, pid}}` if the repo is already started or `{:error, term}` in case anything else goes wrong.
#### Options
See the configuration in the moduledoc for options shared between adapters, for adapter-specific configuration see the adapter's documentation.
### stop(timeout)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L494)
```
@callback stop(timeout()) :: :ok
```
Shuts down the repository.
User callbacks
===============
### default\_options(operation)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1051)
```
@callback default_options(operation) :: Keyword.t()
when operation:
:all
| :insert_all
| :update_all
| :delete_all
| :stream
| :transaction
| :insert
| :update
| :delete
| :insert_or_update
```
A user customizable callback invoked to retrieve default options for operations.
This can be used to provide default values per operation that have higher precedence than the values given on configuration or when starting the repository. It can also be used to set query specific options, such as `:prefix`.
This callback is invoked as the entry point for all repository operations. For example, if you are executing a query with preloads, this callback will be invoked once at the beginning, but the options returned here will be passed to all following operations.
### init(context, config)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L452)
```
@callback init(context :: :supervisor | :runtime, config :: Keyword.t()) ::
{:ok, Keyword.t()} | :ignore
```
A callback executed when the repo starts or when configuration is read.
The first argument is the context the callback is being invoked. If it is called because the Repo supervisor is starting, it will be `:supervisor`. It will be `:runtime` if it is called for reading configuration without actually starting a process.
The second argument is the repository configuration as stored in the application environment. It must return `{:ok, keyword}` with the updated list of configuration or `:ignore` (only in the `:supervisor` case).
### prepare\_query(operation, query, opts)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L1032)
```
@callback prepare_query(operation, query :: Ecto.Query.t(), opts :: Keyword.t()) ::
{Ecto.Query.t(), Keyword.t()}
when operation: :all | :update_all | :delete_all | :stream | :insert_all
```
A user customizable callback invoked for query-based operations.
This callback can be used to further modify the query and options before it is transformed and sent to the database.
This callback is invoked for all query APIs, including the `stream` functions. It is also invoked for `insert_all` if a source query is given. It is not invoked for any of the other schema functions.
#### Examples
Let's say you want to filter out records that were "soft-deleted" (have `deleted_at` column set) from all operations unless an admin is running the query; you can define the callback like this:
```
@impl true
def prepare_query(_operation, query, opts) do
if opts[:admin] do
{query, opts}
else
query = from(x in query, where: is_nil(x.deleted_at))
{query, opts}
end
end
```
And then execute the query:
```
Repo.all(query) # only non-deleted records are returned
Repo.all(query, admin: true) # all records are returned
```
The callback will be invoked for all queries, including queries made from associations and preloads. It is not invoked for each individual join inside a query.
Functions
==========
### all\_running()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/repo.ex#L192)
```
@spec all_running() :: [atom() | pid()]
```
Returns all running Ecto repositories.
The list is returned in no particular order. The list contains either atoms, for named Ecto repositories, or PIDs.
| programming_docs |
phoenix Ecto.Adapter behaviour Ecto.Adapter behaviour
=======================
Specifies the minimal API required from adapters.
Summary
========
Types
------
[adapter\_meta()](#t:adapter_meta/0) The metadata returned by the adapter [`init/1`](#c:init/1).
[t()](#t:t/0) Callbacks
----------
[\_\_before\_compile\_\_(env)](#c:__before_compile__/1) The callback invoked in case the adapter needs to inject code.
[checked\_out?(adapter\_meta)](#c:checked_out?/1) Returns true if a connection has been checked out.
[checkout(adapter\_meta, config, function)](#c:checkout/3) Checks out a connection for the duration of the given function.
[dumpers(primitive\_type, ecto\_type)](#c:dumpers/2) Returns the dumpers for a given type.
[ensure\_all\_started(config, type)](#c:ensure_all_started/2) Ensure all applications necessary to run the adapter are started.
[init(config)](#c:init/1) Initializes the adapter supervision tree by returning the children and adapter metadata.
[loaders(primitive\_type, ecto\_type)](#c:loaders/2) Returns the loaders for a given type.
Functions
----------
[lookup\_meta(repo\_name\_or\_pid)](#lookup_meta/1) Returns the adapter metadata from its [`init/1`](#c:init/1) callback.
Types
======
### adapter\_meta()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L18)
```
@type adapter_meta() :: %{
optional(:stacktrace) => boolean(),
optional(any()) => any()
}
```
The metadata returned by the adapter [`init/1`](#c:init/1).
It must be a map and Ecto itself will always inject two keys into the meta:
* the `:cache` key, which as ETS table that can be used as a cache (if available)
* the `:pid` key, which is the PID returned by the child spec returned in [`init/1`](#c:init/1)
### t()[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L6)
```
@type t() :: module()
```
Callbacks
==========
### \_\_before\_compile\_\_(env)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L23)
```
@macrocallback __before_compile__(term(), env :: Macro.Env.t()) :: Macro.t()
```
The callback invoked in case the adapter needs to inject code.
### checked\_out?(adapter\_meta)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L66)
```
@callback checked_out?(adapter_meta()) :: boolean()
```
Returns true if a connection has been checked out.
### checkout(adapter\_meta, config, function)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L61)
```
@callback checkout(adapter_meta(), config :: Keyword.t(), (() -> result)) :: result
when result: var
```
Checks out a connection for the duration of the given function.
In case the adapter provides a pool, this guarantees all of the code inside the given `fun` runs against the same connection, which might improve performance by for instance allowing multiple related calls to the datastore to share cache information:
```
Repo.checkout(fn ->
for _ <- 100 do
Repo.insert!(%Post{})
end
end)
```
If the adapter does not provide a pool, just calling the passed function and returning its result are enough.
If the adapter provides a pool, it is supposed to "check out" one of the pool connections for the duration of the function call. Which connection is checked out is not passed to the calling function, so it should be done using a stateful method like using the current process' dictionary, process tracking, or some kind of other lookup method. Make sure that this stored connection is then used in the other callbacks implementations, such as [`Ecto.Adapter.Queryable`](ecto.adapter.queryable) and [`Ecto.Adapter.Schema`](ecto.adapter.schema).
### dumpers(primitive\_type, ecto\_type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L123)
```
@callback dumpers(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) ::
[
(term() -> {:ok, term()} | :error) | Ecto.Type.t()
]
```
Returns the dumpers for a given type.
It receives the primitive type and the Ecto type (which may be primitive as well). It returns a list of dumpers with the given type usually at the beginning.
This allows developers to properly translate values coming from the Ecto into adapter ones. For example, if the database does not support booleans but instead returns 0 and 1 for them, you could add:
```
def dumpers(:boolean, type), do: [type, &bool_encode/1]
def dumpers(_primitive, type), do: [type]
defp bool_encode(false), do: {:ok, 0}
defp bool_encode(true), do: {:ok, 1}
```
All adapters are required to implement a clause for :binary\_id types, since they are adapter specific. If your adapter does not provide binary ids, you may simply use [`Ecto.UUID`](ecto.uuid):
```
def dumpers(:binary_id, type), do: [type, Ecto.UUID]
def dumpers(_primitive, type), do: [type]
```
### ensure\_all\_started(config, type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L28)
```
@callback ensure_all_started(
config :: Keyword.t(),
type :: :permanent | :transient | :temporary
) ::
{:ok, [atom()]} | {:error, atom()}
```
Ensure all applications necessary to run the adapter are started.
### init(config)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L34)
```
@callback init(config :: Keyword.t()) :: {:ok, :supervisor.child_spec(), adapter_meta()}
```
Initializes the adapter supervision tree by returning the children and adapter metadata.
### loaders(primitive\_type, ecto\_type)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L94)
```
@callback loaders(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) ::
[
(term() -> {:ok, term()} | :error) | Ecto.Type.t()
]
```
Returns the loaders for a given type.
It receives the primitive type and the Ecto type (which may be primitive as well). It returns a list of loaders with the given type usually at the end.
This allows developers to properly translate values coming from the adapters into Ecto ones. For example, if the database does not support booleans but instead returns 0 and 1 for them, you could add:
```
def loaders(:boolean, type), do: [&bool_decode/1, type]
def loaders(_primitive, type), do: [type]
defp bool_decode(0), do: {:ok, false}
defp bool_decode(1), do: {:ok, true}
```
All adapters are required to implement a clause for `:binary_id` types, since they are adapter specific. If your adapter does not provide binary ids, you may simply use [`Ecto.UUID`](ecto.uuid):
```
def loaders(:binary_id, type), do: [Ecto.UUID, type]
def loaders(_primitive, type), do: [type]
```
Functions
==========
### lookup\_meta(repo\_name\_or\_pid)[Source](https://github.com/elixir-ecto/ecto/blob/v3.8.4/lib/ecto/adapter.ex#L136)
Returns the adapter metadata from its [`init/1`](#c:init/1) callback.
It expects a process name of a repository. The name is either an atom or a PID. For a given repository, you often want to call this function based on the repository dynamic repo:
```
Ecto.Adapter.lookup_meta(repo.get_dynamic_repo())
```
phoenix Ecto.Query.CastError exception Ecto.Query.CastError exception
===============================
Raised at runtime when a value cannot be cast.
phoenix Phoenix.HTML.FormData protocol Phoenix.HTML.FormData protocol
===============================
Converts a data structure into a [`Phoenix.HTML.Form`](phoenix.html.form#t:t/0) struct.
Summary
========
Types
------
[t()](#t:t/0) Functions
----------
[input\_type(data, form, field)](#input_type/3) Receives the given field and returns its input type (:text\_input, :select, etc). Returns `nil` if the type is unknown.
[input\_validations(data, form, field)](#input_validations/3) Returns the HTML5 validations that would apply to the given field.
[input\_value(data, form, field)](#input_value/3) Returns the value for the given field.
[to\_form(data, options)](#to_form/2) Converts a data structure into a [`Phoenix.HTML.Form`](phoenix.html.form#t:t/0) struct.
[to\_form(data, form, field, options)](#to_form/4) Converts the field in the given form based on the data structure into a list of [`Phoenix.HTML.Form`](phoenix.html.form#t:t/0) structs.
Types
======
### t()[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form_data.ex#L1)
#### Specs
```
t() :: term()
```
Functions
==========
### input\_type(data, form, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form_data.ex#L48)
#### Specs
```
input_type(t(), Phoenix.HTML.Form.t(), Phoenix.HTML.Form.field()) ::
atom() | nil
```
Receives the given field and returns its input type (:text\_input, :select, etc). Returns `nil` if the type is unknown.
### input\_validations(data, form, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form_data.ex#L41)
#### Specs
```
input_validations(t(), Phoenix.HTML.Form.t(), Phoenix.HTML.Form.field()) ::
Keyword.t()
```
Returns the HTML5 validations that would apply to the given field.
### input\_value(data, form, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form_data.ex#L34)
#### Specs
```
input_value(t(), Phoenix.HTML.Form.t(), Phoenix.HTML.Form.field()) :: term()
```
Returns the value for the given field.
### to\_form(data, options)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form_data.ex#L15)
#### Specs
```
to_form(t(), Keyword.t()) :: Phoenix.HTML.Form.t()
```
Converts a data structure into a [`Phoenix.HTML.Form`](phoenix.html.form#t:t/0) struct.
The options are the same options given to `form_for/4`. It can be used by implementations to configure their behaviour and it must be stored in the underlying struct, with any custom field removed.
### to\_form(data, form, field, options)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form_data.ex#L28)
#### Specs
```
to_form(t(), Phoenix.HTML.Form.t(), Phoenix.HTML.Form.field(), Keyword.t()) :: [
Phoenix.HTML.Form.t()
]
```
Converts the field in the given form based on the data structure into a list of [`Phoenix.HTML.Form`](phoenix.html.form#t:t/0) structs.
The options are the same options given to `inputs_for/4`. It can be used by implementations to configure their behaviour and it must be stored in the underlying struct, with any custom field removed.
phoenix Phoenix.HTML.Format Phoenix.HTML.Format
====================
Helpers related to formatting text.
Summary
========
Functions
----------
[text\_to\_html(string, opts \\ [])](#text_to_html/2) Returns text transformed into HTML using simple formatting rules.
Functions
==========
### text\_to\_html(string, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/format.ex#L34)
#### Specs
```
text_to_html(Phoenix.HTML.unsafe(), Keyword.t()) :: Phoenix.HTML.safe()
```
Returns text transformed into HTML using simple formatting rules.
Two or more consecutive newlines `\n\n` or `\r\n\r\n` are considered as a paragraph and text between them is wrapped in `<p>` tags. One newline `\n` or `\r\n` is considered as a linebreak and a `<br>` tag is inserted.
#### Examples
```
iex> text_to_html("Hello\n\nWorld") |> safe_to_string
"<p>Hello</p>\n<p>World</p>\n"
iex> text_to_html("Hello\nWorld") |> safe_to_string
"<p>Hello<br>\nWorld</p>\n"
iex> opts = [wrapper_tag: :div, attributes: [class: "p"]]
...> text_to_html("Hello\n\nWorld", opts) |> safe_to_string
"<div class=\"p\">Hello</div>\n<div class=\"p\">World</div>\n"
```
#### Options
* `:escape` - if `false` does not html escape input (default: `true`)
* `:wrapper_tag` - tag to wrap each paragraph (default: `:p`)
* `:attributes` - html attributes of the wrapper tag (default: `[]`)
* `:insert_brs` - if `true` insert `<br>` for single line breaks (default: `true`)
phoenix Phoenix.HTML.Tag Phoenix.HTML.Tag
=================
Helpers related to producing HTML tags within templates.
> Note: the examples in this module use `safe_to_string/1` imported from [`Phoenix.HTML`](phoenix.html) for readability.
>
>
>
> Note: with the addition of the HEEx template engine to Phoenix applications, the functions in this module have lost a bit of relevance. Whenever possible, prefer to use the HEEx template engine instead of the functions here. For example, instead of:
>
>
>
> ```
> <%= content_tag :div, class: @class do %>
> Hello
> <% end %>
> ```
>
> Do:
>
>
>
> ```
> <div class={@class}>
> Hello
> </div>
> ```
>
>
Summary
========
Functions
----------
[content\_tag(name, content)](#content_tag/2) Creates an HTML tag with given name, content, and attributes.
[content\_tag(name, attrs, attrs)](#content_tag/3) [csrf\_input\_tag(to, opts \\ [])](#csrf_input_tag/2) Generates a hidden input tag with a CSRF token.
[csrf\_meta\_tag(opts \\ [])](#csrf_meta_tag/1) Generates a meta tag with CSRF information.
[csrf\_token\_value(to \\ %URI{host: nil})](#csrf_token_value/1) Returns the `csrf_token` value to be used by forms, meta tags, etc.
[form\_tag(action, opts \\ [])](#form_tag/2) Generates a form tag.
[form\_tag(action, options, list)](#form_tag/3) Generates a form tag with the given contents.
[img\_tag(src, opts \\ [])](#img_tag/2) Generates an img tag with a src.
[tag(name)](#tag/1) Creates an HTML tag with the given name and options.
[tag(name, attrs)](#tag/2) Functions
==========
### content\_tag(name, content)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L89)
Creates an HTML tag with given name, content, and attributes.
See [`Phoenix.HTML.Tag.tag/2`](#tag/2) for more information and examples.
```
iex> safe_to_string content_tag(:p, "Hello")
"<p>Hello</p>"
iex> safe_to_string content_tag(:p, "<Hello>", class: "test")
"<p class=\"test\"><Hello></p>"
iex> safe_to_string(content_tag :p, class: "test" do
...> "Hello"
...> end)
"<p class=\"test\">Hello</p>"
iex> safe_to_string content_tag(:option, "Display Value", [{:data, [foo: "bar"]}, value: "value"])
"<option data-foo=\"bar\" value=\"value\">Display Value</option>"
```
### content\_tag(name, attrs, attrs)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L97)
### csrf\_input\_tag(to, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L256)
Generates a hidden input tag with a CSRF token.
This could be used when writing a form without the use of tag helpers like [`form_tag/3`](#form_tag/3) or `form_for/4`, while maintaining CSRF protection.
The `to` argument should be the same as the form action.
#### Example
```
<form action="/login" method="POST">
<%= csrf_input_tag("/login") %>
etc.
</form>
```
Additional options to the tag can be given.
### csrf\_meta\_tag(opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L233)
Generates a meta tag with CSRF information.
Additional options to the tag can be given.
### csrf\_token\_value(to \\ %URI{host: nil})[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L223)
Returns the `csrf_token` value to be used by forms, meta tags, etc.
By default, CSRF tokens are generated through [`Plug.CSRFProtection`](https://hexdocs.pm/plug/1.11.0/Plug.CSRFProtection.html) which is capable of generating a separate token per host. Therefore it is recommended to pass the [`URI`](https://hexdocs.pm/elixir/URI.html) of the destination as argument. If none is given `%URI{host: nil}` is used, which implies a local request is being done.
### form\_tag(action, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L151)
Generates a form tag.
This function generates the `<form>` tag without its closing part. Check [`form_tag/3`](#form_tag/3) for generating an enclosing tag.
#### Examples
```
form_tag("/hello")
<form action="/hello" method="post">
form_tag("/hello", method: :get)
<form action="/hello" method="get">
```
#### Options
* `:method` - the HTTP method. If the method is not "get" nor "post", an input tag with name `_method` is generated along-side the form tag. Defaults to "post".
* `:multipart` - when true, sets enctype to "multipart/form-data". Required when uploading files
* `:csrf_token` - for "post" requests, the form tag will automatically include an input tag with name `_csrf_token`. When set to false, this is disabled
All other options are passed to the underlying HTML tag.
#### CSRF Protection
By default, CSRF tokens are generated through [`Plug.CSRFProtection`](https://hexdocs.pm/plug/1.11.0/Plug.CSRFProtection.html).
### form\_tag(action, options, list)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L196)
Generates a form tag with the given contents.
#### Examples
```
form_tag("/hello", method: "get") do
"Hello"
end
<form action="/hello" method="get">...Hello...</form>
```
### img\_tag(src, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L288)
Generates an img tag with a src.
#### Examples
```
img_tag(user.photo_path)
<img src="/photo.png">
img_tag(user.photo, class: "image")
<img src="/smile.png" class="image">
```
To generate a path to an image hosted in your application "priv/static", with the `@conn` endpoint, use `static_path/2` to get a URL with cache control parameters:
```
img_tag(Routes.static_path(@conn, "/logo.png"))
<img src="/logo-123456.png?vsn=d">
```
For responsive images, pass a map, list or string through `:srcset`.
```
img_tag("/logo.png", srcset: %{"/logo.png" => "1x", "/logo-2x.png" => "2x"})
<img src="/logo.png" srcset="/logo.png 1x, /logo-2x.png 2x">
img_tag("/logo.png", srcset: ["/logo.png", {"/logo-2x.png", "2x"}])
<img src="/logo.png" srcset="/logo.png, /logo-2x.png 2x">
```
### tag(name)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L63)
Creates an HTML tag with the given name and options.
```
iex> safe_to_string tag(:br)
"<br>"
iex> safe_to_string tag(:input, type: "text", name: "user_id")
"<input name=\"user_id\" type=\"text\">"
```
#### Data attributes
In order to add custom data attributes you need to pass a tuple containing :data atom and a keyword list with data attributes' names and values as the first element in the tag's attributes keyword list:
```
iex> safe_to_string tag(:input, [data: [foo: "bar"], id: "some_id"])
"<input data-foo=\"bar\" id=\"some_id\">"
```
#### Boolean values
In case an attribute contains a boolean value, its key is repeated when it is true, as expected in HTML, or the attribute is completely removed if it is false:
```
iex> safe_to_string tag(:audio, autoplay: "autoplay")
"<audio autoplay=\"autoplay\">"
iex> safe_to_string tag(:audio, autoplay: true)
"<audio autoplay>"
iex> safe_to_string tag(:audio, autoplay: false)
"<audio>"
```
If you want the boolean attribute to be sent as is, you can explicitly convert it to a string before.
### tag(name, attrs)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/tag.ex#L65)
phoenix Phoenix.HTML.Engine Phoenix.HTML.Engine
====================
This is an implementation of EEx.Engine that guarantees templates are HTML Safe.
The [`encode_to_iodata!/1`](#encode_to_iodata!/1) function converts the rendered template result into iodata.
Summary
========
Functions
----------
[encode\_to\_iodata!(bin)](#encode_to_iodata!/1) Encodes the HTML templates to iodata.
Functions
==========
### encode\_to\_iodata!(bin)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/engine.ex#L21)
Encodes the HTML templates to iodata.
| programming_docs |
phoenix Phoenix.HTML.Link Phoenix.HTML.Link
==================
Conveniences for working with links and URLs in HTML.
Summary
========
Functions
----------
[button(opts, opts)](#button/2) Generates a button tag that uses the Javascript function handleClick() (see phoenix\_html.js) to submit the form data.
[link(text, opts)](#link/2) Generates a link to the given URL.
Functions
==========
### button(opts, opts)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/link.ex#L196)
Generates a button tag that uses the Javascript function handleClick() (see phoenix\_html.js) to submit the form data.
Useful to ensure that links that change data are not triggered by search engines and other spidering software.
#### Examples
```
button("hello", to: "/world")
#=> <button class="button" data-csrf="csrf_token" data-method="post" data-to="/world">hello</button>
button("hello", to: "/world", method: :get, class: "btn")
#=> <button class="btn" data-method="get" data-to="/world">hello</button>
```
#### Options
* `:to` - the page to link to. This option is required
* `:method` - the method to use with the button. Defaults to :post.
All other options are forwarded to the underlying button input.
When the `:method` is set to `:get` and the `:to` URL contains query parameters the generated form element will strip the parameters in accordance with the [W3C](https://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.4) form specification.
#### Data attributes
Data attributes are added as a keyword list passed to the `data` key. The following data attributes are supported:
* `data-confirm` - shows a confirmation prompt before generating and submitting the form.
### link(text, opts)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/link.ex#L135)
Generates a link to the given URL.
#### Examples
```
link("hello", to: "/world")
#=> <a href="/world">hello</a>
link("hello", to: URI.parse("https://elixir-lang.org"))
#=> <a href="https://elixir-lang.org">hello</a>
link("<hello>", to: "/world")
#=> <a href="/world"><hello></a>
link("<hello>", to: "/world", class: "btn")
#=> <a class="btn" href="/world"><hello></a>
link("delete", to: "/the_world", data: [confirm: "Really?"])
#=> <a data-confirm="Really?" href="/the_world">delete</a>
# If you supply a method other than `:get`:
link("delete", to: "/everything", method: :delete)
#=> <a href="/everything" data-csrf="csrf_token" data-method="delete" data-to="/everything">delete</a>
# You can use a `do ... end` block too:
link to: "/hello" do
"world"
end
```
#### Options
* `:to` - the page to link to. This option is required
* `:method` - the method to use with the link. In case the method is not `:get`, the link is generated inside the form which sets the proper information. In order to submit the form, JavaScript must be enabled
* `:csrf_token` - a custom token to use for links with a method other than `:get`.
All other options are forwarded to the underlying `<a>` tag.
#### JavaScript dependency
In order to support links where `:method` is not `:get` or use the above data attributes, [`Phoenix.HTML`](phoenix.html) relies on JavaScript. You can load `priv/static/phoenix_html.js` into your build tool.
### Data attributes
Data attributes are added as a keyword list passed to the `data` key. The following data attributes are supported:
* `data-confirm` - shows a confirmation prompt before generating and submitting the form when `:method` is not `:get`.
### Overriding the default confirm behaviour
`phoenix_html.js` does trigger a custom event `phoenix.link.click` on the clicked DOM element when a click happened. This allows you to intercept the event on it's way bubbling up to `window` and do your own custom logic to enhance or replace how the `data-confirm` attribute is handled.
You could for example replace the browsers `confirm()` behavior with a custom javascript implementation:
```
// listen on document.body, so it's executed before the default of
// phoenix_html, which is listening on the window object
document.body.addEventListener('phoenix.link.click', function (e) {
// Prevent default implementation
e.stopPropagation();
// Introduce alternative implementation
var message = e.target.getAttribute("data-confirm");
if(!message){ return true; }
vex.dialog.confirm({
message: message,
callback: function (value) {
if (value == false) { e.preventDefault(); }
}
})
}, false);
```
Or you could attach your own custom behavior.
```
window.addEventListener('phoenix.link.click', function (e) {
// Introduce custom behaviour
var message = e.target.getAttribute("data-prompt");
var answer = e.target.getAttribute("data-prompt-answer");
if(message && answer && (answer != window.prompt(message))) {
e.preventDefault();
}
}, false);
```
The latter could also be bound to any `click` event, but this way you can be sure your custom code is only executed when the code of `phoenix_html.js` is run.
#### CSRF Protection
By default, CSRF tokens are generated through [`Plug.CSRFProtection`](https://hexdocs.pm/plug/1.11.0/Plug.CSRFProtection.html).
phoenix Phoenix.HTML Phoenix.HTML
=============
Helpers for working with HTML strings and templates.
When used, it imports the given modules:
* [`Phoenix.HTML`](phoenix.html#content) - functions to handle HTML safety;
* [`Phoenix.HTML.Tag`](phoenix.html.tag) - functions for generating HTML tags;
* [`Phoenix.HTML.Form`](phoenix.html.form) - functions for working with forms;
* [`Phoenix.HTML.Link`](phoenix.html.link) - functions for generating links and urls;
* [`Phoenix.HTML.Format`](phoenix.html.format) - functions for formatting text;
HTML Safe
----------
One of the main responsibilities of this module is to provide convenience functions for escaping and marking HTML code as safe.
By default, data output in templates is not considered safe:
```
<%= "<hello>" %>
```
will be shown as:
```
<hello>
```
User data or data coming from the database is almost never considered safe. However, in some cases, you may want to tag it as safe and show its "raw" contents:
```
<%= raw "<hello>" %>
```
Keep in mind most helpers will automatically escape your data and return safe content:
```
<%= content_tag :p, "<hello>" %>
```
will properly output:
```
<p><hello></p>
```
JavaScript library
-------------------
This project ships with a tiny bit of JavaScript that listens to all click events to:
* Support `data-confirm="message"` attributes, which shows a confirmation modal with the given message
* Support `data-method="patch|post|put|delete"` attributes, which sends the current click as a PATCH/POST/PUT/DELETE HTTP request. You will need to add `data-to` with the URL and `data-csrf` with the CSRF token value
* Dispatch a "phoenix.link.click" event. You can listen to this event to customize the behaviour above. Returning false from this event will disable `data-method`. Stopping propagation will disable `data-confirm`
Summary
========
Types
------
[safe()](#t:safe/0) Guaranteed to be safe
[unsafe()](#t:unsafe/0) May be safe or unsafe (i.e. it needs to be converted)
Functions
----------
[attributes\_escape(attrs)](#attributes_escape/1) Escapes an enumerable of attributes, returning iodata.
[html\_escape(safe)](#html_escape/1) Escapes the HTML entities in the given term, returning safe iodata.
[javascript\_escape(data)](#javascript_escape/1) Escapes HTML content to be inserted a JavaScript string.
[raw(value)](#raw/1) Marks the given content as raw.
[safe\_to\_string(arg)](#safe_to_string/1) Converts a safe result into a string.
Types
======
### safe()[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html.ex#L79)
#### Specs
```
safe() :: {:safe, iodata()}
```
Guaranteed to be safe
### unsafe()[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html.ex#L82)
#### Specs
```
unsafe() :: Phoenix.HTML.Safe.t()
```
May be safe or unsafe (i.e. it needs to be converted)
Functions
==========
### attributes\_escape(attrs)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html.ex#L207)
Escapes an enumerable of attributes, returning iodata.
The attributes are rendered in the given order. Note if a map is given, the key ordering is not guaranteed.
The keys and values can be of any shape, as long as they implement the [`Phoenix.HTML.Safe`](phoenix.html.safe) protocol. In addition, if the key is an atom, it will be "dasherized". In other words, `:phx_value_id` will be converted to `phx-value-id`.
Furthemore, the following attributes provide behaviour:
* `:aria`, `:data`, and `:phx` - they accept a keyword list as value. `data: [confirm: "are you sure?"]` is converted to `data-confirm="are you sure?"`.
* `:class` - it accepts a list of classes as argument. Each element in the list is separated by space. `nil` and `false` elements are discarded. `class: ["foo", nil, "bar"]` then becomes `class="foo bar"`.
* `:id` - it is validated raise if a number is given as ID, which is not allowed by the HTML spec and leads to unpredictable behaviour.
#### Examples
```
iex> safe_to_string attributes_escape(title: "the title", id: "the id", selected: true)
" title=\"the title\" id=\"the id\" selected"
iex> safe_to_string attributes_escape(%{data: [confirm: "Are you sure?"], class: "foo"})
" class=\"foo\" data-confirm=\"Are you sure?\""
iex> safe_to_string attributes_escape(%{phx: [value: [foo: "bar"]], class: "foo"})
" class=\"foo\" phx-value-foo=\"bar\""
```
### html\_escape(safe)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html.ex#L150)
#### Specs
```
html_escape(unsafe()) :: safe()
```
Escapes the HTML entities in the given term, returning safe iodata.
```
iex> html_escape("<hello>")
{:safe, [[[] | "<"], "hello" | ">"]}
iex> html_escape('<hello>')
{:safe, ["<", 104, 101, 108, 108, 111, ">"]}
iex> html_escape(1)
{:safe, "1"}
iex> html_escape({:safe, "<hello>"})
{:safe, "<hello>"}
```
### javascript\_escape(data)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html.ex#L308)
#### Specs
```
javascript_escape(binary()) :: binary()
```
```
javascript_escape(safe()) :: safe()
```
Escapes HTML content to be inserted a JavaScript string.
This function is useful in JavaScript responses when there is a need to escape HTML rendered from other templates, like in the following:
```
$("#container").append("<%= javascript_escape(render("post.html", post: @post)) %>");
```
It escapes quotes (double and single), double backslashes and others.
### raw(value)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html.ex#L129)
#### Specs
```
raw(iodata() | safe() | nil) :: safe()
```
Marks the given content as raw.
This means any HTML code inside the given string won't be escaped.
```
iex> raw("<hello>")
{:safe, "<hello>"}
iex> raw({:safe, "<hello>"})
{:safe, "<hello>"}
iex> raw(nil)
{:safe, ""}
```
### safe\_to\_string(arg)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html.ex#L165)
#### Specs
```
safe_to_string(safe()) :: String.t()
```
Converts a safe result into a string.
Fails if the result is not safe. In such cases, you can invoke [`html_escape/1`](#html_escape/1) or [`raw/1`](#raw/1) accordingly before.
You can combine [`html_escape/1`](#html_escape/1) and [`safe_to_string/1`](#safe_to_string/1) to convert a data structure to a escaped string:
```
data |> html_escape() |> safe_to_string()
```
phoenix Phoenix.HTML.Safe protocol Phoenix.HTML.Safe protocol
===========================
Defines the HTML safe protocol.
In order to promote HTML safety, Phoenix templates do not use [`Kernel.to_string/1`](https://hexdocs.pm/elixir/Kernel.html#to_string/1) to convert data types to strings in templates. Instead, Phoenix uses this protocol which must be implemented by data structures and guarantee that a HTML safe representation is returned.
Furthermore, this protocol relies on iodata, which provides better performance when sending or streaming data to the client.
Summary
========
Types
------
[t()](#t:t/0) Functions
----------
[to\_iodata(data)](#to_iodata/1) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/safe.ex#L1)
#### Specs
```
t() :: term()
```
Functions
==========
### to\_iodata(data)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/safe.ex#L15)
phoenix Phoenix.HTML.Form Phoenix.HTML.Form
==================
Helpers related to producing HTML forms.
The functions in this module can be used in three distinct scenarios:
* with changeset data - when information to populate the form comes from a changeset
* with limited data - when a form is created without an underlying data layer. In this scenario, you can use the connection information (aka Plug.Conn.params) or pass the form values by hand
* outside of a form - when the functions are used directly, outside of `form_for`
We will explore all three scenarios below.
With changeset data
--------------------
The entry point for defining forms in Phoenix is with the [`form_for/4`](#form_for/4) function. For this example, we will use `Ecto.Changeset`, which integrates nicely with Phoenix forms via the `phoenix_ecto` package.
Imagine you have the following action in your controller:
```
def new(conn, _params) do
changeset = User.changeset(%User{})
render conn, "new.html", changeset: changeset
end
```
where `User.changeset/2` is defined as follows:
```
def changeset(user, params \\ %{}) do
cast(user, params, [:name, :age])
end
```
Now a `@changeset` assign is available in views which we can pass to the form:
```
<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
<label>
Name: <%= text_input f, :name %>
</label>
<label>
Age: <%= select f, :age, 18..100 %>
</label>
<%= submit "Submit" %>
<% end %>
```
[`form_for/4`](#form_for/4) receives the `Ecto.Changeset` and converts it to a form, which is passed to the function as the argument `f`. All the remaining functions in this module receive the form and automatically generate the input fields, often by extracting information from the given changeset. For example, if the user had a default value for age set, it will automatically show up as selected in the form.
### A note on `:errors`
If no action has been applied to the changeset or action was set to `:ignore`, no errors are shown on the form object even if the changeset has a non-empty `:errors` value.
This is useful for things like validation hints on form fields, e.g. an empty changeset for a new form. That changeset isn't valid, but we don't want to show errors until an actual user action has been performed.
Ecto automatically applies the action for you when you call Repo.insert/update/delete, but if you want to show errors manually you can also set the action yourself, either directly on the `Ecto.Changeset` struct field or by using `Ecto.Changeset.apply_action/2`.
With limited data
------------------
[`form_for/4`](#form_for/4) expects as first argument any data structure that implements the [`Phoenix.HTML.FormData`](phoenix.html.formdata) protocol. By default, Phoenix implements this protocol for [`Plug.Conn`](https://hexdocs.pm/plug/1.11.0/Plug.Conn.html) and [`Atom`](https://hexdocs.pm/elixir/Atom.html).
This is useful when you are creating forms that are not backed by any kind of data layer. Let's assume that we're submitting a form to the `:new` action in the `FooController`:
```
<%= form_for @conn, Routes.foo_path(@conn, :new), [as: :foo], fn f -> %>
<%= text_input f, :for %>
<%= submit "Search" %>
<% end %>
```
[`form_for/4`](#form_for/4) uses the [`Plug.Conn`](https://hexdocs.pm/plug/1.11.0/Plug.Conn.html) to set input values from the request parameters.
Alternatively, if you don't have a connection, you can pass `:foo` as the form data source and explicitly pass the value for every input:
```
<%= form_for :foo, Routes.foo_path(MyApp.Endpoint, :new), fn f -> %>
<%= text_input f, :for, value: "current value" %>
<%= submit "Search" %>
<% end %>
```
Without form data
------------------
Sometimes we may want to generate a [`text_input/3`](#text_input/3) or any other tag outside of a form. The functions in this module also support such usage by simply passing an atom as first argument instead of the form.
```
<%= text_input :user, :name, value: "This is a prepopulated value" %>
```
Nested inputs
--------------
If your data layer supports embedding or nested associations, you can use `inputs_for` to attach nested data to the form.
Imagine the following Ecto schemas:
```
defmodule User do
use Ecto.Schema
schema "users" do
field :name
embeds_one :permalink, Permalink
end
end
defmodule Permalink do
use Ecto.Schema
embedded_schema do
field :url
end
end
```
In the form, you now can:
```
<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
<%= text_input f, :name %>
<%= inputs_for f, :permalink, fn fp -> %>
<%= text_input fp, :url %>
<% end %>
<% end %>
```
The default option can be given to populate the fields if none is given:
```
<%= inputs_for f, :permalink, [default: %Permalink{title: "default"}], fn fp -> %>
<%= text_input fp, :url %>
<% end %>
```
[`inputs_for/4`](#inputs_for/4) can be used to work with single entities or collections. When working with collections, `:prepend` and `:append` can be used to add entries to the collection stored in the changeset.
CSRF protection
----------------
The form generates a CSRF token by default. Your application should check this token on the server to avoid attackers from making requests on your server on behalf of other users. Phoenix by default checks this token.
When posting a form with a host in its address, such as "//host.com/path" instead of only "/path", Phoenix will include the host signature in the token and validate the token only if the accessed host is the same as the host in the token. This is to avoid tokens from leaking to third party applications. If this behaviour is problematic, you can generate a non-host specific token with [`Plug.CSRFProtection.get_csrf_token/0`](https://hexdocs.pm/plug/1.11.0/Plug.CSRFProtection.html#get_csrf_token/0) and pass it to the form generator via the `:csrf_token` option.
Phoenix.LiveView integration
-----------------------------
Phoenix.LiveView builds on top of this function to [provide a function component named `form`](../phoenix_live_view/phoenix.liveview.helpers#form/1). Inside your HEEx templates, instead of doing this:
```
<%= form_for @changeset, url, opts, fn f -> %>
<%= text_input f, :name %>
<% end %>
```
you should import `Phoenix.LiveView.Helpers` and then write:
```
<.form let={f} for={@changeset}>
<%= text_input f, :name %>
</.form>
```
Summary
========
Types
------
[field()](#t:field/0) [t()](#t:t/0) Functions
----------
[%Phoenix.HTML.Form{}](#__struct__/0) Defines the Phoenix.HTML.Form struct.
[checkbox(form, field, opts \\ [])](#checkbox/3) Generates a checkbox.
[color\_input(form, field, opts \\ [])](#color_input/3) Generates a color input.
[date\_input(form, field, opts \\ [])](#date_input/3) Generates a date input.
[date\_select(form, field, opts \\ [])](#date_select/3) Generates select tags for date.
[datetime\_local\_input(form, field, opts \\ [])](#datetime_local_input/3) Generates a datetime-local input.
[datetime\_select(form, field, opts \\ [])](#datetime_select/3) Generates select tags for datetime.
[email\_input(form, field, opts \\ [])](#email_input/3) Generates an email input.
[file\_input(form, field, opts \\ [])](#file_input/3) Generates a file input.
[form\_for(form\_data, action, options)](#form_for/3) deprecated Generates a form tag with a form builder **without** an anonymous function.
[form\_for(form\_data, action, options \\ [], fun)](#form_for/4) Generates a form tag with a form builder and an anonymous function.
[hidden\_input(form, field, opts \\ [])](#hidden_input/3) Generates a hidden input.
[hidden\_inputs\_for(form)](#hidden_inputs_for/1) Generates hidden inputs for the given form.
[humanize(atom)](#humanize/1) Converts an attribute/form field into its humanize version.
[input\_id(name, field)](#input_id/2) Returns an id of a corresponding form field.
[input\_id(name, field, value)](#input_id/3) Returns an id of a corresponding form field and value attached to it.
[input\_name(form\_or\_name, field)](#input_name/2) Returns a name of a corresponding form field.
[input\_type( form, field, mapping \\ %{ "email" => :email\_input, "password" => :password\_input, "search" => :search\_input, "url" => :url\_input } )](#input_type/3) Gets the input type for a given field.
[input\_validations(form, field)](#input_validations/2) Returns the HTML5 validations that would apply to the given field.
[input\_value(form, field)](#input_value/2) Returns a value of a corresponding form field.
[inputs\_for(form, field)](#inputs_for/2) Same as `inputs_for(form, field, [])`.
[inputs\_for(form, field, options)](#inputs_for/3) Generate a new form builder for the given parameter in form **without** an anonymous function.
[inputs\_for(form, field, options \\ [], fun)](#inputs_for/4) Generate a new form builder for the given parameter in form.
[label(do\_block)](#label/1) Generates a label tag.
[label(opts, field)](#label/2) Generates a label tag for the given field.
[label(form, field, text\_or\_do\_block\_or\_attributes)](#label/3) See [`label/2`](#label/2).
[label(form, field, text, do\_block\_or\_attributes)](#label/4) See [`label/2`](#label/2).
[multiple\_select(form, field, options, opts \\ [])](#multiple_select/4) Generates a select tag with the given `options`.
[number\_input(form, field, opts \\ [])](#number_input/3) Generates a number input.
[options\_for\_select(options, selected\_values)](#options_for_select/2) Returns options to be used inside a select.
[password\_input(form, field, opts \\ [])](#password_input/3) Generates a password input.
[radio\_button(form, field, value, opts \\ [])](#radio_button/4) Generates a radio button.
[range\_input(form, field, opts \\ [])](#range_input/3) Generates a range input.
[reset(value, opts \\ [])](#reset/2) Generates a reset input to reset all the form fields to their original state.
[search\_input(form, field, opts \\ [])](#search_input/3) Generates a search input.
[select(form, field, options, opts \\ [])](#select/4) Generates a select tag with the given `options`.
[submit(block\_option)](#submit/1) Generates a submit button to send the form.
[submit(value, opts \\ [])](#submit/2) Generates a submit button to send the form.
[telephone\_input(form, field, opts \\ [])](#telephone_input/3) Generates a telephone input.
[text\_input(form, field, opts \\ [])](#text_input/3) Generates a text input.
[textarea(form, field, opts \\ [])](#textarea/3) Generates a textarea input.
[time\_input(form, field, opts \\ [])](#time_input/3) Generates a time input.
[time\_select(form, field, opts \\ [])](#time_select/3) Generates select tags for time.
[url\_input(form, field, opts \\ [])](#url_input/3) Generates an url input.
Types
======
### field()[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L256)
#### Specs
```
field() :: atom() | String.t()
```
### t()[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L242)
#### Specs
```
t() :: %Phoenix.HTML.Form{
action: nil | String.t(),
data: %{required(field()) => term()},
errors: Keyword.t(),
hidden: Keyword.t(),
id: String.t(),
impl: module(),
index: nil | non_neg_integer(),
name: String.t(),
options: Keyword.t(),
params: %{required(binary()) => term()},
source: Phoenix.HTML.FormData.t()
}
```
Functions
==========
### %Phoenix.HTML.Form{}[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L230)
Defines the Phoenix.HTML.Form struct.
Its fields are:
* `:source` - the data structure given to [`form_for/4`](#form_for/4) that implements the form data protocol
* `:impl` - the module with the form data protocol implementation. This is used to avoid multiple protocol dispatches.
* `:id` - the id to be used when generating input fields
* `:index` - the index of the struct in the form
* `:name` - the name to be used when generating input fields
* `:data` - the field used to store lookup data
* `:params` - the parameters associated to this form in case they were sent as part of a previous request
* `:hidden` - a keyword list of fields that are required for submitting the form behind the scenes as hidden inputs
* `:options` - a copy of the options given when creating the form via [`form_for/4`](#form_for/4) without any form data specific key
* `:action` - the action the form is meant to submit to
* `:errors` - a keyword list of errors that associated with the form
### checkbox(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1043)
Generates a checkbox.
This function is useful for sending boolean values to the server.
#### Examples
```
# Assuming form contains a User schema
checkbox(form, :famous)
#=> <input name="user[famous]" type="hidden" value="false">
#=> <input checked="checked" id="user_famous" name="user[famous]" type="checkbox" value="true">
```
#### Options
* `:checked_value` - the value to be sent when the checkbox is checked. Defaults to "true"
* `:hidden_input` - controls if this function will generate a hidden input to submit the unchecked value or not. Defaults to "true"
* `:unchecked_value` - the value to be sent when the checkbox is unchecked, Defaults to "false"
* `:value` - the value used to check if a checkbox is checked or unchecked. The default value is extracted from the form data if available
All other options are forwarded to the underlying HTML tag.
#### Hidden fields
Because an unchecked checkbox is not sent to the server, Phoenix automatically generates a hidden field with the unchecked\_value *before* the checkbox field to ensure the `unchecked_value` is sent when the checkbox is not marked. Set `hidden_input` to false If you don't want to send values from unchecked checkbox to the server.
### color\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L728)
Generates a color input.
Warning: this feature isn't available in all browsers. Check `http://caniuse.com/#feat=input-color` for further information.
See [`text_input/3`](#text_input/3) for example and docs.
### date\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L749)
Generates a date input.
Warning: this feature isn't available in all browsers. Check `http://caniuse.com/#feat=input-datetime` for further information.
See [`text_input/3`](#text_input/3) for example and docs.
### date\_select(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1517)
Generates select tags for date.
Check [`datetime_select/3`](#datetime_select/3) for more information on options and supported values.
### datetime\_local\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L761)
Generates a datetime-local input.
Warning: this feature isn't available in all browsers. Check `http://caniuse.com/#feat=input-datetime` for further information.
See [`text_input/3`](#text_input/3) for example and docs.
### datetime\_select(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1498)
Generates select tags for datetime.
#### Examples
```
# Assuming form contains a User schema
datetime_select form, :born_at
#=> <select id="user_born_at_year" name="user[born_at][year]">...</select> /
#=> <select id="user_born_at_month" name="user[born_at][month]">...</select> /
#=> <select id="user_born_at_day" name="user[born_at][day]">...</select> —
#=> <select id="user_born_at_hour" name="user[born_at][hour]">...</select> :
#=> <select id="user_born_at_min" name="user[born_at][minute]">...</select>
```
If you want to include the seconds field (hidden by default), pass `second: []`:
```
# Assuming form contains a User schema
datetime_select form, :born_at, second: []
```
If you want to configure the years range:
```
# Assuming form contains a User schema
datetime_select form, :born_at, year: [options: 1900..2100]
```
You are also able to configure `:month`, `:day`, `:hour`, `:minute` and `:second`. All options given to those keys will be forwarded to the underlying select. See [`select/4`](#select/4) for more information.
For example, if you are using Phoenix with Gettext and you want to localize the list of months, you can pass `:options` to the `:month` key:
```
# Assuming form contains a User schema
datetime_select form, :born_at, month: [
options: [
{gettext("January"), "1"},
{gettext("February"), "2"},
{gettext("March"), "3"},
{gettext("April"), "4"},
{gettext("May"), "5"},
{gettext("June"), "6"},
{gettext("July"), "7"},
{gettext("August"), "8"},
{gettext("September"), "9"},
{gettext("October"), "10"},
{gettext("November"), "11"},
{gettext("December"), "12"},
]
]
```
You may even provide your own `localized_datetime_select/3` built on top of [`datetime_select/3`](#datetime_select/3):
```
defp localized_datetime_select(form, field, opts \\ []) do
opts =
Keyword.put(opts, :month, options: [
{gettext("January"), "1"},
{gettext("February"), "2"},
{gettext("March"), "3"},
{gettext("April"), "4"},
{gettext("May"), "5"},
{gettext("June"), "6"},
{gettext("July"), "7"},
{gettext("August"), "8"},
{gettext("September"), "9"},
{gettext("October"), "10"},
{gettext("November"), "11"},
{gettext("December"), "12"},
])
datetime_select(form, field, opts)
end
```
#### Options
* `:value` - the value used to select a given option. The default value is extracted from the form data if available
* `:default` - the default value to use when none was given in `:value` and none is available in the form data
* `:year`, `:month`, `:day`, `:hour`, `:minute`, `:second` - options passed to the underlying select. See [`select/4`](#select/4) for more information. The available values can be given in `:options`.
* `:builder` - specify how the select can be build. It must be a function that receives a builder that should be invoked with the select name and a set of options. See builder below for more information.
#### Builder
The generated datetime\_select can be customized at will by providing a builder option. Here is an example from EEx:
```
<%= datetime_select form, :born_at, builder: fn b -> %>
Date: <%= b.(:day, []) %> / <%= b.(:month, []) %> / <%= b.(:year, []) %>
Time: <%= b.(:hour, []) %> : <%= b.(:minute, []) %>
<% end %>
```
Although we have passed empty lists as options (they are required), you could pass any option there and it would be given to the underlying select input.
In practice, we recommend you to create your own helper with your default builder:
```
def my_datetime_select(form, field, opts \\ []) do
builder = fn b ->
assigns = %{b: b}
~H"""
Date: <%= @b.(:day, []) %> / <%= @b.(:month, []) %> / <%= @b.(:year, []) %>
Time: <%= @b.(:hour, []) %> : <%= @b.(:minute, []) %>
"""
end
datetime_select(form, field, [builder: builder] ++ opts)
end
```
Then you are able to use your own datetime\_select throughout your whole application.
#### Supported date values
The following values are supported as date:
* a map containing the `year`, `month` and `day` keys (either as strings or atoms)
* a tuple with three elements: `{year, month, day}`
* a string in ISO 8601 format
* `nil`
#### Supported time values
The following values are supported as time:
* a map containing the `hour` and `minute` keys and an optional `second` key (either as strings or atoms)
* a tuple with three elements: `{hour, min, sec}`
* a tuple with four elements: `{hour, min, sec, usec}`
* `nil`
### email\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L661)
Generates an email input.
See [`text_input/3`](#text_input/3) for example and docs.
### file\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L881)
Generates a file input.
It requires the given form to be configured with `multipart: true` when invoking [`form_for/4`](#form_for/4), otherwise it fails with [`ArgumentError`](https://hexdocs.pm/elixir/ArgumentError.html).
See [`text_input/3`](#text_input/3) for example and docs.
### form\_for(form\_data, action, options)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L315)
This function is deprecated. This functionality is deprecated in favor of form\_for with a function. #### Specs
```
form_for(Phoenix.HTML.FormData.t(), String.t(), Keyword.t()) :: t()
```
```
form_for(Phoenix.HTML.FormData.t(), String.t(), (t() -> Phoenix.HTML.unsafe())) ::
Phoenix.HTML.safe()
```
Generates a form tag with a form builder **without** an anonymous function.
This functionality exists mostly for integration with `Phoenix.LiveView` that replaces the anonymous function for explicit closing of the `<form>` tag:
```
<%= f = form_for @changeset, Routes.user_path(@conn, :create), opts %>
Name: <%= text_input f, :name %>
</form>
```
See the [Phoenix.LiveView integration](#module-phoenix-liveview-integration) section in module documentation for examples of using this function.
See [`form_for/4`](#form_for/4) for the available options.
### form\_for(form\_data, action, options \\ [], fun)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L360)
#### Specs
```
form_for(
Phoenix.HTML.FormData.t(),
String.t(),
Keyword.t(),
(t() -> Phoenix.HTML.unsafe())
) ::
Phoenix.HTML.safe()
```
Generates a form tag with a form builder and an anonymous function.
```
<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
Name: <%= text_input f, :name %>
<% end %>
```
See the module documentation for examples of using this function.
#### Options
* `:as` - the server side parameter in which all params for this form will be collected (i.e. `as: :user_params` would mean all fields for this form will be accessed as `conn.params.user_params` server side). Automatically inflected when a changeset is given.
* `:method` - the HTTP method. If the method is not "get" nor "post", an input tag with name `_method` is generated along-side the form tag. Defaults to "post".
* `:multipart` - when true, sets enctype to "multipart/form-data". Required when uploading files
* `:csrf_token` - for "post" requests, the form tag will automatically include an input tag with name `_csrf_token`. When set to false, this is disabled
* `:errors` - use this to manually pass a keyword list of errors to the form (for example from `conn.assigns[:errors]`). This option is only used when a connection is used as the form source and it will make the errors available under `f.errors`
* `:id` - the ID of the form attribute. If an ID is given, all form inputs will also be prefixed by the given ID
All other options will be passed as html attributes, such as `class: "foo"`.
### hidden\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L625)
Generates a hidden input.
See [`text_input/3`](#text_input/3) for example and docs.
### hidden\_inputs\_for(form)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L633)
#### Specs
```
hidden_inputs_for(t()) :: [Phoenix.HTML.safe()]
```
Generates hidden inputs for the given form.
### humanize(atom)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L277)
Converts an attribute/form field into its humanize version.
```
iex> humanize(:username)
"Username"
iex> humanize(:created_at)
"Created at"
iex> humanize("user_id")
"User"
```
### input\_id(name, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L503)
#### Specs
```
input_id(t() | atom(), field()) :: String.t()
```
Returns an id of a corresponding form field.
The form should either be a [`Phoenix.HTML.Form`](phoenix.html.form#content) emitted by `form_for` or an atom.
### input\_id(name, field, value)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L519)
#### Specs
```
input_id(t() | atom(), field(), Phoenix.HTML.Safe.t()) :: String.t()
```
Returns an id of a corresponding form field and value attached to it.
Useful for radio buttons and inputs like multiselect checkboxes.
### input\_name(form\_or\_name, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L537)
#### Specs
```
input_name(t() | atom(), field()) :: String.t()
```
Returns a name of a corresponding form field.
The first argument should either be a [`Phoenix.HTML.Form`](phoenix.html.form#content) emitted by `form_for` or an atom.
#### Examples
```
iex> Phoenix.HTML.Form.input_name(:user, :first_name)
"user[first_name]"
```
### input\_type( form, field, mapping \\ %{ "email" => :email\_input, "password" => :password\_input, "search" => :search\_input, "url" => :url\_input } )[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L579)
Gets the input type for a given field.
If the underlying input type is a `:text_field`, a mapping could be given to further inflect the input type based solely on the field name. The default mapping is:
```
%{"url" => :url_input,
"email" => :email_input,
"search" => :search_input,
"password" => :password_input}
```
### input\_validations(form, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L552)
#### Specs
```
input_validations(t(), field()) :: Keyword.t()
```
Returns the HTML5 validations that would apply to the given field.
### input\_value(form, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L478)
#### Specs
```
input_value(t() | atom(), field()) :: term()
```
Returns a value of a corresponding form field.
The `form` should either be a [`Phoenix.HTML.Form`](phoenix.html.form#content) emitted by `form_for` or an atom.
When a form is given, it will lookup for changes and then fallback to parameters and finally fallback to the default struct/map value.
Since the function looks up parameter values too, there is no guarantee that the value will have a certain type. For example, a boolean field will be sent as "false" as a parameter, and this function will return it as is. If you need to normalize the result of `input_value`, the best option is to call `html_escape` on it and compare the resulting string.
### inputs\_for(form, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L369)
#### Specs
```
inputs_for(t(), field()) :: [t()]
```
Same as `inputs_for(form, field, [])`.
### inputs\_for(form, field, options)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L396)
#### Specs
```
inputs_for(t(), field(), Keyword.t()) :: [t()]
```
```
inputs_for(t(), field(), (t() -> Phoenix.HTML.unsafe())) :: Phoenix.HTML.safe()
```
Generate a new form builder for the given parameter in form **without** an anonymous function.
This functionality exists mostly for integration with `Phoenix.LiveView` that replaces the anonymous function for returning the generated forms instead.
Keep in mind that this function does not generate hidden inputs automatically like [`inputs_for/4`](#inputs_for/4). To generate them you need to explicit do it by yourself.
```
<%= f = form_for @changeset, Routes.user_path(@conn, :create), opts %>
Name: <%= text_input f, :name %>
<%= for friend_form <- inputs_for(f, :friends) do %>
# for generating hidden inputs.
<%= hidden_inputs_for(friend_form) %>
<%= text_input friend_form, :name %>
<% end %>
</form>
```
See [`inputs_for/4`](#inputs_for/4) for the available options.
### inputs\_for(form, field, options \\ [], fun)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L437)
#### Specs
```
inputs_for(t(), field(), Keyword.t(), (t() -> Phoenix.HTML.unsafe())) ::
Phoenix.HTML.safe()
```
Generate a new form builder for the given parameter in form.
See the module documentation for examples of using this function.
#### Options
* `:id` - the id to be used in the form, defaults to the concatenation of the given `field` to the parent form id
* `:as` - the name to be used in the form, defaults to the concatenation of the given `field` to the parent form name
* `:default` - the value to use if none is available
* `:prepend` - the values to prepend when rendering. This only applies if the field value is a list and no parameters were sent through the form.
* `:append` - the values to append when rendering. This only applies if the field value is a list and no parameters were sent through the form.
* `:skip_hidden` - skip the automatic rendering of hidden fields to allow for more tight control over the generated markup. You can access `form.hidden` to generate them manually within the supplied callback.
### label(do\_block)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1680)
Generates a label tag.
Useful when wrapping another input inside a label.
#### Examples
```
label do
radio_button :user, :choice, "Choice"
end
#=> <label>...</label>
label class: "control-label" do
radio_button :user, :choice, "Choice"
end
#=> <label class="control-label">...</label>
```
### label(opts, field)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1686)
Generates a label tag for the given field.
The form should either be a [`Phoenix.HTML.Form`](phoenix.html.form#content) emitted by `form_for` or an atom.
All given options are forwarded to the underlying tag. A default value is provided for `for` attribute but can be overridden if you pass a value to the `for` option. Text content would be inferred from `field` if not specified as either a function argument or string value in a block.
To wrap a label around an input, see [`label/1`](#label/1).
#### Examples
```
# Assuming form contains a User schema
label(form, :name, "Name")
#=> <label for="user_name">Name</label>
label(:user, :email, "Email")
#=> <label for="user_email">Email</label>
label(:user, :email)
#=> <label for="user_email">Email</label>
label(:user, :email, class: "control-label")
#=> <label for="user_email" class="control-label">Email</label>
label :user, :email do
"E-mail Address"
end
#=> <label for="user_email">E-mail Address</label>
label :user, :email, "E-mail Address", class: "control-label"
#=> <label class="control-label" for="user_email">E-mail Address</label>
label :user, :email, class: "control-label" do
"E-mail Address"
end
#=> <label class="control-label" for="user_email">E-mail Address</label>
```
### label(form, field, text\_or\_do\_block\_or\_attributes)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1740)
See [`label/2`](#label/2).
### label(form, field, text, do\_block\_or\_attributes)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1757)
See [`label/2`](#label/2).
### multiple\_select(form, field, options, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1345)
Generates a select tag with the given `options`.
Values are expected to be an Enumerable containing two-item tuples (like maps and keyword lists) or any Enumerable where the element will be used both as key and value for the generated select.
#### Examples
```
# Assuming form contains a User schema
multiple_select(form, :roles, ["Admin": 1, "Power User": 2])
#=> <select id="user_roles" name="user[roles][]">
#=> <option value="1">Admin</option>
#=> <option value="2">Power User</option>
#=> </select>
multiple_select(form, :roles, ["Admin": 1, "Power User": 2], selected: [1])
#=> <select id="user_roles" name="user[roles][]">
#=> <option value="1" selected="selected">Admin</option>
#=> <option value="2">Power User</option>
#=> </select>
```
When working with structs, associations and embeds, you will need to tell Phoenix how to extract the value out of the collection. For example, imagine `user.roles` is a list of `%Role{}` structs. You must call it as:
```
multiple_select(form, :roles, ["Admin": 1, "Power User": 2],
selected: Enum.map(@user.roles, &(&1.id))
```
The `:selected` option will mark the given IDs as selected unless the form is being resubmitted. When resubmitted, it uses the form params as values.
#### Options
* `:selected` - the default options to be marked as selected. The values on this list are ignored in case ids have been set as parameters.
All other options are forwarded to the underlying HTML tag.
### number\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L670)
Generates a number input.
See [`text_input/3`](#text_input/3) for example and docs.
### options\_for\_select(options, selected\_values)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1239)
Returns options to be used inside a select.
This is useful when building the select by hand. It expects all options and one or more select values.
#### Examples
```
options_for_select(["Admin": "admin", "User": "user"], "admin")
#=> <option value="admin" selected="selected">Admin</option>
#=> <option value="user">User</option>
```
Groups are also supported:
```
options_for_select(["Europe": ["UK", "Sweden", "France"], ...], nil)
#=> <optgroup label="Europe">
#=> <option>UK</option>
#=> <option>Sweden</option>
#=> <option>France</option>
#=> </optgroup>
```
### password\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L683)
Generates a password input.
For security reasons, the form data and parameter values are never re-used in [`password_input/3`](#password_input/3). Pass the value explicitly if you would like to set one.
See [`text_input/3`](#text_input/3) for example and docs.
### radio\_button(form, field, value, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L988)
Generates a radio button.
Invoke this function for each possible value you want to be sent to the server.
#### Examples
```
# Assuming form contains a User schema
radio_button(form, :role, "admin")
#=> <input id="user_role_admin" name="user[role]" type="radio" value="admin">
```
#### Options
All options are simply forwarded to the underlying HTML tag.
### range\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L737)
Generates a range input.
See [`text_input/3`](#text_input/3) for example and docs.
### reset(value, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L963)
Generates a reset input to reset all the form fields to their original state.
All options are forwarded to the underlying input tag.
#### Examples
```
reset "Reset"
#=> <input type="reset" value="Reset">
reset "Reset", class: "btn"
#=> <input type="reset" value="Reset" class="btn">
```
### search\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L707)
Generates a search input.
See [`text_input/3`](#text_input/3) for example and docs.
### select(form, field, options, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1182)
Generates a select tag with the given `options`.
`options` are expected to be an enumerable which will be used to generate each respective `option`. The enumerable may have:
* keyword lists - each keyword list is expected to have the keys `:key` and `:value`. Additional keys such as `:disabled` may be given to customize the option
* two-item tuples - where the first element is an atom, string or integer to be used as the option label and the second element is an atom, string or integer to be used as the option value
* atom, string or integer - which will be used as both label and value for the generated select
#### Optgroups
If `options` is map or keyword list where the first element is a string, atom or integer and the second element is a list or a map, it is assumed the key will be wrapped in an `<optgroup>` and the value will be used to generate `<options>` nested under the group.
#### Examples
```
# Assuming form contains a User schema
select(form, :age, 0..120)
#=> <select id="user_age" name="user[age]">
#=> <option value="0">0</option>
#=> ...
#=> <option value="120">120</option>
#=> </select>
select(form, :role, ["Admin": "admin", "User": "user"])
#=> <select id="user_role" name="user[role]">
#=> <option value="admin">Admin</option>
#=> <option value="user">User</option>
#=> </select>
select(form, :role, [[key: "Admin", value: "admin", disabled: true],
[key: "User", value: "user"]])
#=> <select id="user_role" name="user[role]">
#=> <option value="admin" disabled="disabled">Admin</option>
#=> <option value="user">User</option>
#=> </select>
```
You can also pass a prompt:
```
select(form, :role, ["Admin": "admin", "User": "user"], prompt: "Choose your role")
#=> <select id="user_role" name="user[role]">
#=> <option value="">Choose your role</option>
#=> <option value="admin">Admin</option>
#=> <option value="user">User</option>
#=> </select>
```
And customize the prompt as any other entry:
```
select(form, :role, ["Admin": "admin", "User": "user"], prompt: [key: "Choose your role", disabled: true])
#=> <select id="user_role" name="user[role]">
#=> <option value="" disabled="">Choose your role</option>
#=> <option value="admin">Admin</option>
#=> <option value="user">User</option>
#=> </select>
```
If you want to select an option that comes from the database, such as a manager for a given project, you may write:
```
select(form, :manager_id, Enum.map(@managers, &{&1.name, &1.id}))
#=> <select id="manager_id" name="project[manager_id]">
#=> <option value="1">Mary Jane</option>
#=> <option value="2">John Doe</option>
#=> </select>
```
Finally, if the values are a list or a map, we use the keys for grouping:
```
select(form, :country, ["Europe": ["UK", "Sweden", "France"]], ...)
#=> <select id="user_country" name="user[country]">
#=> <optgroup label="Europe">
#=> <option>UK</option>
#=> <option>Sweden</option>
#=> <option>France</option>
#=> </optgroup>
#=> ...
#=> </select>
```
#### Options
* `:prompt` - an option to include at the top of the options. It may be a string or a keyword list of attributes and the `:key`
* `:selected` - the default value to use when none was sent as parameter
Be aware that a `:multiple` option will not generate a correctly functioning multiple select element. Use [`multiple_select/4`](#multiple_select/4) instead.
All other options are forwarded to the underlying HTML tag.
### submit(block\_option)[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L913)
Generates a submit button to send the form.
#### Examples
```
submit do: "Submit"
#=> <button type="submit">Submit</button>
```
### submit(value, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L934)
Generates a submit button to send the form.
All options are forwarded to the underlying button tag. When called with a `do:` block, the button tag options come first.
#### Examples
```
submit "Submit"
#=> <button type="submit">Submit</button>
submit "Submit", class: "btn"
#=> <button class="btn" type="submit">Submit</button>
submit [class: "btn"], do: "Submit"
#=> <button class="btn" type="submit">Submit</button>
```
### telephone\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L716)
Generates a telephone input.
See [`text_input/3`](#text_input/3) for example and docs.
### text\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L616)
Generates a text input.
The form should either be a [`Phoenix.HTML.Form`](phoenix.html.form#content) emitted by `form_for` or an atom.
All given options are forwarded to the underlying input, default values are provided for id, name and value if possible.
#### Examples
```
# Assuming form contains a User schema
text_input(form, :name)
#=> <input id="user_name" name="user[name]" type="text" value="">
text_input(:user, :name)
#=> <input id="user_name" name="user[name]" type="text" value="">
```
### textarea(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L863)
Generates a textarea input.
All given options are forwarded to the underlying input, default values are provided for id, name and textarea content if possible.
#### Examples
```
# Assuming form contains a User schema
textarea(form, :description)
#=> <textarea id="user_description" name="user[description]"></textarea>
```
#### New lines
Notice the generated textarea includes a new line after the opening tag. This is because the HTML spec says new lines after tags must be ignored and all major browser implementations do that.
So in order to avoid new lines provided by the user from being ignored when the form is resubmitted, we automatically add a new line before the text area value.
### time\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L800)
Generates a time input.
Warning: this feature isn't available in all browsers. Check `http://caniuse.com/#feat=input-datetime` for further information.
#### Options
* `:precision` - Allowed values: `:minute`, `:second`, `:millisecond`. Defaults to `:minute`.
All other options are forwarded. See [`text_input/3`](#text_input/3) for example and docs.
#### Examples
```
time_input form, :time
#=> <input id="form_time" name="form[time]" type="time" value="23:00">
time_input form, :time, precision: :second
#=> <input id="form_time" name="form[time]" type="time" value="23:00:00">
time_input form, :time, precision: :millisecond
#=> <input id="form_time" name="form[time]" type="time" value="23:00:00.000">
```
### time\_select(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L1551)
Generates select tags for time.
Check [`datetime_select/3`](#datetime_select/3) for more information on options and supported values.
### url\_input(form, field, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_html/blob/v3.2.0/lib/phoenix_html/form.ex#L698)
Generates an url input.
See [`text_input/3`](#text_input/3) for example and docs.
| programming_docs |
phoenix Plug.Parsers.UnsupportedMediaTypeError exception Plug.Parsers.UnsupportedMediaTypeError exception
=================================================
Error raised when the request body cannot be parsed.
Summary
========
Functions
----------
[message(exception)](#message/1) Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
Functions
==========
### message(exception)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/parsers.ex#L20)
Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
phoenix Plug.Parsers behaviour Plug.Parsers behaviour
=======================
A plug for parsing the request body.
It invokes a list of `:parsers`, which are activated based on the request content-type. Custom parsers are also supported by defining a module that implements the behaviour defined by this module.
Once a connection goes through this plug, it will have `:body_params` set to the map of params parsed by one of the parsers listed in `:parsers` and `:params` set to the result of merging the `:body_params` and `:query_params`. In case `:query_params` have not yet been parsed, [`Plug.Conn.fetch_query_params/2`](plug.conn#fetch_query_params/2) is automatically invoked.
This plug will raise [`Plug.Parsers.UnsupportedMediaTypeError`](plug.parsers.unsupportedmediatypeerror) by default if the request cannot be parsed by any of the given types and the MIME type has not been explicitly accepted with the `:pass` option.
[`Plug.Parsers.RequestTooLargeError`](plug.parsers.requesttoolargeerror) will be raised if the request goes over the given limit. The default length is 8MB and it can be customized by passing the `:length` option to the Plug. `:read_timeout` and `:read_length`, as described by [`Plug.Conn.read_body/2`](plug.conn#read_body/2), are also supported.
Parsers may raise a [`Plug.Parsers.ParseError`](plug.parsers.parseerror) if the request has a malformed body.
This plug only parses the body if the request method is one of the following:
* `POST`
* `PUT`
* `PATCH`
* `DELETE`
For requests with a different request method, this plug will only fetch the query params.
Options
--------
* `:parsers` - a list of modules or atoms of built-in parsers to be invoked for parsing. These modules need to implement the behaviour outlined in this module.
* `:pass` - an optional list of MIME type strings that are allowed to pass through. Any mime not handled by a parser and not explicitly listed in `:pass` will `raise UnsupportedMediaTypeError`. For example:
+ `["*/*"]` - never raises
+ `["text/html", "application/*"]` - doesn't raise for those values
+ `[]` - always raises (default)
* `:query_string_length` - the maximum allowed size for query strings
* `:validate_utf8` - boolean that tells whether or not we want to validate that parsed binaries are utf8 strings.
* `:body_reader` - an optional replacement (or wrapper) for [`Plug.Conn.read_body/2`](plug.conn#read_body/2) to provide a function that gives access to the raw body before it is parsed and discarded. It is in the standard format of `{Module, :function, [args]}` (MFA) and defaults to `{Plug.Conn, :read_body, []}`. Note that this option is not used by [`Plug.Parsers.MULTIPART`](plug.parsers.multipart) which relies instead on other functions defined in [`Plug.Conn`](plug.conn).
All other options given to this Plug are forwarded to the parsers.
Examples
---------
```
plug Plug.Parsers,
parsers: [:urlencoded, :multipart],
pass: ["text/*"]
```
Any other option given to Plug.Parsers is forwarded to the underlying parsers. Therefore, you can use a JSON parser and pass the `:json_decoder` option at the root:
```
plug Plug.Parsers,
parsers: [:urlencoded, :json],
json_decoder: Jason
```
Or directly to the parser itself:
```
plug Plug.Parsers,
parsers: [:urlencoded, {:json, json_decoder: Jason}]
```
It is also possible to pass the `:json_decoder` as a `{module, function, args}` tuple, useful for passing options to the JSON decoder:
```
plug Plug.Parsers,
parsers: [:json],
json_decoder: {Jason, :decode!, [[floats: :decimals]]}
```
A common set of shared options given to Plug.Parsers is `:length`, `:read_length` and `:read_timeout`, which customizes the maximum request length you want to accept. For example, to support file uploads, you can do:
```
plug Plug.Parsers,
parsers: [:url_encoded, :multipart],
length: 20_000_000
```
However, the above will increase the maximum length of all request types. If you want to increase the limit only for multipart requests (which is typically the ones used for file uploads), you can do:
```
plug Plug.Parsers,
parsers: [
:url_encoded,
{:multipart, length: 20_000_000} # Increase to 20MB max upload
]
```
Built-in parsers
-----------------
Plug ships with the following parsers:
* [`Plug.Parsers.URLENCODED`](plug.parsers.urlencoded) - parses `application/x-www-form-urlencoded` requests (can be used as `:urlencoded` as well in the `:parsers` option)
* [`Plug.Parsers.MULTIPART`](plug.parsers.multipart) - parses `multipart/form-data` and `multipart/mixed` requests (can be used as `:multipart` as well in the `:parsers` option)
* [`Plug.Parsers.JSON`](plug.parsers.json) - parses `application/json` requests with the given `:json_decoder` (can be used as `:json` as well in the `:parsers` option)
File handling
--------------
If a file is uploaded via any of the parsers, Plug will stream the uploaded contents to a file in a temporary directory in order to avoid loading the whole file into memory. For such, the `:plug` application needs to be started in order for file uploads to work. More details on how the uploaded file is handled can be found in the documentation for [`Plug.Upload`](plug.upload).
When a file is uploaded, the request parameter that identifies that file will be a [`Plug.Upload`](plug.upload) struct with information about the uploaded file (e.g. filename and content type) and about where the file is stored.
The temporary directory where files are streamed to can be customized by setting the `PLUG_TMPDIR` environment variable on the host system. If `PLUG_TMPDIR` isn't set, Plug will look at some environment variables which usually hold the value of the system's temporary directory (like `TMPDIR` or `TMP`). If no value is found in any of those variables, `/tmp` is used as a default.
Custom body reader
-------------------
Sometimes you may want to customize how a parser reads the body from the connection. For example, you may want to cache the body to perform verification later, such as HTTP Signature Verification. This can be achieved with a custom body reader that would read the body and store it in the connection, such as:
```
defmodule CacheBodyReader do
def read_body(conn, opts) do
{:ok, body, conn} = Plug.Conn.read_body(conn, opts)
conn = update_in(conn.assigns[:raw_body], &[body | (&1 || [])])
{:ok, body, conn}
end
end
```
which could then be set as:
```
plug Plug.Parsers,
parsers: [:urlencoded, :json],
pass: ["text/*"],
body_reader: {CacheBodyReader, :read_body, []},
json_decoder: Jason
```
Summary
========
Callbacks
----------
[init(opts)](#c:init/1) [parse( conn, type, subtype, params, opts )](#c:parse/5) Attempts to parse the connection's request body given the content-type type, subtype, and its parameters.
Callbacks
==========
### init(opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/parsers.ex#L213)
```
@callback init(opts :: Keyword.t()) :: Plug.opts()
```
### parse( conn, type, subtype, params, opts )[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/parsers.ex#L243)
```
@callback parse(
conn :: Plug.Conn.t(),
type :: binary(),
subtype :: binary(),
params :: Plug.Conn.Utils.params(),
opts :: Plug.opts()
) ::
{:ok, Plug.Conn.params(), Plug.Conn.t()}
| {:error, :too_large, Plug.Conn.t()}
| {:next, Plug.Conn.t()}
```
Attempts to parse the connection's request body given the content-type type, subtype, and its parameters.
The arguments are:
* the [`Plug.Conn`](plug.conn) connection
* `type`, the content-type type (e.g., `"x-sample"` for the `"x-sample/json"` content-type)
* `subtype`, the content-type subtype (e.g., `"json"` for the `"x-sample/json"` content-type)
* `params`, the content-type parameters (e.g., `%{"foo" => "bar"}` for the `"text/plain; foo=bar"` content-type)
This function should return:
* `{:ok, body_params, conn}` if the parser is able to handle the given content-type; `body_params` should be a map
* `{:next, conn}` if the next parser should be invoked
* `{:error, :too_large, conn}` if the request goes over the given limit
phoenix Plug.Builder Plug.Builder
=============
Conveniences for building plugs.
You can use this module to build a plug pipeline:
```
defmodule MyApp do
use Plug.Builder
plug Plug.Logger
plug :hello, upper: true
# A function from another module can be plugged too, provided it's
# imported into the current module first.
import AnotherModule, only: [interesting_plug: 2]
plug :interesting_plug
def hello(conn, opts) do
body = if opts[:upper], do: "WORLD", else: "world"
send_resp(conn, 200, body)
end
end
```
Multiple plugs can be defined with the [`plug/2`](#plug/2) macro, forming a pipeline. The plugs in the pipeline will be executed in the order they've been added through the [`plug/2`](#plug/2) macro. In the example above, [`Plug.Logger`](plug.logger) will be called first and then the `:hello` function plug will be called on the resulting connection.
[`Plug.Builder`](plug.builder#content) also imports the [`Plug.Conn`](plug.conn) module, making functions like `send_resp/3` available.
Options
--------
When used, the following options are accepted by [`Plug.Builder`](plug.builder#content):
* `:init_mode` - the environment to initialize the plug's options, one of `:compile` or `:runtime`. Defaults `:compile`.
* `:log_on_halt` - accepts the level to log whenever the request is halted
* `:copy_opts_to_assign` - an `atom` representing an assign. When supplied, it will copy the options given to the Plug initialization to the given connection assign
Plug behaviour
---------------
Internally, [`Plug.Builder`](plug.builder#content) implements the [`Plug`](plug) behaviour, which means both the `init/1` and `call/2` functions are defined.
By implementing the Plug API, [`Plug.Builder`](plug.builder#content) guarantees this module is a plug and can be handed to a web server or used as part of another pipeline.
Overriding the default Plug API functions
------------------------------------------
Both the `init/1` and `call/2` functions defined by [`Plug.Builder`](plug.builder#content) can be manually overridden. For example, the `init/1` function provided by [`Plug.Builder`](plug.builder#content) returns the options that it receives as an argument, but its behaviour can be customized:
```
defmodule PlugWithCustomOptions do
use Plug.Builder
plug Plug.Logger
def init(opts) do
opts
end
end
```
The `call/2` function that [`Plug.Builder`](plug.builder#content) provides is used internally to execute all the plugs listed using the `plug` macro, so overriding the `call/2` function generally implies using `super` in order to still call the plug chain:
```
defmodule PlugWithCustomCall do
use Plug.Builder
plug Plug.Logger
plug Plug.Head
def call(conn, opts) do
conn
|> super(opts) # calls Plug.Logger and Plug.Head
|> assign(:called_all_plugs, true)
end
end
```
Halting a plug pipeline
------------------------
A plug pipeline can be halted with [`Plug.Conn.halt/1`](plug.conn#halt/1). The builder will prevent further plugs downstream from being invoked and return the current connection. In the following example, the [`Plug.Logger`](plug.logger) plug never gets called:
```
defmodule PlugUsingHalt do
use Plug.Builder
plug :stopper
plug Plug.Logger
def stopper(conn, _opts) do
halt(conn)
end
end
```
Summary
========
Types
------
[plug()](#t:plug/0) Functions
----------
[builder\_opts()](#builder_opts/0) deprecated Using [`builder_opts/0`](#builder_opts/0) is deprecated.
[compile(env, pipeline, builder\_opts)](#compile/3) Compiles a plug pipeline.
[plug(plug, opts \\ [])](#plug/2) A macro that stores a new plug. `opts` will be passed unchanged to the new plug.
Types
======
### plug()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/builder.ex#L106)
```
@type plug() :: module() | atom()
```
Functions
==========
### builder\_opts()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/builder.ex#L241)
This macro is deprecated. Pass :copy\_opts\_to\_assign on "use Plug.Builder". Using [`builder_opts/0`](#builder_opts/0) is deprecated.
Instead use `:copy_opts_to_assign` on `use Plug.Builder`.
### compile(env, pipeline, builder\_opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/builder.ex#L286)
```
@spec compile(Macro.Env.t(), [{plug(), Plug.opts(), Macro.t()}], Keyword.t()) ::
{Macro.t(), Macro.t()}
```
Compiles a plug pipeline.
Each element of the plug pipeline (according to the type signature of this function) has the form:
```
{plug_name, options, guards}
```
Note that this function expects a reversed pipeline (with the last plug that has to be called coming first in the pipeline).
The function returns a tuple with the first element being a quoted reference to the connection and the second element being the compiled quoted pipeline.
#### Examples
```
Plug.Builder.compile(env, [
{Plug.Logger, [], true}, # no guards, as added by the Plug.Builder.plug/2 macro
{Plug.Head, [], quote(do: a when is_binary(a))}
], [])
```
### plug(plug, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/builder.ex#L210)
A macro that stores a new plug. `opts` will be passed unchanged to the new plug.
This macro doesn't add any guards when adding the new plug to the pipeline; for more information about adding plugs with guards see [`compile/3`](#compile/3).
#### Examples
```
plug Plug.Logger # plug module
plug :foo, some_options: true # plug function
```
phoenix Plug.Logger Plug.Logger
============
A plug for logging basic request information in the format:
```
GET /index.html
Sent 200 in 572ms
```
To use it, just plug it into the desired module.
```
plug Plug.Logger, log: :debug
```
Options
--------
* `:log` - The log level at which this plug should log its request info. Default is `:info`. The [list of supported levels](https://hexdocs.pm/logger/Logger.html#module-levels) is available in the [`Logger`](https://hexdocs.pm/logger/Logger.html) documentation.
phoenix Plug.Session.COOKIE Plug.Session.COOKIE
====================
Stores the session in a cookie.
This cookie store is based on [`Plug.Crypto.MessageVerifier`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.MessageVerifier.html) and [`Plug.Crypto.MessageEncryptor`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.MessageEncryptor.html) which encrypts and signs each cookie to ensure they can't be read nor tampered with.
Since this store uses crypto features, it requires you to set the `:secret_key_base` field in your connection. This can be easily achieved with a plug:
```
plug :put_secret_key_base
def put_secret_key_base(conn, _) do
put_in conn.secret_key_base, "-- LONG STRING WITH AT LEAST 64 BYTES --"
end
```
Options
--------
* `:secret_key_base` - the secret key base to built the cookie signing/encryption on top of. If one is given on initialization, the cookie store can precompute all relevant values at compilation time. Otherwise, the value is taken from `conn.secret_key_base` and cached.
* `:encryption_salt` - a salt used with `conn.secret_key_base` to generate a key for encrypting/decrypting a cookie, can be either a binary or an MFA returning a binary;
* `:signing_salt` - a salt used with `conn.secret_key_base` to generate a key for signing/verifying a cookie, can be either a binary or an MFA returning a binary;
* `:key_iterations` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 1000;
* `:key_length` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to 32;
* `:key_digest` - option passed to [`Plug.Crypto.KeyGenerator`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.KeyGenerator.html) when generating the encryption and signing keys. Defaults to `:sha256`;
* `:serializer` - cookie serializer module that defines `encode/1` and `decode/1` returning an `{:ok, value}` tuple. Defaults to `:external_term_format`.
* `:log` - Log level to use when the cookie cannot be decoded. Defaults to `:debug`, can be set to false to disable it.
* `:rotating_options` - additional list of options to use when decrypting and verifying the cookie. These options are used only when the cookie could not be decoded using primary options and are fetched on init so they cannot be changed in runtime. Defaults to `[]`.
Examples
---------
```
plug Plug.Session, store: :cookie,
key: "_my_app_session",
encryption_salt: "cookie store encryption salt",
signing_salt: "cookie store signing salt",
key_length: 64,
log: :debug
```
phoenix Plug.Session.Store behaviour Plug.Session.Store behaviour
=============================
Specification for session stores.
Summary
========
Types
------
[cookie()](#t:cookie/0) The cookie value that will be sent in cookie headers. This value should be base64 encoded to avoid security issues.
[session()](#t:session/0) The session contents, the final data to be stored after it has been built with [`Plug.Conn.put_session/3`](plug.conn#put_session/3) and the other session manipulating functions.
[sid()](#t:sid/0) The internal reference to the session in the store.
Callbacks
----------
[delete(conn, sid, opts)](#c:delete/3) Removes the session associated with given session id from the store.
[get(conn, cookie, opts)](#c:get/3) Parses the given cookie.
[init(opts)](#c:init/1) Initializes the store.
[put(conn, sid, any, opts)](#c:put/4) Stores the session associated with given session id.
Functions
----------
[get(store)](#get/1) Gets the store name from an atom or a module.
Types
======
### cookie()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L32)
```
@type cookie() :: binary()
```
The cookie value that will be sent in cookie headers. This value should be base64 encoded to avoid security issues.
### session()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L38)
```
@type session() :: map()
```
The session contents, the final data to be stored after it has been built with [`Plug.Conn.put_session/3`](plug.conn#put_session/3) and the other session manipulating functions.
### sid()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L26)
```
@type sid() :: term() | nil
```
The internal reference to the session in the store.
Callbacks
==========
### delete(conn, sid, opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L70)
```
@callback delete(conn :: Plug.Conn.t(), sid(), opts :: Plug.opts()) :: :ok
```
Removes the session associated with given session id from the store.
### get(conn, cookie, opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L57)
```
@callback get(conn :: Plug.Conn.t(), cookie(), opts :: Plug.opts()) :: {sid(), session()}
```
Parses the given cookie.
Returns a session id and the session contents. The session id is any value that can be used to identify the session by the store.
The session id may be nil in case the cookie does not identify any value in the store. The session contents must be a map.
### init(opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L46)
```
@callback init(opts :: Plug.opts()) :: Plug.opts()
```
Initializes the store.
The options returned from this function will be given to [`get/3`](#c:get/3), [`put/4`](#c:put/4) and [`delete/3`](#c:delete/3).
### put(conn, sid, any, opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L65)
```
@callback put(conn :: Plug.Conn.t(), sid(), any(), opts :: Plug.opts()) :: cookie()
```
Stores the session associated with given session id.
If `nil` is given as id, a new session id should be generated and returned.
Functions
==========
### get(store)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/session/store.ex#L16)
Gets the store name from an atom or a module.
```
iex> Plug.Session.Store.get(CustomStore)
CustomStore
iex> Plug.Session.Store.get(:cookie)
Plug.Session.COOKIE
```
| programming_docs |
phoenix Plug.Conn.Query Plug.Conn.Query
================
Conveniences for decoding and encoding url encoded queries.
Plug allows a developer to build query strings that map to Elixir structures in order to make manipulation of such structures easier on the server side. Here are some examples:
```
iex> decode("foo=bar")["foo"]
"bar"
```
If a value is given more than once, the last value takes precedence:
```
iex> decode("foo=bar&foo=baz")["foo"]
"baz"
```
Nested structures can be created via `[key]`:
```
iex> decode("foo[bar]=baz")["foo"]["bar"]
"baz"
```
Lists are created with `[]`:
```
iex> decode("foo[]=bar&foo[]=baz")["foo"]
["bar", "baz"]
```
Keys without values are treated as empty strings, according to <https://url.spec.whatwg.org/#application/x-www-form-urlencoded>:
```
iex> decode("foo")["foo"]
""
```
Maps can be encoded:
```
iex> encode(%{foo: "bar", baz: "bat"})
"baz=bat&foo=bar"
```
Encoding keyword lists preserves the order of the fields:
```
iex> encode([foo: "bar", baz: "bat"])
"foo=bar&baz=bat"
```
When encoding keyword lists with duplicate keys, the key that comes first takes precedence:
```
iex> encode([foo: "bar", foo: "bat"])
"foo=bar"
```
Encoding named lists:
```
iex> encode(%{foo: ["bar", "baz"]})
"foo[]=bar&foo[]=baz"
```
Encoding nested structures:
```
iex> encode(%{foo: %{bar: "baz"}})
"foo[bar]=baz"
```
Summary
========
Functions
----------
[decode(query, initial \\ %{}, invalid\_exception \\ Plug.Conn.InvalidQueryError, validate\_utf8 \\ true)](#decode/4) Decodes the given binary.
[decode\_pair(arg, acc)](#decode_pair/2) Decodes the given tuple and stores it in the accumulator.
[encode(kv, encoder \\ &to\_string/1)](#encode/2) Encodes the given map or list of tuples.
Functions
==========
### decode(query, initial \\ %{}, invalid\_exception \\ Plug.Conn.InvalidQueryError, validate\_utf8 \\ true)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/query.ex#L67)
Decodes the given binary.
The binary is assumed to be encoded in "x-www-form-urlencoded" format. The format is decoded and then validated for proper UTF-8 encoding.
### decode\_pair(arg, acc)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/query.ex#L133)
Decodes the given tuple and stores it in the accumulator.
It parses the key and stores the value into the current accumulator. The keys and values are not assumed to be encoded in "x-www-form-urlencoded".
Parameter lists are added to the accumulator in reverse order, so be sure to pass the parameters in reverse order.
### encode(kv, encoder \\ &to\_string/1)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/query.ex#L203)
Encodes the given map or list of tuples.
phoenix Plug.Conn.Adapter behaviour Plug.Conn.Adapter behaviour
============================
Specification of the connection adapter API implemented by webservers.
Summary
========
Types
------
[http\_protocol()](#t:http_protocol/0) [payload()](#t:payload/0) [peer\_data()](#t:peer_data/0) Callbacks
----------
[chunk(payload, body)](#c:chunk/2) Sends a chunk in the chunked response.
[get\_http\_protocol(payload)](#c:get_http_protocol/1) Returns the HTTP protocol and its version.
[get\_peer\_data(payload)](#c:get_peer_data/1) Returns peer information such as the address, port and ssl cert.
[inform(payload, status, headers)](#c:inform/3) Send an informational response to the client.
[push(payload, path, headers)](#c:push/3) Push a resource to the client.
[read\_req\_body(payload, options)](#c:read_req_body/2) Reads the request body.
[send\_chunked(payload, status, headers)](#c:send_chunked/3) Sends the given status, headers as the beginning of a chunked response to the client.
[send\_file( payload, status, headers, file, offset, length )](#c:send_file/6) Sends the given status, headers and file as a response back to the client.
[send\_resp( payload, status, headers, body )](#c:send_resp/4) Sends the given status, headers and body as a response back to the client.
Functions
----------
[conn(adapter, method, uri, remote\_ip, req\_headers)](#conn/5) Function used by adapters to create a new connection.
Types
======
### http\_protocol()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L7)
```
@type http_protocol() :: :"HTTP/1" | :"HTTP/1.1" | :"HTTP/2" | atom()
```
### payload()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L8)
```
@type payload() :: term()
```
### peer\_data()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L9)
```
@type peer_data() :: %{
address: :inet.ip_address(),
port: :inet.port_number(),
ssl_cert: binary() | nil
}
```
Callbacks
==========
### chunk(payload, body)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L105)
```
@callback chunk(payload(), body :: Plug.Conn.body()) ::
:ok | {:ok, sent_body :: binary(), payload()} | {:error, term()}
```
Sends a chunk in the chunked response.
If the request has method `"HEAD"`, the adapter should not send the response to the client.
Webservers are advised to return `:ok` and not modify any further state for each chunk. However, the test implementation returns the actual body and payload so it can be used during testing.
### get\_http\_protocol(payload)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L144)
```
@callback get_http_protocol(payload()) :: http_protocol()
```
Returns the HTTP protocol and its version.
### get\_peer\_data(payload)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L139)
```
@callback get_peer_data(payload()) :: peer_data()
```
Returns peer information such as the address, port and ssl cert.
### inform(payload, status, headers)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L133)
```
@callback inform(payload(), status :: Plug.Conn.status(), headers :: Keyword.t()) ::
:ok | {:error, term()}
```
Send an informational response to the client.
If the adapter does not support inform, then `{:error, :not_supported}` should be returned.
### push(payload, path, headers)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L125)
```
@callback push(payload(), path :: String.t(), headers :: Keyword.t()) ::
:ok | {:error, term()}
```
Push a resource to the client.
If the adapter does not support server push then `{:error, :not_supported}` should be returned.
### read\_req\_body(payload, options)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L114)
```
@callback read_req_body(payload(), options :: Keyword.t()) ::
{:ok, data :: binary(), payload()}
| {:more, data :: binary(), payload()}
| {:error, term()}
```
Reads the request body.
Read the docs in [`Plug.Conn.read_body/2`](plug.conn#read_body/2) for the supported options and expected behaviour.
### send\_chunked(payload, status, headers)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L91)
```
@callback send_chunked(
payload(),
status :: Plug.Conn.status(),
headers :: Plug.Conn.headers()
) ::
{:ok, sent_body :: binary() | nil, payload()}
```
Sends the given status, headers as the beginning of a chunked response to the client.
Webservers are advised to return `nil` as the sent\_body, as the body can no longer be manipulated. However, the test implementation returns the actual body so it can be used during testing.
### send\_file( payload, status, headers, file, offset, length )[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L80)
```
@callback send_file(
payload(),
status :: Plug.Conn.status(),
headers :: Plug.Conn.headers(),
file :: binary(),
offset :: integer(),
length :: integer() | :all
) :: {:ok, sent_body :: binary() | nil, payload()}
```
Sends the given status, headers and file as a response back to the client.
If the request has method `"HEAD"`, the adapter should not send the response to the client.
Webservers are advised to return `nil` as the sent\_body, as the body can no longer be manipulated. However, the test implementation returns the actual body so it can be used during testing.
### send\_resp( payload, status, headers, body )[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L58)
```
@callback send_resp(
payload(),
status :: Plug.Conn.status(),
headers :: Plug.Conn.headers(),
body :: Plug.Conn.body()
) :: {:ok, sent_body :: binary() | nil, payload()}
```
Sends the given status, headers and body as a response back to the client.
If the request has method `"HEAD"`, the adapter should not send the response to the client.
Webservers are advised to return `nil` as the sent\_body, as the body can no longer be manipulated. However, the test implementation returns the actual body so it can be used during testing.
Functions
==========
### conn(adapter, method, uri, remote\_ip, req\_headers)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/adapter.ex#L18)
Function used by adapters to create a new connection.
phoenix Plug.Conn.WrapperError exception Plug.Conn.WrapperError exception
=================================
Wraps the connection in an error which is meant to be handled upper in the stack.
Used by both [`Plug.Debugger`](plug.debugger) and [`Plug.ErrorHandler`](plug.errorhandler).
Summary
========
Functions
----------
[message(map)](#message/1) Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
[reraise(reason)](#reraise/1) Reraises an error or a wrapped one.
[reraise(conn, kind, reason)](#reraise/3) deprecated [reraise(conn, kind, reason, stack)](#reraise/4) Functions
==========
### message(map)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/wrapper_error.ex#L10)
Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
### reraise(reason)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/wrapper_error.ex#L17)
Reraises an error or a wrapped one.
### reraise(conn, kind, reason)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/wrapper_error.ex#L22)
This function is deprecated. Use reraise/1 or reraise/4 instead. ### reraise(conn, kind, reason, stack)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/wrapper_error.ex#L29)
phoenix Plug.RewriteOn Plug.RewriteOn
===============
A plug to rewrite the request's host/port/protocol from `x-forwarded-*` headers.
If your Plug application is behind a proxy that handles HTTPS, you may need to tell Plug to parse the proper protocol from the `x-forwarded-*` header.
```
plug Plug.RewriteOn, [:x_forwarded_host, :x_forwarded_port, :x_forwarded_proto]
```
The supported values are:
* `:x_forwarded_host` - to override the host based on on the "x-forwarded-host" header
* `:x_forwarded_port` - to override the port based on on the "x-forwarded-port" header
* `:x_forwarded_proto` - to override the protocol based on on the "x-forwarded-proto" header
Since rewriting the scheme based on `x-forwarded-*` headers can open up security vulnerabilities, only use this plug if:
* your app is behind a proxy
* your proxy strips the given `x-forwarded-*` headers from all incoming requests
* your proxy sets the `x-forwarded-*` headers and sends it to Plug
phoenix Plug.Conn.NotSentError exception Plug.Conn.NotSentError exception
=================================
Error raised when no response is sent in a request
phoenix Plug.MethodOverride Plug.MethodOverride
====================
This plug overrides the request's `POST` method with the method defined in the `_method` request parameter.
The `POST` method can be overridden only by these HTTP methods:
* `PUT`
* `PATCH`
* `DELETE`
This plug expects the body parameters to be already parsed and fetched. Those can be fetched with [`Plug.Parsers`](plug.parsers).
This plug doesn't accept any options.
Examples
---------
```
Plug.MethodOverride.call(conn, [])
```
phoenix Plug.BadRequestError exception Plug.BadRequestError exception
===============================
The request will not be processed due to a client error.
phoenix Plug.BasicAuth Plug.BasicAuth
===============
Functionality for providing Basic HTTP authentication.
It is recommended to only use this module in production if SSL is enabled and enforced. See [`Plug.SSL`](plug.ssl) for more information.
Compile-time usage
-------------------
If you have a single username and password, you can use the [`basic_auth/2`](#basic_auth/2) plug:
```
import Plug.BasicAuth
plug :basic_auth, username: "hello", password: "secret"
```
Or if you would rather put those in a config file:
```
# lib/your_app.ex
import Plug.BasicAuth
plug :basic_auth, Application.compile_env(:my_app, :basic_auth)
# config/config.exs
config :my_app, :basic_auth, username: "hello", password: "secret"
```
Once the user first accesses the page, the request will be denied with reason 401 and the request is halted. The browser will then prompt the user for username and password. If they match, then the request succeeds.
Both approaches shown above rely on static configuration. Let's see alternatives.
Runtime-time usage
-------------------
As any other Plug, we can use the `basic_auth` at runtime by simply wrapping it in a function:
```
plug :auth
defp auth(conn, opts) do
username = System.fetch_env!("AUTH_USERNAME")
password = System.fetch_env!("AUTH_PASSWORD")
Plug.BasicAuth.basic_auth(conn, username: username, password: password)
end
```
This approach is useful when both username and password are specified upfront and available at runtime. However, you may also want to compute a different password for each different user. In those cases, we can use the low-level API.
Low-level usage
----------------
If you want to provide your own authentication logic on top of Basic HTTP auth, you can use the low-level functions. As an example, we define `:auth` plug that extracts username and password from the request headers, compares them against the database, and either assigns a `:current_user` on success or responds with an error on failure.
```
plug :auth
defp auth(conn, _opts) do
with {user, pass} <- Plug.BasicAuth.parse_basic_auth(conn),
%User{} = user <- MyApp.Accounts.find_by_username_and_password(user, pass) do
assign(conn, :current_user, user)
else
_ -> conn |> Plug.BasicAuth.request_basic_auth() |> halt()
end
end
```
Keep in mind that:
* The supplied `user` and `pass` may be empty strings;
* If you are comparing the username and password with existing strings, do not use [`==/2`](https://hexdocs.pm/elixir/Kernel.html#==/2). Use [`Plug.Crypto.secure_compare/2`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.html#secure_compare/2) instead.
Summary
========
Functions
----------
[basic\_auth(conn, options \\ [])](#basic_auth/2) Higher level usage of Basic HTTP auth.
[encode\_basic\_auth(user, pass)](#encode_basic_auth/2) Encodes a basic authentication header.
[parse\_basic\_auth(conn)](#parse_basic_auth/1) Parses the request username and password from Basic HTTP auth.
[request\_basic\_auth(conn, options \\ [])](#request_basic_auth/2) Requests basic authentication from the client.
Functions
==========
### basic\_auth(conn, options \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/basic_auth.ex#L95)
Higher level usage of Basic HTTP auth.
See the module docs for examples.
#### Options
* `:username` - the expected username
* `:password` - the expected password
* `:realm` - the authentication realm. The value is not fully sanitized, so do not accept user input as the realm and use strings with only alphanumeric characters and space
### encode\_basic\_auth(user, pass)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/basic_auth.ex#L137)
Encodes a basic authentication header.
This can be used during tests:
```
put_req_header(conn, "authorization", encode_basic_auth("hello", "world"))
```
### parse\_basic\_auth(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/basic_auth.ex#L119)
Parses the request username and password from Basic HTTP auth.
It returns either `{user, pass}` or `:error`. Note the username and password may be empty strings. When comparing the username and password with the expected values, be sure to use [`Plug.Crypto.secure_compare/2`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.html#secure_compare/2).
See the module docs for examples.
### request\_basic\_auth(conn, options \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/basic_auth.ex#L154)
Requests basic authentication from the client.
It sets the response to status 401 with "Unauthorized" as body. The response is not sent though (nor the connection is halted), allowing developers to further customize it.
#### Options
* `:realm` - the authentication realm. The value is not fully sanitized, so do not accept user input as the realm and use strings with only alphanumeric characters and space
phoenix Plug.Conn.AlreadySentError exception Plug.Conn.AlreadySentError exception
=====================================
Error raised when trying to modify or send an already sent response
phoenix Plug.SSL Plug.SSL
=========
A plug to force SSL connections and enable HSTS.
If the scheme of a request is `https`, it'll add a `strict-transport-security` header to enable HTTP Strict Transport Security by default.
Otherwise, the request will be redirected to a corresponding location with the `https` scheme by setting the `location` header of the response. The status code will be 301 if the method of `conn` is `GET` or `HEAD`, or 307 in other situations.
Besides being a Plug, this module also provides conveniences for configuring SSL. See [`configure/1`](#configure/1).
x-forwarded-\*
---------------
If your Plug application is behind a proxy that handles HTTPS, you may need to tell Plug to parse the proper protocol from the `x-forwarded-*` header. This can be done using the `:rewrite_on` option:
```
plug Plug.SSL, rewrite_on: [:x_forwarded_host, :x_forwarded_port, :x_forwarded_proto]
```
For further details refer to [`Plug.RewriteOn`](plug.rewriteon).
Plug Options
-------------
* `:rewrite_on` - rewrites the given connection information based on the given headers
* `:hsts` - a boolean on enabling HSTS or not, defaults to `true`
* `:expires` - seconds to expires for HSTS, defaults to `31_536_000` (1 year)
* `:preload` - a boolean to request inclusion on the HSTS preload list (for full set of required flags, see: [Chromium HSTS submission site](https://hstspreload.org)), defaults to `false`
* `:subdomains` - a boolean on including subdomains or not in HSTS, defaults to `false`
* `:exclude` - exclude the given hosts from redirecting to the `https` scheme. Defaults to `["localhost"]`. It may be set to a list of binaries or a tuple [`{module, function, args}`](#module-excluded-hosts-tuple).
* `:host` - a new host to redirect to if the request's scheme is `http`, defaults to `conn.host`. It may be set to a binary or a tuple `{module, function, args}` that will be invoked on demand
* `:log` - The log level at which this plug should log its request info. Default is `:info`. Can be `false` to disable logging.
Port
-----
It is not possible to directly configure the port in [`Plug.SSL`](plug.ssl#content) because HSTS expects the port to be 443 for SSL. If you are not using HSTS and want to redirect to HTTPS on another port, you can sneak it alongside the host, for example: `host: "example.com:443"`.
Excluded hosts tuple
---------------------
Tuple `{module, function, args}` can be passed to be invoked each time the plug is checking whether to redirect host. Provided function needs to receive at least one argument (`host`).
For example, you may define it as:
```
plug Plug.SSL,
rewrite_on: [:x_forwarded_proto],
exclude: {__MODULE__, :excluded_host?, []}
```
where:
```
def excluded_host?(host) do
# Custom logic
end
```
Summary
========
Functions
----------
[configure(options)](#configure/1) Configures and validates the options given to the `:ssl` application.
Functions
==========
### configure(options)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/ssl.ex#L165)
```
@spec configure(Keyword.t()) :: {:ok, Keyword.t()} | {:error, String.t()}
```
Configures and validates the options given to the `:ssl` application.
This function is often called internally by adapters, such as Cowboy, to validate and set reasonable defaults for SSL handling. Therefore Plug users are not expected to invoke it directly, rather you pass the relevant SSL options to your adapter which then invokes this.
#### Options
This function accepts all options defined [in Erlang/OTP `:ssl` documentation](http://erlang.org/doc/man/ssl.html).
Besides the options from `:ssl`, this function adds on extra option:
* `:cipher_suite` - it may be `:strong` or `:compatible`, as outlined in the following section
Furthermore, it sets the following defaults:
* `secure_renegotiate: true` - to avoid certain types of man-in-the-middle attacks
* `reuse_sessions: true` - for improved handshake performance of recurring connections
For a complete guide on HTTPS and best pratices, see [our Plug HTTPS Guide](https).
#### Cipher Suites
To simplify configuration of TLS defaults, this function provides two preconfigured options: `cipher_suite: :strong` and `cipher_suite: :compatible`. The Ciphers chosen and related configuration come from the [OWASP Cipher String Cheat Sheet](https://www.owasp.org/index.php/TLS_Cipher_String_Cheat_Sheet)
We've made two modifications to the suggested config from the OWASP recommendations. First we include ECDSA certificates which are excluded from their configuration. Second we have changed the order of the ciphers to deprioritize DHE because of performance implications noted within the OWASP post itself. As the article notes "...the TLS handshake with DHE hinders the CPU about 2.4 times more than ECDHE".
The **Strong** cipher suite only supports tlsv1.2. Ciphers were based on the OWASP Group A+ and includes support for RSA or ECDSA certificates. The intention of this configuration is to provide as secure as possible defaults knowing that it will not be fully compatible with older browsers and operating systems.
The **Compatible** cipher suite supports tlsv1, tlsv1.1 and tlsv1.2. Ciphers were based on the OWASP Group B and includes support for RSA or ECDSA certificates. The intention of this configuration is to provide as secure as possible defaults that still maintain support for older browsers and Android versions 4.3 and earlier
For both suites we've specified certificate curves secp256r1, ecp384r1 and secp521r1. Since OWASP doesn't prescribe curves we've based the selection on [Mozilla's recommendations](https://wiki.mozilla.org/Security/Server_Side_TLS#Cipher_names_correspondence_table)
**The cipher suites were last updated on 2018-JUN-14.**
| programming_docs |
phoenix Plug.Conn Plug.Conn
==========
The Plug connection.
This module defines a struct and the main functions for working with requests and responses in an HTTP connection.
Note request headers are normalized to lowercase and response headers are expected to have lowercase keys.
Request fields
---------------
These fields contain request information:
* `host` - the requested host as a binary, example: `"www.example.com"`
* `method` - the request method as a binary, example: `"GET"`
* `path_info` - the path split into segments, example: `["hello", "world"]`
* `script_name` - the initial portion of the URL's path that corresponds to the application routing, as segments, example: `["sub","app"]`
* `request_path` - the requested path, example: `/trailing/and//double//slashes/`
* `port` - the requested port as an integer, example: `80`
* `remote_ip` - the IP of the client, example: `{151, 236, 219, 228}`. This field is meant to be overwritten by plugs that understand e.g. the `X-Forwarded-For` header or HAProxy's PROXY protocol. It defaults to peer's IP
* `req_headers` - the request headers as a list, example: `[{"content-type", "text/plain"}]`. Note all headers will be downcased
* `scheme` - the request scheme as an atom, example: `:http`
* `query_string` - the request query string as a binary, example: `"foo=bar"`
Fetchable fields
-----------------
The request information in these fields is not populated until it is fetched using the associated `fetch_` function. For example, the `cookies` field uses [`fetch_cookies/2`](#fetch_cookies/2).
If you access these fields before fetching them, they will be returned as [`Plug.Conn.Unfetched`](plug.conn.unfetched) structs.
* `cookies`- the request cookies with the response cookies
* `body_params` - the request body params, populated through a [`Plug.Parsers`](plug.parsers) parser.
* `query_params` - the request query params, populated through [`fetch_query_params/2`](#fetch_query_params/2)
* `path_params` - the request path params, populated by routers such as [`Plug.Router`](plug.router)
* `params` - the request params, the result of merging the `:path_params` on top of `:body_params` on top of `:query_params`
* `req_cookies` - the request cookies (without the response ones)
Response fields
----------------
These fields contain response information:
* `resp_body` - the response body, by default is an empty string. It is set to nil after the response is sent, except for test connections. The response charset used defaults to "utf-8".
* `resp_cookies` - the response cookies with their name and options
* `resp_headers` - the response headers as a list of tuples, by default `cache-control` is set to `"max-age=0, private, must-revalidate"`. Note, response headers are expected to have lowercase keys.
* `status` - the response status
Connection fields
------------------
* `assigns` - shared user data as a map
* `owner` - the Elixir process that owns the connection
* `halted` - the boolean status on whether the pipeline was halted
* `secret_key_base` - a secret key used to verify and encrypt cookies. the field must be set manually whenever one of those features are used. This data must be kept in the connection and never used directly, always use [`Plug.Crypto.KeyGenerator.generate/3`](https://hexdocs.pm/plug_crypto/1.2.1/Plug.Crypto.KeyGenerator.html#generate/3) to derive keys from it
* `state` - the connection state
The connection state is used to track the connection lifecycle. It starts as `:unset` but is changed to `:set` (via [`resp/3`](#resp/3)) or `:set_chunked` (used only for `before_send` callbacks by [`send_chunked/2`](#send_chunked/2)) or `:file` (when invoked via [`send_file/3`](#send_file/3)). Its final result is `:sent`, `:file` or `:chunked` depending on the response model.
Private fields
---------------
These fields are reserved for libraries/framework usage.
* `adapter` - holds the adapter information in a tuple
* `private` - shared library data as a map
Custom status codes
--------------------
Plug allows status codes to be overridden or added in order to allow new codes not directly specified by Plug or its adapters. Adding or overriding a status code is done through the Mix configuration of the `:plug` application. For example, to override the existing 404 reason phrase for the 404 status code ("Not Found" by default) and add a new 998 status code, the following config can be specified:
```
config :plug, :statuses, %{
404 => "Actually This Was Found",
998 => "Not An RFC Status Code"
}
```
As this configuration is Plug specific, Plug will need to be recompiled for the changes to take place: this will not happen automatically as dependencies are not automatically recompiled when their configuration changes. To recompile Plug:
```
mix deps.clean --build plug
```
The atoms that can be used in place of the status code in many functions are inflected from the reason phrase of the status code. With the above configuration, the following will all work:
```
put_status(conn, :not_found) # 404
put_status(conn, :actually_this_was_found) # 404
put_status(conn, :not_an_rfc_status_code) # 998
```
Even though 404 has been overridden, the `:not_found` atom can still be used to set the status to 404 as well as the new atom `:actually_this_was_found` inflected from the reason phrase "Actually This Was Found".
Summary
========
Types
------
[adapter()](#t:adapter/0) [assigns()](#t:assigns/0) [body()](#t:body/0) [cookies()](#t:cookies/0) [halted()](#t:halted/0) [headers()](#t:headers/0) [host()](#t:host/0) [int\_status()](#t:int_status/0) [method()](#t:method/0) [owner()](#t:owner/0) [params()](#t:params/0) [port\_number()](#t:port_number/0) [query\_param()](#t:query_param/0) [query\_params()](#t:query_params/0) [query\_string()](#t:query_string/0) [req\_cookies()](#t:req_cookies/0) [resp\_cookies()](#t:resp_cookies/0) [scheme()](#t:scheme/0) [secret\_key\_base()](#t:secret_key_base/0) [segments()](#t:segments/0) [state()](#t:state/0) [status()](#t:status/0) [t()](#t:t/0) Functions
----------
[assign(conn, key, value)](#assign/3) Assigns a value to a key in the connection.
[chunk(conn, chunk)](#chunk/2) Sends a chunk as part of a chunked response.
[clear\_session(conn)](#clear_session/1) Clears the entire session.
[configure\_session(conn, opts)](#configure_session/2) Configures the session.
[delete\_req\_header(conn, key)](#delete_req_header/2) Deletes a request header if present.
[delete\_resp\_cookie(conn, key, opts \\ [])](#delete_resp_cookie/3) Deletes a response cookie.
[delete\_resp\_header(conn, key)](#delete_resp_header/2) Deletes a response header if present.
[delete\_session(conn, key)](#delete_session/2) Deletes `key` from session.
[fetch\_cookies(conn, opts \\ [])](#fetch_cookies/2) Fetches cookies from the request headers.
[fetch\_query\_params(conn, opts \\ [])](#fetch_query_params/2) Fetches query parameters from the query string.
[fetch\_session(conn, opts \\ [])](#fetch_session/2) Fetches the session from the session store. Will also fetch cookies.
[get\_http\_protocol(conn)](#get_http_protocol/1) Returns the HTTP protocol and version.
[get\_peer\_data(conn)](#get_peer_data/1) Returns the request peer data if one is present.
[get\_req\_header(conn, key)](#get_req_header/2) Returns the values of the request header specified by `key`.
[get\_resp\_header(conn, key)](#get_resp_header/2) Returns the values of the response header specified by `key`.
[get\_session(conn)](#get_session/1) Returns the whole session.
[get\_session(conn, key)](#get_session/2) Returns session value for the given `key`. If `key` is not set, `nil` is returned.
[halt(conn)](#halt/1) Halts the Plug pipeline by preventing further plugs downstream from being invoked. See the docs for [`Plug.Builder`](plug.builder) for more information on halting a Plug pipeline.
[inform!(conn, status, headers \\ [])](#inform!/3) Sends an information response to a client but raises if the adapter does not support inform.
[inform(conn, status, headers \\ [])](#inform/3) Sends an informational response to the client.
[merge\_assigns(conn, keyword)](#merge_assigns/2) Assigns multiple values to keys in the connection.
[merge\_private(conn, keyword)](#merge_private/2) Assigns multiple **private** keys and values in the connection.
[merge\_resp\_headers(conn, headers)](#merge_resp_headers/2) Merges a series of response headers into the connection.
[prepend\_resp\_headers(conn, headers)](#prepend_resp_headers/2) Prepends the list of headers to the connection response headers.
[push!(conn, path, headers \\ [])](#push!/3) Pushes a resource to the client but raises if the adapter does not support server push.
[push(conn, path, headers \\ [])](#push/3) Pushes a resource to the client.
[put\_private(conn, key, value)](#put_private/3) Assigns a new **private** key and value in the connection.
[put\_req\_header(conn, key, value)](#put_req_header/3) Adds a new request header (`key`) if not present, otherwise replaces the previous value of that header with `value`.
[put\_resp\_content\_type(conn, content\_type, charset \\ "utf-8")](#put_resp_content_type/3) Sets the value of the `"content-type"` response header taking into account the `charset`.
[put\_resp\_cookie(conn, key, value, opts \\ [])](#put_resp_cookie/4) Puts a response cookie in the connection.
[put\_resp\_header(conn, key, value)](#put_resp_header/3) Adds a new response header (`key`) if not present, otherwise replaces the previous value of that header with `value`.
[put\_session(conn, key, value)](#put_session/3) Puts the specified `value` in the session for the given `key`.
[put\_status(conn, status)](#put_status/2) Stores the given status code in the connection.
[read\_body(conn, opts \\ [])](#read_body/2) Reads the request body.
[read\_part\_body(conn, opts)](#read_part_body/2) Reads the body of a multipart request.
[read\_part\_headers(conn, opts \\ [])](#read_part_headers/2) Reads the headers of a multipart request.
[register\_before\_send(conn, callback)](#register_before_send/2) Registers a callback to be invoked before the response is sent.
[request\_url(conn)](#request_url/1) Returns the full request URL.
[resp(conn, status, body)](#resp/3) Sets the response to the given `status` and `body`.
[send\_chunked(conn, status)](#send_chunked/2) Sends the response headers as a chunked response.
[send\_file(conn, status, file, offset \\ 0, length \\ :all)](#send_file/5) Sends a file as the response body with the given `status` and optionally starting at the given offset until the given length.
[send\_resp(conn)](#send_resp/1) Sends a response to the client.
[send\_resp(conn, status, body)](#send_resp/3) Sends a response with the given status and body.
[update\_req\_header(conn, key, initial, fun)](#update_req_header/4) Updates a request header if present, otherwise it sets it to an initial value.
[update\_resp\_header(conn, key, initial, fun)](#update_resp_header/4) Updates a response header if present, otherwise it sets it to an initial value.
Types
======
### adapter()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L120)
```
@type adapter() :: {module(), term()}
```
### assigns()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L121)
```
@type assigns() :: %{optional(atom()) => any()}
```
### body()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L122)
```
@type body() :: iodata()
```
### cookies()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L124)
```
@type cookies() :: %{optional(binary()) => term()}
```
### halted()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L125)
```
@type halted() :: boolean()
```
### headers()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L126)
```
@type headers() :: [{binary(), binary()}]
```
### host()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L127)
```
@type host() :: binary()
```
### int\_status()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L128)
```
@type int_status() :: non_neg_integer() | nil
```
### method()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L130)
```
@type method() :: binary()
```
### owner()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L129)
```
@type owner() :: pid()
```
### params()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L133)
```
@type params() :: %{optional(binary()) => term()}
```
### port\_number()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L134)
```
@type port_number() :: :inet.port_number()
```
### query\_param()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L131)
```
@type query_param() ::
binary() | %{optional(binary()) => query_param()} | [query_param()]
```
### query\_params()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L132)
```
@type query_params() :: %{optional(binary()) => query_param()}
```
### query\_string()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L135)
```
@type query_string() :: String.t()
```
### req\_cookies()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L123)
```
@type req_cookies() :: %{optional(binary()) => binary()}
```
### resp\_cookies()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L136)
```
@type resp_cookies() :: %{optional(binary()) => map()}
```
### scheme()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L137)
```
@type scheme() :: :http | :https
```
### secret\_key\_base()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L138)
```
@type secret_key_base() :: binary() | nil
```
### segments()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L139)
```
@type segments() :: [binary()]
```
### state()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L140)
```
@type state() :: :unset | :set | :set_chunked | :set_file | :file | :chunked | :sent
```
### status()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L141)
```
@type status() :: atom() | int_status()
```
### t()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L143)
```
@type t() :: %Plug.Conn{
adapter: adapter(),
assigns: assigns(),
body_params: params() | Plug.Conn.Unfetched.t(),
cookies: cookies() | Plug.Conn.Unfetched.t(),
halted: halted(),
host: host(),
method: method(),
owner: owner(),
params: params() | Plug.Conn.Unfetched.t(),
path_info: segments(),
path_params: query_params(),
port: :inet.port_number(),
private: assigns(),
query_params: query_params() | Plug.Conn.Unfetched.t(),
query_string: query_string(),
remote_ip: :inet.ip_address(),
req_cookies: req_cookies() | Plug.Conn.Unfetched.t(),
req_headers: headers(),
request_path: binary(),
resp_body: body() | nil,
resp_cookies: resp_cookies(),
resp_headers: headers(),
scheme: scheme(),
script_name: segments(),
secret_key_base: secret_key_base(),
state: state(),
status: int_status()
}
```
Functions
==========
### assign(conn, key, value)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L269)
```
@spec assign(t(), atom(), term()) :: t()
```
Assigns a value to a key in the connection.
The "assigns" storage is meant to be used to store values in the connection so that other plugs in your plug pipeline can access them. The assigns storage is a map.
#### Examples
```
iex> conn.assigns[:hello]
nil
iex> conn = assign(conn, :hello, :world)
iex> conn.assigns[:hello]
:world
```
### chunk(conn, chunk)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L511)
```
@spec chunk(t(), body()) :: {:ok, t()} | {:error, term()} | no_return()
```
Sends a chunk as part of a chunked response.
It expects a connection with state `:chunked` as set by [`send_chunked/2`](#send_chunked/2). It returns `{:ok, conn}` in case of success, otherwise `{:error, reason}`.
To stream data use [`Enum.reduce_while/3`](https://hexdocs.pm/elixir/Enum.html#reduce_while/3) instead of [`Enum.into/2`](https://hexdocs.pm/elixir/Enum.html#into/2). [`Enum.reduce_while/3`](https://hexdocs.pm/elixir/Enum.html#reduce_while/3) allows aborting the execution if [`chunk/2`](#chunk/2) fails to deliver the chunk of data.
#### Example
```
Enum.reduce_while(~w(each chunk as a word), conn, fn (chunk, conn) ->
case Plug.Conn.chunk(conn, chunk) do
{:ok, conn} ->
{:cont, conn}
{:error, :closed} ->
{:halt, conn}
end
end)
```
### clear\_session(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1595)
```
@spec clear_session(t()) :: t()
```
Clears the entire session.
This function removes every key from the session, clearing the session.
Note that, even if [`clear_session/1`](#clear_session/1) is used, the session is still sent to the client. If the session should be effectively *dropped*, [`configure_session/2`](#configure_session/2) should be used with the `:drop` option set to `true`.
### configure\_session(conn, opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1615)
```
@spec configure_session(t(), Keyword.t()) :: t()
```
Configures the session.
#### Options
* `:renew` - When `true`, generates a new session id for the cookie
* `:drop` - When `true`, drops the session, a session cookie will not be included in the response
* `:ignore` - When `true`, ignores all changes made to the session in this request cycle
#### Examples
```
configure_session(conn, renew: true)
```
### delete\_req\_header(conn, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L668)
```
@spec delete_req_header(t(), binary()) :: t()
```
Deletes a request header if present.
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
#### Examples
```
Plug.Conn.delete_req_header(conn, "content-type")
```
### delete\_resp\_cookie(conn, key, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1503)
```
@spec delete_resp_cookie(t(), binary(), Keyword.t()) :: t()
```
Deletes a response cookie.
Deleting a cookie requires the same options as to when the cookie was put. Check [`put_resp_cookie/4`](#put_resp_cookie/4) for more information.
### delete\_resp\_header(conn, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L875)
```
@spec delete_resp_header(t(), binary()) :: t()
```
Deletes a response header if present.
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
#### Examples
```
Plug.Conn.delete_resp_header(conn, "content-type")
```
### delete\_session(conn, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1578)
```
@spec delete_session(t(), String.t() | atom()) :: t()
```
Deletes `key` from session.
The key can be a string or an atom, where atoms are automatically converted to strings.
### fetch\_cookies(conn, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1327)
```
@spec fetch_cookies(t(), Keyword.t()) :: t()
```
Fetches cookies from the request headers.
#### Options
* `:signed` - a list of one or more cookies that are signed and must be verified accordingly
* `:encrypted` - a list of one or more cookies that are encrypted and must be decrypted accordingly
See [`put_resp_cookie/4`](#put_resp_cookie/4) for more information.
### fetch\_query\_params(conn, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L972)
```
@spec fetch_query_params(t(), Keyword.t()) :: t()
```
Fetches query parameters from the query string.
Params are decoded as `"x-www-form-urlencoded"` in which key/value pairs are separated by `&` and keys are separated from values by `=`.
This function does not fetch parameters from the body. To fetch parameters from the body, use the [`Plug.Parsers`](plug.parsers) plug.
#### Options
* `:length` - the maximum query string length. Defaults to `1_000_000` bytes. Keep in mind the webserver you are using may have a more strict limit. For example, for the Cowboy webserver, [please read](https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html#module-safety-limits).
* `:validate_utf8` - boolean that tells whether or not to validate the keys and values of the decoded query string are UTF-8 encoded. Defaults to `true`.
### fetch\_session(conn, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1516)
```
@spec fetch_session(t(), Keyword.t()) :: t()
```
Fetches the session from the session store. Will also fetch cookies.
### get\_http\_protocol(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L605)
```
@spec get_http_protocol(t()) :: Plug.Conn.Adapter.http_protocol()
```
Returns the HTTP protocol and version.
#### Examples
```
iex> get_http_protocol(conn)
:"HTTP/1.1"
```
### get\_peer\_data(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L591)
```
@spec get_peer_data(t()) :: Plug.Conn.Adapter.peer_data()
```
Returns the request peer data if one is present.
### get\_req\_header(conn, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L619)
```
@spec get_req_header(t(), binary()) :: [binary()]
```
Returns the values of the request header specified by `key`.
#### Examples
```
iex> get_req_header(conn, "accept")
["application/json"]
```
### get\_resp\_header(conn, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L732)
```
@spec get_resp_header(t(), binary()) :: [binary()]
```
Returns the values of the response header specified by `key`.
#### Examples
```
iex> conn = %{conn | resp_headers: [{"content-type", "text/plain"}]}
iex> get_resp_header(conn, "content-type")
["text/plain"]
```
### get\_session(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1563)
```
@spec get_session(t()) :: %{optional(String.t()) => any()}
```
Returns the whole session.
Although [`get_session/2`](#get_session/2) and [`put_session/3`](#put_session/3) allow atom keys, they are always normalized to strings. So this function always returns a map with string keys.
Raises if the session was not yet fetched.
### get\_session(conn, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1549)
```
@spec get_session(t(), String.t() | atom()) :: any()
```
Returns session value for the given `key`. If `key` is not set, `nil` is returned.
The key can be a string or an atom, where atoms are automatically converted to strings.
### halt(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1669)
```
@spec halt(t()) :: t()
```
Halts the Plug pipeline by preventing further plugs downstream from being invoked. See the docs for [`Plug.Builder`](plug.builder) for more information on halting a Plug pipeline.
### inform!(conn, status, headers \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1235)
```
@spec inform!(t(), status(), Keyword.t()) :: t()
```
Sends an information response to a client but raises if the adapter does not support inform.
See `inform/1` for more information.
### inform(conn, status, headers \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1223)
```
@spec inform(t(), status(), Keyword.t()) :: t()
```
Sends an informational response to the client.
An informational response, such as an early hint, must happen prior to a response being sent. If an informational request is attempted after a response is sent then a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) will be raised. Only status codes from 100-199 are valid.
To use inform for early hints send one or more informs with a status of 103.
If the adapter does not support informational responses then this is a noop.
Most HTTP/1.1 clients do not properly support informational responses but some proxies require it to support server push for HTTP/2. You can call [`get_http_protocol/1`](#get_http_protocol/1) to retrieve the protocol and version.
### merge\_assigns(conn, keyword)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L288)
```
@spec merge_assigns(t(), Keyword.t()) :: t()
```
Assigns multiple values to keys in the connection.
Equivalent to multiple calls to [`assign/3`](#assign/3).
#### Examples
```
iex> conn.assigns[:hello]
nil
iex> conn = merge_assigns(conn, hello: :world)
iex> conn.assigns[:hello]
:world
```
### merge\_private(conn, keyword)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L347)
```
@spec merge_private(t(), Keyword.t()) :: t()
```
Assigns multiple **private** keys and values in the connection.
Equivalent to multiple [`put_private/3`](#put_private/3) calls.
#### Examples
```
iex> conn.private[:my_plug_hello]
nil
iex> conn = merge_private(conn, my_plug_hello: :world)
iex> conn.private[:my_plug_hello]
:world
```
### merge\_resp\_headers(conn, headers)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L837)
```
@spec merge_resp_headers(t(), Enum.t()) :: t()
```
Merges a series of response headers into the connection.
It is recommended for header keys to be in lowercase, to avoid sending duplicate keys in a request. Additionally, responses with mixed-case headers served over HTTP/2 are not considered valid by common clients, resulting in dropped responses. As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any headers that aren't lowercase will raise a [`Plug.Conn.InvalidHeaderError`](plug.conn.invalidheadererror).
#### Example
```
Plug.Conn.merge_resp_headers(conn, [{"content-type", "text/plain"}, {"X-1337", "5P34K"}])
```
### prepend\_resp\_headers(conn, headers)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L801)
```
@spec prepend_resp_headers(t(), headers()) :: t()
```
Prepends the list of headers to the connection response headers.
Similar to `put_resp_header` this functions adds a new response header (`key`) but rather then replacing the existing one it prepends another header with the same `key`.
It is recommended for header keys to be in lowercase, to avoid sending duplicate keys in a request. Additionally, responses with mixed-case headers served over HTTP/2 are not considered valid by common clients, resulting in dropped responses. As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any headers that aren't lowercase will raise a [`Plug.Conn.InvalidHeaderError`](plug.conn.invalidheadererror).
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
Raises a [`Plug.Conn.InvalidHeaderError`](plug.conn.invalidheadererror) if the header value contains control feed (`\r`) or newline (`\n`) characters.
#### Examples
```
Plug.Conn.prepend_resp_headers(conn, [{"content-type", "application/json"}])
```
### push!(conn, path, headers \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1286)
```
@spec push!(t(), String.t(), Keyword.t()) :: t()
```
Pushes a resource to the client but raises if the adapter does not support server push.
### push(conn, path, headers \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1276)
```
@spec push(t(), String.t(), Keyword.t()) :: t()
```
Pushes a resource to the client.
Server pushes must happen prior to a response being sent. If a server push is attempted after a response is sent then a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) will be raised.
If the adapter does not support server push then this is a noop.
Note that certain browsers (such as Google Chrome) will not accept a pushed resource if your certificate is not trusted. In the case of Chrome this means a valid cert with a SAN. See <https://www.chromestatus.com/feature/4981025180483584>
### put\_private(conn, key, value)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L328)
```
@spec put_private(t(), atom(), term()) :: t()
```
Assigns a new **private** key and value in the connection.
This storage is meant to be used by libraries and frameworks to avoid writing to the user storage (the `:assigns` field). It is recommended for libraries/frameworks to prefix the keys with the library name.
For example, if a plug called `my_plug` needs to store a `:hello` key, it would store it as `:my_plug_hello`:
```
iex> conn.private[:my_plug_hello]
nil
iex> conn = put_private(conn, :my_plug_hello, :world)
iex> conn.private[:my_plug_hello]
:world
```
### put\_req\_header(conn, key, value)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L644)
```
@spec put_req_header(t(), binary(), binary()) :: t()
```
Adds a new request header (`key`) if not present, otherwise replaces the previous value of that header with `value`.
Because header keys are case-insensitive in both HTTP/1.1 and HTTP/2, it is recommended for header keys to be in lowercase, to avoid sending duplicate keys in a request. Additionally, requests with mixed-case headers served over HTTP/2 are not considered valid by common clients, resulting in dropped requests. As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any headers that aren't lowercase will raise a [`Plug.Conn.InvalidHeaderError`](plug.conn.invalidheadererror).
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
#### Examples
```
Plug.Conn.put_req_header(conn, "accept", "application/json")
```
### put\_resp\_content\_type(conn, content\_type, charset \\ "utf-8")[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L941)
```
@spec put_resp_content_type(t(), binary(), binary() | nil) :: t()
```
Sets the value of the `"content-type"` response header taking into account the `charset`.
If `charset` is `nil`, the value of the `"content-type"` response header won't specify a charset.
#### Examples
```
iex> conn = put_resp_content_type(conn, "application/json")
iex> get_resp_header(conn, "content-type")
["application/json; charset=utf-8"]
```
### put\_resp\_cookie(conn, key, value, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1457)
```
@spec put_resp_cookie(t(), binary(), any(), Keyword.t()) :: t()
```
Puts a response cookie in the connection.
If the `:sign` or `:encrypt` flag are given, then the cookie value can be any term.
If the cookie is not signed nor encrypted, then the value must be a binary. Note the value is not automatically escaped. Therefore if you want to store values with non-alphanumeric characters, you must either sign or encrypt the cookie or consider explicitly escaping the cookie value by using a function such as `Base.encode64(value, padding: false)` when writing and `Base.decode64(encoded, padding: false)` when reading the cookie. It is important for padding to be disabled since `=` is not a valid character in cookie values.
#### Signing and encrypting cookies
This function allows you to automatically sign and encrypt cookies. When signing or encryption is enabled, then any Elixir value can be stored in the cookie (except anonymous functions for security reasons). Once a value is signed or encrypted, you must also call [`fetch_cookies/2`](#fetch_cookies/2) with the name of the cookies that are either signed or encrypted.
To sign, you would do:
```
put_resp_cookie(conn, "my-cookie", %{user_id: user.id}, sign: true)
```
and then:
```
fetch_cookies(conn, signed: ~w(my-cookie))
```
To encrypt, you would do:
```
put_resp_cookie(conn, "my-cookie", %{user_id: user.id}, encrypt: true)
```
and then:
```
fetch_cookies(conn, encrypted: ~w(my-cookie))
```
By default a signed or encrypted cookie is only valid for a day, unless a `:max_age` is specified.
The signing and encryption keys are derived from the connection's `secret_key_base` using a salt that is built by appending "\_cookie" to the cookie name. Care should be taken not to derive other keys using this value as the salt. Similarly do not use the same cookie name to store different values with distinct purposes.
#### Options
* `:domain` - the domain the cookie applies to
* `:max_age` - the cookie max-age, in seconds. Providing a value for this option will set both the *max-age* and *expires* cookie attributes.
* `:path` - the path the cookie applies to
* `:http_only` - when `false`, the cookie is accessible beyond HTTP
* `:secure` - if the cookie must be sent only over https. Defaults to true when the connection is HTTPS
* `:extra` - string to append to cookie. Use this to take advantage of non-standard cookie attributes.
* `:sign` - when true, signs the cookie
* `:encrypt` - when true, encrypts the cookie
* `:same_site` - set the cookie SameSite attribute to a string value. If no string value is set, the attribute is omitted.
### put\_resp\_header(conn, key, value)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L760)
```
@spec put_resp_header(t(), binary(), binary()) :: t()
```
Adds a new response header (`key`) if not present, otherwise replaces the previous value of that header with `value`.
Because header keys are case-insensitive in both HTTP/1.1 and HTTP/2, it is recommended for header keys to be in lowercase, to avoid sending duplicate keys in a request. Additionally, responses with mixed-case headers served over HTTP/2 are not considered valid by common clients, resulting in dropped responses. As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any headers that aren't lowercase will raise a [`Plug.Conn.InvalidHeaderError`](plug.conn.invalidheadererror).
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
Raises a [`Plug.Conn.InvalidHeaderError`](plug.conn.invalidheadererror) if the header value contains control feed (`\r`) or newline (`\n`) characters.
#### Examples
```
Plug.Conn.put_resp_header(conn, "content-type", "application/json")
```
### put\_session(conn, key, value)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1534)
```
@spec put_session(t(), String.t() | atom(), any()) :: t()
```
Puts the specified `value` in the session for the given `key`.
The key can be a string or an atom, where atoms are automatically converted to strings. Can only be invoked on unsent `conn`s. Will raise otherwise.
### put\_status(conn, status)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L367)
```
@spec put_status(t(), status()) :: t()
```
Stores the given status code in the connection.
The status code can be `nil`, an integer, or an atom. The list of allowed atoms is available in [`Plug.Conn.Status`](plug.conn.status).
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
#### Examples
```
Plug.Conn.put_status(conn, :not_found)
Plug.Conn.put_status(conn, 200)
```
### read\_body(conn, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1050)
```
@spec read_body(t(), Keyword.t()) ::
{:ok, binary(), t()} | {:more, binary(), t()} | {:error, term()}
```
Reads the request body.
This function reads a chunk of the request body up to a given length (specified by the `:length` option). If there is more data to be read, then `{:more, partial_body, conn}` is returned. Otherwise `{:ok, body, conn}` is returned. In case of an error reading the socket, `{:error, reason}` is returned as per [`:gen_tcp.recv/2`](https://www.erlang.org/doc/man/gen_tcp.html#recv-2).
Like all functions in this module, the `conn` returned by `read_body` must be passed to the next stage of your pipeline and should not be ignored.
In order to, for instance, support slower clients you can tune the `:read_length` and `:read_timeout` options. These specify how much time should be allowed to pass for each read from the underlying socket.
Because the request body can be of any size, reading the body will only work once, as Plug will not cache the result of these operations. If you need to access the body multiple times, it is your responsibility to store it. Finally keep in mind some plugs like [`Plug.Parsers`](plug.parsers) may read the body, so the body may be unavailable after being accessed by such plugs.
This function is able to handle both chunked and identity transfer-encoding by default.
#### Options
* `:length` - sets the maximum number of bytes to read from the body on every call, defaults to `8_000_000` bytes
* `:read_length` - sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to `1_000_000` bytes
* `:read_timeout` - sets the timeout for each socket read, defaults to `15_000` milliseconds
The values above are not meant to be exact. For example, setting the length to `8_000_000` may end up reading some hundred bytes more from the socket until we halt.
#### Examples
```
{:ok, body, conn} = Plug.Conn.read_body(conn, length: 1_000_000)
```
### read\_part\_body(conn, opts)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1126)
```
@spec read_part_body(t(), Keyword.t()) ::
{:ok, binary(), t()} | {:more, binary(), t()} | {:done, t()}
```
Reads the body of a multipart request.
Returns `{:ok, body, conn}` if all body has been read, `{:more, binary, conn}` otherwise, and `{:done, conn}` if there is no more body.
It accepts the same options as [`read_body/2`](#read_body/2).
### read\_part\_headers(conn, opts \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1085)
```
@spec read_part_headers(t(), Keyword.t()) :: {:ok, headers(), t()} | {:done, t()}
```
Reads the headers of a multipart request.
It returns `{:ok, headers, conn}` with the headers or `{:done, conn}` if there are no more parts.
Once [`read_part_headers/2`](#read_part_headers/2) is invoked, you may call [`read_part_body/2`](#read_part_body/2) to read the body associated to the headers. If [`read_part_headers/2`](#read_part_headers/2) is called instead, the body is automatically skipped until the next part headers.
#### Options
* `:length` - sets the maximum number of bytes to read from the body for each chunk, defaults to `64_000` bytes
* `:read_length` - sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to `64_000` bytes
* `:read_timeout` - sets the timeout for each socket read, defaults to `5_000` milliseconds
### register\_before\_send(conn, callback)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1651)
```
@spec register_before_send(t(), (t() -> t())) :: t()
```
Registers a callback to be invoked before the response is sent.
Callbacks are invoked in the reverse order they are defined (callbacks defined first are invoked last).
#### Examples
To log the status of response being sent:
```
require Logger
Plug.Conn.register_before_send(conn, fn conn ->
Logger.info("Sent a #{conn.status} response")
conn
end)
```
### request\_url(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L1676)
Returns the full request URL.
### resp(conn, status, body)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L572)
```
@spec resp(t(), status(), body()) :: t()
```
Sets the response to the given `status` and `body`.
It sets the connection state to `:set` (if not already `:set`) and raises [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if it was already `:sent`.
If you also want to send the response, use [`send_resp/1`](#send_resp/1) after this or use [`send_resp/3`](#send_resp/3).
The status can be an integer, an atom, or `nil`. See [`Plug.Conn.Status`](plug.conn.status) for more information.
#### Examples
```
Plug.Conn.resp(conn, 404, "Not found")
```
### send\_chunked(conn, status)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L473)
```
@spec send_chunked(t(), status()) :: t() | no_return()
```
Sends the response headers as a chunked response.
It expects a connection that has not been `:sent` yet and sets its state to `:chunked` afterwards. Otherwise, raises [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror). After [`send_chunked/2`](#send_chunked/2) is called, chunks can be sent to the client via the [`chunk/2`](#chunk/2) function.
HTTP/2 does not support chunking and will instead stream the response without a transfer encoding. When using HTTP/1.1, the Cowboy adapter will stream the response instead of emitting chunks if the `content-length` header has been set before calling [`send_chunked/2`](#send_chunked/2).
### send\_file(conn, status, file, offset \\ 0, length \\ :all)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L429)
```
@spec send_file(
t(),
status(),
filename :: binary(),
offset :: integer(),
length :: integer() | :all
) ::
t() | no_return()
```
Sends a file as the response body with the given `status` and optionally starting at the given offset until the given length.
If available, the file is sent directly over the socket using the operating system `sendfile` operation.
It expects a connection that has not been `:sent` yet and sets its state to `:file` afterwards. Otherwise raises [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror).
#### Examples
```
Plug.Conn.send_file(conn, 200, "README.md")
```
### send\_resp(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L392)
```
@spec send_resp(t()) :: t() | no_return()
```
Sends a response to the client.
It expects the connection state to be `:set`, otherwise raises an [`ArgumentError`](https://hexdocs.pm/elixir/ArgumentError.html) for `:unset` connections or a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) for already `:sent` connections.
At the end sets the connection state to `:sent`.
Note that this function does not halt the connection, so if subsequent plugs try to send another response, it will error out. Use [`halt/1`](#halt/1) after this function if you want to halt the plug pipeline.
#### Examples
```
conn
|> Plug.Conn.resp(404, "Not found")
|> Plug.Conn.send_resp()
```
### send\_resp(conn, status, body)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L550)
```
@spec send_resp(t(), status(), body()) :: t() | no_return()
```
Sends a response with the given status and body.
This is equivalent to setting the status and the body and then calling [`send_resp/1`](#send_resp/1).
Note that this function does not halt the connection, so if subsequent plugs try to send another response, it will error out. Use [`halt/1`](#halt/1) after this function if you want to halt the plug pipeline.
#### Examples
```
Plug.Conn.send_resp(conn, 404, "Not found")
```
### update\_req\_header(conn, key, initial, fun)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L703)
```
@spec update_req_header(t(), binary(), binary(), (binary() -> binary())) :: t()
```
Updates a request header if present, otherwise it sets it to an initial value.
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
Only the first value of the header `key` is updated if present.
#### Examples
```
Plug.Conn.update_req_header(
conn,
"accept",
"application/json; charset=utf-8",
&(&1 <> "; charset=utf-8")
)
```
### update\_resp\_header(conn, key, initial, fun)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn.ex#L908)
```
@spec update_resp_header(t(), binary(), binary(), (binary() -> binary())) :: t()
```
Updates a response header if present, otherwise it sets it to an initial value.
Raises a [`Plug.Conn.AlreadySentError`](plug.conn.alreadysenterror) if the connection has already been `:sent` or `:chunked`.
Only the first value of the header `key` is updated if present.
#### Examples
```
Plug.Conn.update_resp_header(
conn,
"content-type",
"application/json; charset=utf-8",
&(&1 <> "; charset=utf-8")
)
```
| programming_docs |
phoenix Plug.CSRFProtection Plug.CSRFProtection
====================
Plug to protect from cross-site request forgery.
For this plug to work, it expects a session to have been previously fetched. It will then compare the token stored in the session with the one sent by the request to determine the validity of the request. For an invalid request the action taken is based on the `:with` option.
The token may be sent by the request either via the params with key "\_csrf\_token" or a header with name "x-csrf-token".
GET requests are not protected, as they should not have any side-effect or change your application state. JavaScript requests are an exception: by using a script tag, external websites can embed server-side generated JavaScript, which can leak information. For this reason, this plug also forbids any GET JavaScript request that is not XHR (or AJAX).
Note that it is recommended to enable CSRFProtection whenever a session is used, even for JSON requests. For example, Chrome had a bug that allowed POST requests to be triggered with arbitrary content-type, making JSON exploitable. More info: <https://bugs.chromium.org/p/chromium/issues/detail?id=490015>
Finally, we recommend developers to invoke [`delete_csrf_token/0`](#delete_csrf_token/0) every time after they log a user in, to avoid CSRF fixation attacks.
Token generation
-----------------
This plug won't generate tokens automatically. Instead, tokens will be generated only when required by calling [`get_csrf_token/0`](#get_csrf_token/0). In case you are generating the token for certain specific URL, you should use [`get_csrf_token_for/1`](#get_csrf_token_for/1) as that will avoid tokens from being leaked to other applications.
Once a token is generated, it is cached in the process dictionary. The CSRF token is usually generated inside forms which may be isolated from [`Plug.Conn`](plug.conn). Storing them in the process dictionary allows them to be generated as a side-effect only when necessary, becoming one of those rare situations where using the process dictionary is useful.
Cross-host protection
----------------------
If you are sending data to a full URI, such as `//subdomain.host.com/path` or `//external.com/path`, instead of a simple path such as `/path`, you may want to consider using [`get_csrf_token_for/1`](#get_csrf_token_for/1), as that will encode the host in the CSRF token. Once received, Plug will only consider the CSRF token to be valid if the `host` encoded in the token is the same as the one in `conn.host`.
Therefore, if you get a warning that the host does not match, it is either because someone is attempting to steal CSRF tokens or because you have a misconfigured host configuration.
For example, if you are running your application behind a proxy, the browser will send a request to the proxy with `www.example.com` but the proxy will request you using an internal IP. In such cases, it is common for proxies to attach information such as `"x-forwarded-host"` that contains the original host.
This may also happen on redirects. If you have a POST request to `foo.example.com` that redirects to `bar.example.com` with status 307, the token will contain a different host than the one in the request.
You can pass the `:allow_hosts` option to control any host that you may want to allow. The values in `:allow_hosts` may either be a full host name or a host suffix. For example: `["www.example.com", ".subdomain.example.com"]` will allow the exact host of `"www.example.com"` and any host that ends with `".subdomain.example.com"`.
Options
--------
* `:session_key` - the name of the key in session to store the token under
* `:allow_hosts` - a list with hosts to allow on cross-host tokens
* `:with` - should be one of `:exception` or `:clear_session`. Defaults to `:exception`.
+ `:exception` - for invalid requests, this plug will raise [`Plug.CSRFProtection.InvalidCSRFTokenError`](plug.csrfprotection.invalidcsrftokenerror).
+ `:clear_session` - for invalid requests, this plug will set an empty session for only this request. Also any changes to the session during this request will be ignored.
Disabling
----------
You may disable this plug by doing `Plug.Conn.put_private(conn, :plug_skip_csrf_protection, true)`. This was made available for disabling [`Plug.CSRFProtection`](plug.csrfprotection#content) in tests and not for dynamically skipping [`Plug.CSRFProtection`](plug.csrfprotection#content) in production code. If you want specific routes to skip [`Plug.CSRFProtection`](plug.csrfprotection#content), then use a different stack of plugs for that route that does not include [`Plug.CSRFProtection`](plug.csrfprotection#content).
Examples
---------
```
plug Plug.Session, ...
plug :fetch_session
plug Plug.CSRFProtection
```
Summary
========
Functions
----------
[delete\_csrf\_token()](#delete_csrf_token/0) Deletes the CSRF token from the process dictionary.
[dump\_state()](#dump_state/0) Dump CSRF state from the process dictionary.
[dump\_state\_from\_session(session\_token)](#dump_state_from_session/1) Dumps the CSRF state from the session token.
[get\_csrf\_token()](#get_csrf_token/0) Gets the CSRF token.
[get\_csrf\_token\_for(url)](#get_csrf_token_for/1) Gets the CSRF token for the associated URL (as a string or a URI struct).
[load\_state(secret\_key\_base, csrf\_state)](#load_state/2) Load CSRF state into the process dictionary.
[valid\_state\_and\_csrf\_token?(state, csrf\_token)](#valid_state_and_csrf_token?/2) Validates the `csrf_token` against the state.
Functions
==========
### delete\_csrf\_token()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/csrf_protection.ex#L279)
Deletes the CSRF token from the process dictionary.
This will force the token to be deleted once the response is sent. If you want to refresh the CSRF state, you can call [`get_csrf_token/0`](#get_csrf_token/0) after [`delete_csrf_token/0`](#delete_csrf_token/0) to ensure a new token is generated.
### dump\_state()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/csrf_protection.ex#L184)
Dump CSRF state from the process dictionary.
This allows it to be loaded in another process.
See [`load_state/2`](#load_state/2) for more information.
### dump\_state\_from\_session(session\_token)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/csrf_protection.ex#L194)
Dumps the CSRF state from the session token.
It expects the value of `get_session(conn, "_csrf_token")` as input. It returns `nil` if the given token is not valid.
### get\_csrf\_token()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/csrf_protection.ex#L224)
Gets the CSRF token.
Generates a token and stores it in the process dictionary if one does not exist.
### get\_csrf\_token\_for(url)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/csrf_protection.ex#L241)
Gets the CSRF token for the associated URL (as a string or a URI struct).
If the URL has a host, a CSRF token that is tied to that host will be generated. If it is a relative path URL, a simple token emitted with [`get_csrf_token/0`](#get_csrf_token/0) will be used.
### load\_state(secret\_key\_base, csrf\_state)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/csrf_protection.ex#L171)
Load CSRF state into the process dictionary.
This can be used to load CSRF state into another process. See [`dump_state/0`](#dump_state/0) and `dump_state_from_session/2` for dumping it.
#### Examples
To dump the state from the current process and load into another one:
```
csrf_state = Plug.CSRFProtection.dump_state()
secret_key_base = conn.secret_key_base
Task.async(fn ->
Plug.CSRFProtection.load_state(secret_key_base, csrf_state)
end)
```
If you have a session but the CSRF state was not loaded into the current process, you can dump the state from the session:
```
csrf_state = Plug.CSRFProtection.dump_state_from_session(session["_csrf_token"])
Task.async(fn ->
Plug.CSRFProtection.load_state(secret_key_base, csrf_state)
end)
```
### valid\_state\_and\_csrf\_token?(state, csrf\_token)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/csrf_protection.ex#L207)
Validates the `csrf_token` against the state.
This is the mechanism used by the Plug itself to match the token received in the request (via headers or parameters) with the state (typically stored in the session).
phoenix Plug.Parsers.BadEncodingError exception Plug.Parsers.BadEncodingError exception
========================================
Raised when the request body contains bad encoding.
phoenix Plug.Debugger Plug.Debugger
==============
A module (**not a plug**) for debugging in development.
This module is commonly used within a [`Plug.Builder`](plug.builder) or a [`Plug.Router`](plug.router) and it wraps the `call/2` function.
Notice [`Plug.Debugger`](plug.debugger#content) *does not* catch errors, as errors should still propagate so that the Elixir process finishes with the proper reason. This module does not perform any logging either, as all logging is done by the web server handler.
**Note:** If this module is used with [`Plug.ErrorHandler`](plug.errorhandler), only one of them will effectively handle errors. For this reason, it is recommended that [`Plug.Debugger`](plug.debugger#content) is used before [`Plug.ErrorHandler`](plug.errorhandler) and only in particular environments, like `:dev`.
In case of an error, the rendered page drops the `content-security-policy` header before rendering the error to ensure that the error is displayed correctly.
Examples
---------
```
defmodule MyApp do
use Plug.Builder
if Mix.env == :dev do
use Plug.Debugger, otp_app: :my_app
end
plug :boom
def boom(conn, _) do
# Error raised here will be caught and displayed in a debug page
# complete with a stacktrace and other helpful info.
raise "oops"
end
end
```
Options
--------
* `:otp_app` - the OTP application that is using Plug. This option is used to filter stacktraces that belong only to the given application.
* `:style` - custom styles (see below)
* `:banner` - the optional MFA (`{module, function, args}`) which receives exception details and returns banner contents to appear at the top of the page. May be any string, including markup.
Custom styles
--------------
You may pass a `:style` option to customize the look of the HTML page.
```
use Plug.Debugger, style:
[primary: "#c0392b", logo: "data:image/png;base64,..."]
```
The following keys are available:
* `:primary` - primary color
* `:accent` - accent color
* `:logo` - logo URI, or `nil` to disable
The `:logo` is preferred to be a base64-encoded data URI so not to make any external requests, though external URLs (eg, `https://...`) are supported.
Custom Banners
---------------
You may pass an MFA (`{module, function, args}`) to be invoked when an error is rendered which provides a custom banner at the top of the debugger page. The function receives the following arguments, with the passed `args` concatenated at the end:
```
[conn, status, kind, reason, stacktrace]
```
For example, the following `:banner` option:
```
use Plug.Debugger, banner: {MyModule, :debug_banner, []}
```
would invoke the function:
```
MyModule.debug_banner(conn, status, kind, reason, stacktrace)
```
Links to the text editor
-------------------------
If a `PLUG_EDITOR` environment variable is set, [`Plug.Debugger`](plug.debugger#content) will use it to generate links to your text editor. The variable should be set with `__FILE__` and `__LINE__` placeholders which will be correctly replaced. For example (with the [TextMate](http://macromates.com) editor):
```
txmt://open/?url=file://__FILE__&line=__LINE__
```
Or, using Visual Studio Code:
```
vscode://file/__FILE__:__LINE__
```
phoenix HTTPS HTTPS
======
Plug can serve HTTP over TLS ('HTTPS') through an appropriately configured Adapter. While the exact syntax for defining an HTTPS listener is adapter-specific, Plug does define a common set of TLS configuration options that most adapters support, formally documented as [`Plug.SSL.configure/1`](plug.ssl#configure/1).
This guide describes how to use these parameters to set up an HTTPS server with Plug, and documents some best-practices and potential pitfalls.
> Editor's note: The secure transport protocol used by HTTPS is nowadays referred to as TLS. However, the application in the Erlang/OTP standard library that implements it is called `:ssl`, for historical reasons. In this document we will refer to the protocol as 'TLS' and to the Erlang/OTP implementation as `:ssl`, and its configuration parameters as `:ssl` options.
>
>
Prerequisites
--------------
The prerequisites for running an HTTPS server with Plug include:
* The Erlang/OTP runtime, with OpenSSL bindings; run `:crypto.info_lib()` in an IEx session to verify
* A Plug Adapter that supports HTTPS, e.g. [Plug.Cowboy](https://hex.pm/packages/plug_cowboy)
* A valid certificate and associated private key
### Self-signed Certificate
For testing purposes it may be sufficient to use a self-signed certificate. Such certificates generally result in warnings in browsers and failed connections from other tools, but these can be overridden to enable HTTPS testing. This is especially useful for local testing of HTTP 2, which is only specified over TLS.
> **Warning**: use self-signed certificates only for local testing, and do not mark such test certificates as globally trusted in browsers or operating system!
>
>
The [Phoenix](https://phoenixframework.org/) project includes a Mix task `mix phx.gen.cert` that generates the necessary files and places them in the application's 'priv' directory. The [X509](https://hex.pm/packages/x509) package can be used as a dev-only dependency to add a similar `mix x509.gen.selfsigned` task to non-Phoenix projects.
Alternatively, the OpenSSL CLI or other utilities can be used to generate a self-signed certificate. Instructions are widely available online.
### CA Issued Certificate
For staging and production it is necessary to obtain a CA-signed certificate from a trusted Certificate Authority, such as [Let's Encrypt](https://letsencrypt.org). Certificates issued by a CA usually come with an additional file containing one or more certificates that make up the 'CA chain'.
For use with Plug the certificates and key should be stored in PEM format, containing Base64-encoded data between 'BEGIN' and 'END' markers. Some useful OpenSSL commands for converting certificates/keys from other formats can be found at [the end of this document](#converting-certificates-and-keys).
Getting Started
----------------
A minimal HTTPS listener, using Plug.Cowboy, might be defined as follows:
```
Plug.Cowboy.https MyApp.MyPlug, [],
port: 8443,
cipher_suite: :strong,
certfile: "/etc/letsencrypt/live/example.net/cert.pem",
keyfile: "/etc/letsencrypt/live/example.net/privkey.pem",
cacertfile: "/etc/letsencrypt/live/example.net/chain.pem"
```
The `cacertfile` option is not needed when using a self-signed certificate, or when the file pointed to by `certfile` contains both the server certificate and all necessary CA chain certificates:
```
#...
certfile: "/etc/letsencrypt/live/example.net/fullchain.pem",
keyfile: "/etc/letsencrypt/live/example.net/privkey.pem"
```
It is possible to bundle the certificate files with the application, possibly for packaging into a release. In this case the files must be stored under the application's 'priv' directory. The `otp_app` option must be set to the name of the OTP application that contains the files, in order to correctly resolve the relative paths:
```
Plug.Cowboy.https MyApp.MyPlug, [],
port: 8443,
cipher_suite: :strong,
certfile: "priv/cert/selfsigned.pem",
keyfile: "priv/cert/selfsigned_key.pem",
otp_app: :my_app
```
Remember to exclude the files from version control, unless the certificate and key are shared by all developers for testing purposes only. For example, add this line to the '.gitignore' file: `priv/**/*.pem`.
TLS Protocol Options
---------------------
In addition to a certificate, an HTTPS server needs a secure TLS protocol configuration. [`Plug.SSL`](plug.ssl) always sets the following options:
* Set `secure_renegotiate: true`, to avoid certain types of man-in-the-middle attacks
* Set `reuse_sessions: true`, for improved handshake performance of recurring connections
Additional options can be set by selecting a predefined profile or by setting `:ssl` options individually.
### Predefined Options
To simplify configuration of TLS defaults Plug provides two preconfigured options: `cipher_suite: :strong` and `cipher_suite: :compatible`.
The `:strong` profile enables AES-GCM ciphers with ECDHE or DHE key exchange, and TLS version 1.2 only. It is intended for typical installations with support for browsers and other modern clients.
The `:compatible` profile additionally enables AES-CBC ciphers, as well as TLS versions 1.1 and 1.0. Use this configuration to allow connections from older clients, such as older PC or mobile operating systems. Note that RSA key exchange is not enabled by this configuration, due to known weaknesses, so to support clients that do not support ECDHE or DHE it is necessary specify the ciphers explicitly (see [below](#manual-configuration)).
In addition, both profiles:
* Configure the server to choose a cipher based on its own preferences rather than the client's (`honor_cipher_order` set to `true`); when specifying a custom cipher list, ensure the ciphers are listed in descending order of preference
* Select the 'Prime' (SECP) curves for use in Elliptic Curve Cryptography (ECC)
All these parameters, including the global defaults mentioned above, can be overridden by specifying custom `:ssl` configuration options.
It is worth noting that the cipher lists and TLS protocol versions selected by the profiles are whitelists. If a new Erlang/OTP release introduces new TLS protocol versions or ciphers that are not included in the profile definition, they would have to be enabled explicitly by overriding the `:ciphers` and/or `:versions` options, until such time as they are added to the [`Plug.SSL`](plug.ssl) profiles.
The ciphers chosen and related configuration are based on [OWASP recommendations](https://www.owasp.org/index.php/TLS_Cipher_String_Cheat_Sheet), with some modifications as described in the [`Plug.SSL.configure/1`](plug.ssl#configure/1) documentation.
### Manual Configuration
Please refer to the [Erlang/OTP `:ssl` documentation](http://erlang.org/doc/man/ssl.html) for details on the supported configuration options.
An example configuration with custom `:ssl` options might look like this:
```
Plug.Cowboy.https MyApp.MyPlug, [],
port: 8443,
certfile: "/etc/letsencrypt/live/example.net/cert.pem",
keyfile: "/etc/letsencrypt/live/example.net/privkey.pem",
cacertfile: "/etc/letsencrypt/live/example.net/chain.pem",
versions: [:"tlsv1.2", :"tlsv1.1"],
ciphers: [
'ECDHE-RSA-AES256-GCM-SHA384',
'ECDHE-RSA-AES128-GCM-SHA256',
'DHE-RSA-AES256-GCM-SHA384',
'DHE-RSA-AES128-GCM-SHA256'
],
honor_cipher_order: true,
sni_fun: &MyPlug.ssl_opts_for_hostname/1
```
HTTP Strict Transport Security (HSTS)
--------------------------------------
Once a server is configured to support HTTPS it is often a good idea to redirect HTTP requests to HTTPS. To do this, include [`Plug.SSL`](plug.ssl) in the Plug pipeline.
To prevent downgrade attacks, in which an attacker intercepts a plain HTTP request to the server before the redirect to HTTPS takes place, [`Plug.SSL`](plug.ssl) by default sets the '[Strict-Transport-Security](https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet)' (HSTS) header. This informs the browser that the current site must only ever be accessed over HTTPS, even if the user typed or clicked a plain HTTP URL. This only works if the site is reachable on port 443 (see [Listening on Port 443](#listening-on-port-443), below).
> **Warning**: it is very difficult, if not impossible, to revert the effect of HSTS before the entry stored in the browser expires! Consider using a short `:expires` value initially, and increasing it to a large value (e.g. 31536000 seconds for 1 year) after testing.
>
>
The Strict-Transport-Security header can be disabled altogether by setting `hsts: false` in the [`Plug.SSL`](plug.ssl) options.
Encrypted Keys
---------------
To protect the private key on disk it is best stored in encrypted PEM format, protected by a password. When configuring a Plug server with an encrypted private key, specify the password using the `:password` option:
```
Plug.Cowboy.https MyApp.MyPlug, [],
port: 8443,
certfile: "/etc/letsencrypt/live/example.net/cert.pem",
keyfile: "/etc/letsencrypt/live/example.net/privkey_aes.pem",
cacertfile: "/etc/letsencrypt/live/example.net/chain.pem",
password: "SECRET"
```
To encrypt an existing PEM-encoded RSA key use the OpenSSL CLI: `openssl rsa -in privkey.pem -out privkey_aes.pem -aes128`. Use `ec` instead of `rsa` when using an ECDSA certificate. Don't forget to securely erase the unencrypted copy afterwards! Best practice would be to encrypt the file immediately during initial key generation: please refer to the instructions provided by the CA.
> Note: at the time of writing, Erlang/OTP does not support keys encrypted with AES-256. The OpenSSL command in the previous paragraph can also be used to convert an AES-256 encrypted key to AES-128.
>
>
Passing DER Binaries
---------------------
Sometimes it is preferable to not store the private key on disk at all. Instead, the private key might be passed to the application using an environment variable or retrieved from a key store such as Vault.
In such cases it is possible to pass the private key directly, using the `:key` parameter. For example, assuming an RSA private key is available in the PRIVKEY environment variable in Base64 encoded DER format, the key may be set as follows:
```
der = System.get_env("PRIVKEY") |> Base.decode64!
Plug.Cowboy.https MyApp.MyPlug, [],
port: 8443,
key: {:RSAPrivateKey, der},
#....
```
Note that reading environment variables in Mix config files only works when starting the application using Mix, e.g. in a development environment. In production, a different approach is needed for runtime configuration, but this is out of scope for the current document.
The certificate and CA chain can also be specified using DER binaries, using the `:cert` and `:cacerts` options, but this is best avoided. The use of PEM files has been tested much more thoroughly with the Erlang/OTP `:ssl` application, and there have been a number of issues with DER binary certificates in the past.
Custom Diffie-Hellman Parameters
---------------------------------
It is recommended to generate a custom set of Diffie-Hellman parameters, to be used for the DHE key exchange. Use the following OpenSSL CLI command to create a `dhparam.pem` file:
`openssl dhparam -out dhparams.pem 4096`
On a slow machine (e.g. a cheap VPS) this may take several hours. You may want to run the command on a strong machine and copy the file over to the target server: the file does not need to be kept secret. It is best practice to rotate the file periodically.
Pass the (relative or absolute) path using the `:dhfile` option:
```
Plug.Cowboy.https MyApp.MyPlug, [],
port: 8443,
cipher_suite: :strong,
certfile: "priv/cert/selfsigned.pem",
keyfile: "priv/cert/selfsigned_key.pem",
dhfile: "priv/cert/dhparams.pem",
otp_app: :my_app
```
If no custom parameters are specified, Erlang's `:ssl` uses its built-in defaults. Since OTP 19 this has been the 2048-bit 'group 14' from RFC3526.
Renewing Certificates
----------------------
Whenever a certificate is about to expire, when the contents of the certificate have been updated, or when the certificate is 're-keyed', the HTTPS server needs to be updated with the new certificate and/or key.
When using the `:certfile` and `:keyfile` parameters to reference PEM files on disk, replacing the certificate and key is as simple as overwriting the files. Erlang's `:ssl` application periodically reloads any referenced files, with changes taking effect in subsequent handshakes. It may be best to use symbolic links that point to versioned copies of the files, to allow for quick rollback in case of problems.
Note that there is a potential race condition when both the certificate and the key need to be replaced at the same time: if the `:ssl` application reloads one file before the other file is updated, the partial update can leave the HTTPS server with a mismatched private key. This can be avoiding by placing the private key in the same PEM file as the certificate, and omitting the `:keyfile` option. This configuration allows atomic updates, and it works because `:ssl` looks for a private key entry in the `:certfile` PEM file if no `:key` or `:keyfile` option is specified.
While it is possible to update the DER binaries passed in the `:cert` or `:key` options (as well as any other TLS protocol parameters) at runtime, this requires knowledge of the internals of the Plug adapter being used, and is therefore beyond the scope of this document.
Listening on Port 443
----------------------
By default clients expect HTTPS servers to listen on port 443. It is possible to specify a different port in HTTPS URLs, but for public servers it is often preferable to stick to the default. In particular, HSTS requires that the site be reachable on port 443 using HTTPS.
This presents a problem, however: only privileged processes can bind to TCP port numbers under 1024, and it is bad idea to run the application as 'root'.
Leaving aside solutions that rely on external network elements, such as load balancers, there are several solutions on typical Linux servers:
* Deploy a reverse proxy or load balancer process, such as Nginx or HAProxy (see [Offloading TLS](#offloading-tls), below); the proxy listens on port 443 and passes the traffic to the Elixir application running on an unprivileged port
* Create an IPTables rule to forward packets arriving on port 443 to the port on which the Elixir application is running
* Give the Erlang/OTP runtime (that is, the BEAM VM executable) permission to bind to privileged ports using 'setcap', e.g. `sudo setcap 'cap_net_bind_service=+ep' /usr/lib/erlang/erts-10.1/bin/beam.smp`; update the path as necessary, and remember to run the command again after Erlang upgrades
* Use a tool such as 'authbind' to give an unprivileged user/group permission to bind to specific ports
This is not intended to be an exhaustive list, as this topic is actually a bit beyond the scope of the current document. The issue is a generic one, not specific to Erlang/Elixir, and further explanations can be found online.
Offloading TLS
---------------
So far this document has focused on configuring Plug to handle TLS within the application. Some people instead prefer to terminate TLS in a proxy or load balancer deployed in front of the Plug application.
### Pros and Cons
Offloading might be done to achieve higher throughput, or to stick to the more widely used OpenSSL implementation of the TLS protocol. The Erlang/OTP implementation depends on OpenSSL for the underlying cryptography, but it implements its own message framing and protocol state machine. While it is not clear that one implementation is inherently more secure than the other, just patching OpenSSL along with everybody else in case of vulnerabilities might give peace of mind, compared to than having to research the implications on the Erlang/OTP implementation.
On the other hand, the proxy solution might not support end-to-end HTTP 2, limiting the benefits of the new protocol. It can also introduce operational complexities and new resource constraints, especially for long-lived connections such as WebSockets.
### Plug Configuration Impact
When using TLS offloading it may be necessary to make some configuration changes to the application.
[`Plug.SSL`](plug.ssl) takes on another important role when using TLS offloading: it can update the `:scheme` and `:port` fields in the [`Plug.Conn`](plug.conn) struct based on an HTTP header (e.g. 'X-Forwarded-Proto'), to reflect the actual protocol used by the client (HTTP or HTTPS). It is very important that the `:scheme` field properly reflects the use of HTTPS, even if the connection between the proxy and the application uses plain HTTP, because cookies set by [`Plug.Session`](plug.session) and [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4) by default set the 'secure' cookie flag only if `:scheme` is set to `:https`! When relying on this default behaviour it is essential that [`Plug.SSL`](plug.ssl) is included in the Plug pipeline, that its `:rewrite_on` option is set correctly, and that the proxy sets the appropriate header.
The `:remote_ip` field in the [`Plug.Conn`](plug.conn) struct by default contains the network peer IP address. Terminating TLS in a separate process or network element typically masks the actual client IP address from the Elixir application. If proxying is done at the HTTP layer, the original client IP address is often inserted into an HTTP header, e.g. 'X-Forwarded-For'. There are Plug packages available to extract the client IP from such a header and update the `:remote_ip` field.
> **Warning**: ensure that clients cannot spoof their IP address by including this header in their original request, by filtering such headers in the proxy!
>
>
For solutions that operate below the HTTP layer, e.g. using HAProxy, the client IP address can sometimes be passed through the 'PROXY protocol'. Extracting this information must be handled by the Plug adapter. Please refer to the Plug adapter documentation for further information.
Converting Certificates and Keys
---------------------------------
When certificate and/or key files are not in provided in PEM format they can usually be converted using the OpenSSL CLI. This section describes some common formats and the associated OpenSSL commands to convert to PEM.
### From DER to PEM
DER-encoded files contain binary data. Common file extensions are `.crt` for certificates and `.key` for keys.
To convert a single DER-encoded certificate to PEM format: `openssl x509 -in server.crt -inform der -out cert.pem`
To convert an RSA private key from DER to PEM format: `openssl rsa -in privkey.der -inform der -out privkey.pem`. If the private key is a Elliptic Curve key, for use with an ECDSA certificate, replace `rsa` with `ec`. You may want to add the `-aes128` argument to produce an encrypted, password protected PEM file.
### From PKCS#12 to PEM
The PKCS#12 format is a container format containing one or more certificates and/or encrypted keys. Such files typically have a `.p12` extension.
To extract all certificates from a PKCS#12 file to a PEM file: `openssl pkcs12 -in server.p12 -nokeys -out fullchain.pem`. The resulting file contains all certificates from the input file, typically the server certificate and any CA certificates that make up the CA chain. You can split the file into separate `cert.pem` and `chain.pem` files using a text editor, or you can just pass `certfile: fullchain.pem` to the HTTPS adapter.
To extract a private key from a PKCS#12 file to a PEM file: `openssl pkcs12 -in server.p12 -nocerts -nodes -out privkey.pem`. You may want to replace the `-nodes` argument with `-aes128` to produce an encrypted, password protected PEM file.
[← Previous Page Plug](readme)
| programming_docs |
phoenix Plug.TimeoutError exception Plug.TimeoutError exception
============================
Timeout while waiting for the request.
phoenix Plug.Router Plug.Router
============
A DSL to define a routing algorithm that works with Plug.
It provides a set of macros to generate routes. For example:
```
defmodule AppRouter do
use Plug.Router
plug :match
plug :dispatch
get "/hello" do
send_resp(conn, 200, "world")
end
match _ do
send_resp(conn, 404, "oops")
end
end
```
Each route receives a `conn` variable containing a [`Plug.Conn`](plug.conn) struct and it needs to return a connection, as per the Plug spec. A catch-all `match` is recommended to be defined as in the example above, otherwise routing fails with a function clause error.
The router is itself a plug, which means it can be invoked as:
```
AppRouter.call(conn, AppRouter.init([]))
```
Each [`Plug.Router`](plug.router#content) has a plug pipeline, defined by [`Plug.Builder`](plug.builder), and by default it requires two plugs: `:match` and `:dispatch`. `:match` is responsible for finding a matching route which is then forwarded to `:dispatch`. This means users can easily hook into the router mechanism and add behaviour before match, before dispatch, or after both. See the [`Plug.Builder`](plug.builder) module for more information.
Routes
-------
```
get "/hello" do
send_resp(conn, 200, "world")
end
```
In the example above, a request will only match if it is a `GET` request and the route is "/hello". The supported HTTP methods are `get`, `post`, `put`, `patch`, `delete` and `options`.
A route can also specify parameters which will then be available in the function body:
```
get "/hello/:name" do
send_resp(conn, 200, "hello #{name}")
end
```
This means the name can also be used in guards:
```
get "/hello/:name" when name in ~w(foo bar) do
send_resp(conn, 200, "hello #{name}")
end
```
The `:name` parameter will also be available in the function body as `conn.params["name"]` and `conn.path_params["name"]`.
The identifier always starts with `:` and must be followed by letters, numbers, and underscores, like any Elixir variable. It is possible for identifiers to be either prefixed or suffixed by other words. For example, you can include a suffix such as a dot delimited file extension:
```
get "/hello/:name.json" do
send_resp(conn, 200, "hello #{name}")
end
```
The above will match `/hello/foo.json` but not `/hello/foo`. Other delimiters such as `-`, `@` may be used to denote suffixes.
Routes allow for globbing which will match the remaining parts of a route. A glob match is done with the `*` character followed by the variable name. Typically you prefix the variable name with underscore to discard it:
```
get "/hello/*_rest" do
send_resp(conn, 200, "matches all routes starting with /hello")
end
```
But you can also assign the glob to any variable. The contents will always be a list:
```
get "/hello/*glob" do
send_resp(conn, 200, "route after /hello: #{inspect glob}")
end
```
Opposite to `:identifiers`, globs do not allow prefix nor suffix matches.
Finally, a general `match` function is also supported:
```
match "/hello" do
send_resp(conn, 200, "world")
end
```
A `match` will match any route regardless of the HTTP method. Check [`match/3`](#match/3) for more information on how route compilation works and a list of supported options.
Parameter Parsing
------------------
Handling request data can be done through the [`Plug.Parsers`](plug.parsers#content) plug. It provides support for parsing URL-encoded, form-data, and JSON data as well as providing a behaviour that others parsers can adopt.
Here is an example of [`Plug.Parsers`](plug.parsers) can be used in a [`Plug.Router`](plug.router#content) router to parse the JSON-encoded body of a POST request:
```
defmodule AppRouter do
use Plug.Router
plug :match
plug Plug.Parsers,
parsers: [:json],
pass: ["application/json"],
json_decoder: Jason
plug :dispatch
post "/hello" do
IO.inspect conn.body_params # Prints JSON POST body
send_resp(conn, 200, "Success!")
end
end
```
It is important that [`Plug.Parsers`](plug.parsers) is placed before the `:dispatch` plug in the pipeline, otherwise the matched clause route will not receive the parsed body in its [`Plug.Conn`](plug.conn) argument when dispatched.
[`Plug.Parsers`](plug.parsers) can also be plugged between `:match` and `:dispatch` (like in the example above): this means that [`Plug.Parsers`](plug.parsers) will run only if there is a matching route. This can be useful to perform actions such as authentication *before* parsing the body, which should only be parsed if a route matches afterwards.
Error handling
---------------
In case something goes wrong in a request, the router by default will crash, without returning any response to the client. This behaviour can be configured in two ways, by using two different modules:
* [`Plug.ErrorHandler`](plug.errorhandler) - allows the developer to customize exactly which page is sent to the client via the `handle_errors/2` function;
* [`Plug.Debugger`](plug.debugger) - automatically shows debugging and request information about the failure. This module is recommended to be used only in a development environment.
Here is an example of how both modules could be used in an application:
```
defmodule AppRouter do
use Plug.Router
if Mix.env == :dev do
use Plug.Debugger
end
use Plug.ErrorHandler
plug :match
plug :dispatch
get "/hello" do
send_resp(conn, 200, "world")
end
defp handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
send_resp(conn, conn.status, "Something went wrong")
end
end
```
Passing data between routes and plugs
--------------------------------------
It is also possible to assign data to the [`Plug.Conn`](plug.conn) that will be available to any plug invoked after the `:match` plug. This is very useful if you want a matched route to customize how later plugs will behave.
You can use `:assigns` (which contains user data) or `:private` (which contains library/framework data) for this. For example:
```
get "/hello", assigns: %{an_option: :a_value} do
send_resp(conn, 200, "world")
end
```
In the example above, `conn.assigns[:an_option]` will be available to all plugs invoked after `:match`. Such plugs can read from `conn.assigns` (or `conn.private`) to configure their behaviour based on the matched route.
`use` options
--------------
All of the options given to `use Plug.Router` are forwarded to [`Plug.Builder`](plug.builder). See the [`Plug.Builder`](plug.builder) module for more information.
Telemetry
----------
The router emits the following telemetry events:
* `[:plug, :router_dispatch, :start]` - dispatched before dispatching to a matched route
+ Measurement: `%{system_time: System.system_time}`
+ Metadata: `%{telemetry_span_context: term(), conn: Plug.Conn.t, route: binary, router: module}`
* `[:plug, :router_dispatch, :exception]` - dispatched after exceptions on dispatching a route
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{telemetry_span_context: term(), conn: Plug.Conn.t, route: binary, router: module, kind: :throw | :error | :exit, reason: term(), stacktrace: list()}`
* `[:plug, :router_dispatch, :stop]` - dispatched after successfully dispatching a matched route
+ Measurement: `%{duration: native_time}`
+ Metadata: `%{telemetry_span_context: term(), conn: Plug.Conn.t, route: binary, router: module}`
Summary
========
Functions
----------
[delete(path, options, contents \\ [])](#delete/3) Dispatches to the path only if the request is a DELETE request. See [`match/3`](#match/3) for more examples.
[forward(path, options)](#forward/2) Forwards requests to another Plug. The `path_info` of the forwarded connection will exclude the portion of the path specified in the call to `forward`. If the path contains any parameters, those will be available in the target Plug in `conn.params` and `conn.path_params`.
[get(path, options, contents \\ [])](#get/3) Dispatches to the path only if the request is a GET request. See [`match/3`](#match/3) for more examples.
[head(path, options, contents \\ [])](#head/3) Dispatches to the path only if the request is a HEAD request. See [`match/3`](#match/3) for more examples.
[match(path, options, contents \\ [])](#match/3) Main API to define routes.
[match\_path(conn)](#match_path/1) Returns the path of the route that the request was matched to.
[options(path, options, contents \\ [])](#options/3) Dispatches to the path only if the request is an OPTIONS request. See [`match/3`](#match/3) for more examples.
[patch(path, options, contents \\ [])](#patch/3) Dispatches to the path only if the request is a PATCH request. See [`match/3`](#match/3) for more examples.
[post(path, options, contents \\ [])](#post/3) Dispatches to the path only if the request is a POST request. See [`match/3`](#match/3) for more examples.
[put(path, options, contents \\ [])](#put/3) Dispatches to the path only if the request is a PUT request. See [`match/3`](#match/3) for more examples.
Functions
==========
### delete(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L394)
Dispatches to the path only if the request is a DELETE request. See [`match/3`](#match/3) for more examples.
### forward(path, options)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L447)
Forwards requests to another Plug. The `path_info` of the forwarded connection will exclude the portion of the path specified in the call to `forward`. If the path contains any parameters, those will be available in the target Plug in `conn.params` and `conn.path_params`.
#### Options
`forward` accepts the following options:
* `:to` - a Plug the requests will be forwarded to.
* `:init_opts` - the options for the target Plug. It is the preferred mechanism for passing options to the target Plug.
* `:host` - a string representing the host or subdomain, exactly like in [`match/3`](#match/3).
* `:private` - values for `conn.private`, exactly like in [`match/3`](#match/3).
* `:assigns` - values for `conn.assigns`, exactly like in [`match/3`](#match/3).
If `:init_opts` is undefined, then all remaining options are passed to the target plug.
#### Examples
```
forward "/users", to: UserRouter
```
Assuming the above code, a request to `/users/sign_in` will be forwarded to the `UserRouter` plug, which will receive what it will see as a request to `/sign_in`.
```
forward "/foo/:bar/qux", to: FooPlug
```
Here, a request to `/foo/BAZ/qux` will be forwarded to the `FooPlug` plug, which will receive what it will see as a request to `/`, and `conn.params["bar"]` will be set to `"BAZ"`.
Some other examples:
```
forward "/foo/bar", to: :foo_bar_plug, host: "foobar."
forward "/baz", to: BazPlug, init_opts: [plug_specific_option: true]
```
### get(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L354)
Dispatches to the path only if the request is a GET request. See [`match/3`](#match/3) for more examples.
### head(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L362)
Dispatches to the path only if the request is a HEAD request. See [`match/3`](#match/3) for more examples.
### match(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L346)
Main API to define routes.
It accepts an expression representing the path and many options allowing the match to be configured.
The route can dispatch either to a function body or a Plug module.
#### Examples
```
match "/foo/bar", via: :get do
send_resp(conn, 200, "hello world")
end
match "/baz", to: MyPlug, init_opts: [an_option: :a_value]
```
#### Options
[`match/3`](#match/3) and the other route macros accept the following options:
* `:host` - the host which the route should match. Defaults to `nil`, meaning no host match, but can be a string like "example.com" or a string ending with ".", like "subdomain." for a subdomain match.
* `:private` - assigns values to `conn.private` for use in the match
* `:assigns` - assigns values to `conn.assigns` for use in the match
* `:via` - matches the route against some specific HTTP method(s) specified as an atom, like `:get` or `:put`, or a list, like `[:get, :post]`.
* `:do` - contains the implementation to be invoked in case the route matches.
* `:to` - a Plug that will be called in case the route matches.
* `:init_opts` - the options for the target Plug given by `:to`.
A route should specify only one of `:do` or `:to` options.
### match\_path(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L299)
```
@spec match_path(Plug.Conn.t()) :: String.t()
```
Returns the path of the route that the request was matched to.
### options(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L402)
Dispatches to the path only if the request is an OPTIONS request. See [`match/3`](#match/3) for more examples.
### patch(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L386)
Dispatches to the path only if the request is a PATCH request. See [`match/3`](#match/3) for more examples.
### post(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L370)
Dispatches to the path only if the request is a POST request. See [`match/3`](#match/3) for more examples.
### put(path, options, contents \\ [])[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/router.ex#L378)
Dispatches to the path only if the request is a PUT request. See [`match/3`](#match/3) for more examples.
phoenix Plug Plug
=====
Plug is:
1. A specification for composing web applications with functions
2. Connection adapters for different web servers in the Erlang VM
[Documentation for Plug is available online](http://hexdocs.pm/plug/).
Installation
-------------
In order to use Plug, you need a webserver and its bindings for Plug. The Cowboy webserver is the most common one, which can be installed by adding `plug_cowboy` as a dependency to your `mix.exs`:
```
def deps do
[
{:plug_cowboy, "~> 2.0"}
]
end
```
Hello world
------------
```
defmodule MyPlug do
import Plug.Conn
def init(options) do
# initialize options
options
end
def call(conn, _opts) do
conn
|> put_resp_content_type("text/plain")
|> send_resp(200, "Hello world")
end
end
```
The snippet above shows a very simple example on how to use Plug. Save that snippet to a file and run it inside the plug application with:
```
$ iex -S mix
iex> c "path/to/file.ex"
[MyPlug]
iex> {:ok, _} = Plug.Cowboy.http MyPlug, []
{:ok, #PID<...>}
```
Access <http://localhost:4000/> and we are done! For now, we have directly started the server in our terminal but, for production deployments, you likely want to start it in your supervision tree. See the [Supervised handlers](#supervised-handlers) section next.
Supervised handlers
--------------------
On a production system, you likely want to start your Plug pipeline under your application's supervision tree. Start a new Elixir project with the `--sup` flag:
```
$ mix new my_app --sup
```
and then update `lib/my_app/application.ex` as follows:
```
defmodule MyApp.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
{Plug.Cowboy, scheme: :http, plug: MyPlug, options: [port: 4001]}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
```
Now run `mix run --no-halt` and it will start your application with a web server running at `localhost:4001`.
Supported Versions
-------------------
| Branch | Support |
| --- | --- |
| v1.13 | Bug fixes |
| v1.12 | Security patches only |
| v1.11 | Security patches only |
| v1.10 | Security patches only |
| v1.9 | Security patches only |
| v1.8 | Security patches only |
| v1.7 | Unsupported from 01/2022 |
| v1.6 | Unsupported from 01/2022 |
| v1.5 | Unsupported from 03/2021 |
| v1.4 | Unsupported from 12/2018 |
| v1.3 | Unsupported from 12/2018 |
| v1.2 | Unsupported from 06/2018 |
| v1.1 | Unsupported from 01/2018 |
| v1.0 | Unsupported from 05/2017 |
The [`Plug.Conn`](plug.conn) struct
------------------------------------
In the hello world example, we defined our first plug. What is a plug after all?
A plug takes two shapes. A function plug receives a connection and a set of options as arguments and returns the connection:
```
def hello_world_plug(conn, _opts) do
conn
|> put_resp_content_type("text/plain")
|> send_resp(200, "Hello world")
end
```
A module plug implements an `init/1` function to initialize the options and a `call/2` function which receives the connection and initialized options and returns the connection:
```
defmodule MyPlug do
def init([]), do: false
def call(conn, _opts), do: conn
end
```
As per the specification above, a connection is represented by the [`Plug.Conn`](plug.conn) struct:
```
%Plug.Conn{
host: "www.example.com",
path_info: ["bar", "baz"],
...
}
```
Data can be read directly from the connection and also pattern matched on. Manipulating the connection often happens with the use of the functions defined in the [`Plug.Conn`](plug.conn) module. In our example, both `put_resp_content_type/2` and `send_resp/3` are defined in [`Plug.Conn`](plug.conn).
Remember that, as everything else in Elixir, **a connection is immutable**, so every manipulation returns a new copy of the connection:
```
conn = put_resp_content_type(conn, "text/plain")
conn = send_resp(conn, 200, "ok")
conn
```
Finally, keep in mind that a connection is a **direct interface to the underlying web server**. When you call `send_resp/3` above, it will immediately send the given status and body back to the client. This makes features like streaming a breeze to work with.
[`Plug.Router`](plug.router)
-----------------------------
To write a "router" plug that dispatches based on the path and method of incoming requests, Plug provides [`Plug.Router`](plug.router):
```
defmodule MyRouter do
use Plug.Router
plug :match
plug :dispatch
get "/hello" do
send_resp(conn, 200, "world")
end
forward "/users", to: UsersRouter
match _ do
send_resp(conn, 404, "oops")
end
end
```
The router is a plug. Not only that: it contains its own plug pipeline too. The example above says that when the router is invoked, it will invoke the `:match` plug, represented by a local (imported) `match/2` function, and then call the `:dispatch` plug which will execute the matched code.
Plug ships with many plugs that you can add to the router plug pipeline, allowing you to plug something before a route matches or before a route is dispatched to. For example, if you want to add logging to the router, just do:
```
plug Plug.Logger
plug :match
plug :dispatch
```
Note [`Plug.Router`](plug.router) compiles all of your routes into a single function and relies on the Erlang VM to optimize the underlying routes into a tree lookup, instead of a linear lookup that would instead match route-per-route. This means route lookups are extremely fast in Plug!
This also means that a catch all `match` block is recommended to be defined as in the example above, otherwise routing fails with a function clause error (as it would in any regular Elixir function).
Each route needs to return the connection as per the Plug specification. See the [`Plug.Router`](plug.router) docs for more information.
Testing plugs
--------------
Plug ships with a [`Plug.Test`](plug.test) module that makes testing your plugs easy. Here is how we can test the router from above (or any other plug):
```
defmodule MyPlugTest do
use ExUnit.Case, async: true
use Plug.Test
@opts MyRouter.init([])
test "returns hello world" do
# Create a test connection
conn = conn(:get, "/hello")
# Invoke the plug
conn = MyRouter.call(conn, @opts)
# Assert the response and status
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body == "world"
end
end
```
Available plugs
----------------
This project aims to ship with different plugs that can be re-used across applications:
* [`Plug.BasicAuth`](plug.basicauth) - provides Basic HTTP authentication;
* [`Plug.CSRFProtection`](plug.csrfprotection) - adds Cross-Site Request Forgery protection to your application. Typically required if you are using [`Plug.Session`](plug.session);
* [`Plug.Head`](plug.head) - converts HEAD requests to GET requests;
* [`Plug.Logger`](plug.logger) - logs requests;
* [`Plug.MethodOverride`](plug.methodoverride) - overrides a request method with one specified in the request parameters;
* [`Plug.Parsers`](plug.parsers) - responsible for parsing the request body given its content-type;
* [`Plug.RequestId`](plug.requestid) - sets up a request ID to be used in logs;
* [`Plug.RewriteOn`](plug.rewriteon) - rewrite the request's host/port/protocol from `x-forwarded-*` headers;
* [`Plug.Session`](plug.session) - handles session management and storage;
* [`Plug.SSL`](plug.ssl) - enforces requests through SSL;
* [`Plug.Static`](plug.static) - serves static files;
* [`Plug.Telemetry`](plug.telemetry) - instruments the plug pipeline with `:telemetry` events;
You can go into more details about each of them [in our docs](http://hexdocs.pm/plug/).
Helper modules
---------------
Modules that can be used after you use [`Plug.Router`](plug.router) or [`Plug.Builder`](plug.builder) to help development:
* [`Plug.Debugger`](plug.debugger) - shows a helpful debugging page every time there is a failure in a request;
* [`Plug.ErrorHandler`](plug.errorhandler) - allows developers to customize error pages in case of crashes instead of sending a blank one;
Contributing
-------------
We welcome everyone to contribute to Plug and help us tackle existing issues!
Use the [issue tracker](https://github.com/elixir-plug/plug/issues) for bug reports or feature requests. Open a [pull request](https://github.com/elixir-plug/plug/pulls) when you are ready to contribute. When submitting a pull request you should not update the `CHANGELOG.md`.
If you are planning to contribute documentation, [please check our best practices for writing documentation](https://hexdocs.pm/elixir/writing-documentation.html).
Finally, remember all interactions in our official spaces follow our [Code of Conduct](https://github.com/elixir-lang/elixir/blob/master/CODE_OF_CONDUCT.md).
License
--------
Plug source code is released under Apache License 2.0. Check LICENSE file for more information.
[← Previous Page API Reference](api-reference) [Next Page → HTTPS](https)
| programming_docs |
phoenix Plug.Conn.InvalidHeaderError exception Plug.Conn.InvalidHeaderError exception
=======================================
Error raised when trying to send a header that has errors, for example:
* the header key contains uppercase chars
* the header value contains newlines \n
phoenix Plug.Head Plug.Head
==========
A Plug to convert `HEAD` requests to `GET` requests.
Examples
---------
```
Plug.Head.call(conn, [])
```
phoenix Plug.Parsers.JSON Plug.Parsers.JSON
==================
Parses JSON request body.
JSON documents that aren't maps (arrays, strings, numbers, etc) are parsed into a `"_json"` key to allow proper param merging.
An empty request body is parsed as an empty map.
Options
--------
All options supported by [`Plug.Conn.read_body/2`](plug.conn#read_body/2) are also supported here. They are repeated here for convenience:
* `:length` - sets the maximum number of bytes to read from the request, defaults to 8\_000\_000 bytes
* `:read_length` - sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to 1\_000\_000 bytes
* `:read_timeout` - sets the timeout for each socket read, defaults to 15\_000ms
So by default, [`Plug.Parsers`](plug.parsers) will read 1\_000\_000 bytes at a time from the socket with an overall limit of 8\_000\_000 bytes.
phoenix Plug.Conn.Status Plug.Conn.Status
=================
Conveniences for working with status codes.
Summary
========
Functions
----------
[code(integer\_or\_atom)](#code/1) Returns the status code given an integer or a known atom.
[reason\_atom(code)](#reason_atom/1) Returns the atom for given integer.
[reason\_phrase(integer)](#reason_phrase/1) Functions
==========
### code(integer\_or\_atom)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/status.ex#L112)
```
@spec code(integer() | atom()) :: integer()
```
Returns the status code given an integer or a known atom.
#### Known status codes
The following status codes can be given as atoms with their respective value shown next:
* `:continue` - 100
* `:switching_protocols` - 101
* `:processing` - 102
* `:early_hints` - 103
* `:ok` - 200
* `:created` - 201
* `:accepted` - 202
* `:non_authoritative_information` - 203
* `:no_content` - 204
* `:reset_content` - 205
* `:partial_content` - 206
* `:multi_status` - 207
* `:already_reported` - 208
* `:im_used` - 226
* `:multiple_choices` - 300
* `:moved_permanently` - 301
* `:found` - 302
* `:see_other` - 303
* `:not_modified` - 304
* `:use_proxy` - 305
* `:switch_proxy` - 306
* `:temporary_redirect` - 307
* `:permanent_redirect` - 308
* `:bad_request` - 400
* `:unauthorized` - 401
* `:payment_required` - 402
* `:forbidden` - 403
* `:not_found` - 404
* `:method_not_allowed` - 405
* `:not_acceptable` - 406
* `:proxy_authentication_required` - 407
* `:request_timeout` - 408
* `:conflict` - 409
* `:gone` - 410
* `:length_required` - 411
* `:precondition_failed` - 412
* `:request_entity_too_large` - 413
* `:request_uri_too_long` - 414
* `:unsupported_media_type` - 415
* `:requested_range_not_satisfiable` - 416
* `:expectation_failed` - 417
* `:im_a_teapot` - 418
* `:misdirected_request` - 421
* `:unprocessable_entity` - 422
* `:locked` - 423
* `:failed_dependency` - 424
* `:too_early` - 425
* `:upgrade_required` - 426
* `:precondition_required` - 428
* `:too_many_requests` - 429
* `:request_header_fields_too_large` - 431
* `:unavailable_for_legal_reasons` - 451
* `:internal_server_error` - 500
* `:not_implemented` - 501
* `:bad_gateway` - 502
* `:service_unavailable` - 503
* `:gateway_timeout` - 504
* `:http_version_not_supported` - 505
* `:variant_also_negotiates` - 506
* `:insufficient_storage` - 507
* `:loop_detected` - 508
* `:not_extended` - 510
* `:network_authentication_required` - 511
### reason\_atom(code)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/status.ex#L135)
```
@spec reason_atom(integer()) :: atom()
```
Returns the atom for given integer.
See [`code/1`](#code/1) for the mapping.
### reason\_phrase(integer)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/status.ex#L147)
```
@spec reason_phrase(integer()) :: String.t()
```
phoenix Plug.Static Plug.Static
============
A plug for serving static assets.
It requires two options:
* `:at` - the request path to reach for static assets. It must be a string.
* `:from` - the file system path to read static assets from. It can be either: a string containing a file system path, an atom representing the application name (where assets will be served from `priv/static`), a tuple containing the application name and the directory to serve assets from (besides `priv/static`), or an MFA tuple.
The preferred form is to use `:from` with an atom or tuple, since it will make your application independent from the starting directory. For example, if you pass:
```
plug Plug.Static, from: "priv/app/path"
```
Plug.Static will be unable to serve assets if you build releases or if you change the current directory. Instead do:
```
plug Plug.Static, from: {:app_name, "priv/app/path"}
```
If a static asset cannot be found, [`Plug.Static`](plug.static#content) simply forwards the connection to the rest of the pipeline.
Cache mechanisms
-----------------
[`Plug.Static`](plug.static#content) uses etags for HTTP caching. This means browsers/clients should cache assets on the first request and validate the cache on following requests, not downloading the static asset once again if it has not changed. The cache-control for etags is specified by the `cache_control_for_etags` option and defaults to `"public"`.
However, [`Plug.Static`](plug.static#content) also supports direct cache control by using versioned query strings. If the request query string starts with "?vsn=", [`Plug.Static`](plug.static#content) assumes the application is versioning assets and does not set the `ETag` header, meaning the cache behaviour will be specified solely by the `cache_control_for_vsn_requests` config, which defaults to `"public, max-age=31536000"`.
Options
--------
* `:encodings` - list of 2-ary tuples where first value is value of the `Accept-Encoding` header and second is extension of the file to be served if given encoding is accepted by client. Entries will be tested in order in list, so entries higher in list will be preferred. Defaults to: `[]`.
In addition to setting this value directly it supports 2 additional options for compatibility reasons:
+ `:brotli` - will append `{"br", ".br"}` to the encodings list.
+ `:gzip` - will append `{"gzip", ".gz"}` to the encodings list.Additional options will be added in the above order (Brotli takes preference over Gzip) to reflect older behaviour which was set due to fact that Brotli in general provides better compression ratio than Gzip.
* `:cache_control_for_etags` - sets the cache header for requests that use etags. Defaults to `"public"`.
* `:etag_generation` - specify a `{module, function, args}` to be used to generate an etag. The `path` of the resource will be passed to the function, as well as the `args`. If this option is not supplied, etags will be generated based off of file size and modification time. Note it is [recommended for the etag value to be quoted](https://tools.ietf.org/html/rfc7232#section-2.3), which Plug won't do automatically.
* `:cache_control_for_vsn_requests` - sets the cache header for requests starting with "?vsn=" in the query string. Defaults to `"public, max-age=31536000"`.
* `:only` - filters which requests to serve. This is useful to avoid file system access on every request when this plug is mounted at `"/"`. For example, if `only: ["images", "favicon.ico"]` is specified, only files in the "images" directory and the "favicon.ico" file will be served by [`Plug.Static`](plug.static#content). Note that [`Plug.Static`](plug.static#content) matches these filters against request uri and not against the filesystem. When requesting a file with name containing non-ascii or special characters, you should use urlencoded form. For example, you should write `only: ["file%20name"]` instead of `only: ["file name"]`. Defaults to `nil` (no filtering).
* `:only_matching` - a relaxed version of `:only` that will serve any request as long as one of the given values matches the given path. For example, `only_matching: ["images", "favicon"]` will match any request that starts at "images" or "favicon", be it "/images/foo.png", "/images-high/foo.png", "/favicon.ico" or "/favicon-high.ico". Such matches are useful when serving digested files at the root. Defaults to `nil` (no filtering).
* `:headers` - other headers to be set when serving static assets. Specify either an enum of key-value pairs or a `{module, function, args}` to return an enum. The `conn` will be passed to the function, as well as the `args`.
* `:content_types` - custom MIME type mapping. As a map with filename as key and content type as value. For example: `content_types: %{"apple-app-site-association" => "application/json"}`.
Examples
---------
This plug can be mounted in a [`Plug.Builder`](plug.builder) pipeline as follows:
```
defmodule MyPlug do
use Plug.Builder
plug Plug.Static,
at: "/public",
from: :my_app,
only: ~w(images robots.txt)
plug :not_found
def not_found(conn, _) do
send_resp(conn, 404, "not found")
end
end
```
phoenix Plug.Parsers.ParseError exception Plug.Parsers.ParseError exception
==================================
Error raised when the request body is malformed.
Summary
========
Functions
----------
[message(map)](#message/1) Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
Functions
==========
### message(map)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/parsers.ex#L40)
Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).
phoenix Plug.Test Plug.Test
==========
Conveniences for testing plugs.
This module can be used in your test cases, like this:
```
use ExUnit.Case, async: true
use Plug.Test
```
Using this module will:
* import all the functions from this module
* import all the functions from the [`Plug.Conn`](plug.conn) module
By default, Plug tests checks for invalid header keys, e.g. header keys which include uppercase letters, and raises a [`Plug.Conn.InvalidHeaderError`](plug.conn.invalidheadererror) when it finds one. To disable it, set `:validate_header_keys_during_test` to false on the app config.
```
config :plug, :validate_header_keys_during_test, false
```
Summary
========
Functions
----------
[conn(method, path, params\_or\_body \\ nil)](#conn/3) Creates a test connection.
[delete\_req\_cookie(conn, key)](#delete_req_cookie/2) Deletes a request cookie.
[init\_test\_session(conn, session)](#init_test_session/2) Initializes the session with the given contents.
[put\_http\_protocol(conn, http\_protocol)](#put_http_protocol/2) Puts the HTTP protocol.
[put\_peer\_data(conn, peer\_data)](#put_peer_data/2) Puts the peer data.
[put\_req\_cookie(conn, key, value)](#put_req_cookie/3) Puts a request cookie.
[recycle\_cookies(new\_conn, old\_conn)](#recycle_cookies/2) Moves cookies from a connection into a new connection for subsequent requests.
[sent\_informs(conn)](#sent_informs/1) Returns the informational requests that have been sent.
[sent\_pushes(conn)](#sent_pushes/1) Returns the assets that have been pushed.
[sent\_resp(conn)](#sent_resp/1) Returns the sent response.
Functions
==========
### conn(method, path, params\_or\_body \\ nil)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L65)
```
@spec conn(String.Chars.t(), binary(), params()) :: Plug.Conn.t()
```
Creates a test connection.
The request `method` and `path` are required arguments. `method` may be any value that implements [`to_string/1`](https://hexdocs.pm/elixir/Kernel.html#to_string/1) and it will be properly converted and normalized (e.g., `:get` or `"post"`).
The `path` is commonly the request path with optional query string but it may also be a complete URI. When a URI is given, the host and schema will be used as part of the request too.
The `params_or_body` field must be one of:
* `nil` - meaning there is no body;
* a binary - containing a request body. For such cases, `:headers` must be given as option with a content-type;
* a map or list - containing the parameters which will automatically set the content-type to multipart. The map or list may contain other lists or maps and all entries will be normalized to string keys;
#### Examples
```
conn(:get, "/foo?bar=10")
conn(:get, "/foo", %{bar: 10})
conn(:post, "/")
conn("patch", "/", "") |> put_req_header("content-type", "application/json")
```
### delete\_req\_cookie(conn, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L192)
```
@spec delete_req_cookie(Plug.Conn.t(), binary()) :: Plug.Conn.t()
```
Deletes a request cookie.
### init\_test\_session(conn, session)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L236)
```
@spec init_test_session(Plug.Conn.t(), %{optional(String.t() | atom()) => any()}) ::
Plug.Conn.t()
```
Initializes the session with the given contents.
If the session has already been initialized, the new contents will be merged with the previous ones.
### put\_http\_protocol(conn, http\_protocol)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L164)
Puts the HTTP protocol.
### put\_peer\_data(conn, peer\_data)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L173)
Puts the peer data.
### put\_req\_cookie(conn, key, value)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L183)
```
@spec put_req_cookie(Plug.Conn.t(), binary(), binary()) :: Plug.Conn.t()
```
Puts a request cookie.
### recycle\_cookies(new\_conn, old\_conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L212)
```
@spec recycle_cookies(Plug.Conn.t(), Plug.Conn.t()) :: Plug.Conn.t()
```
Moves cookies from a connection into a new connection for subsequent requests.
This function copies the cookie information in `old_conn` into `new_conn`, emulating multiple requests done by clients where cookies are always passed forward, and returns the new version of `new_conn`.
### sent\_informs(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L119)
Returns the informational requests that have been sent.
This function depends on gathering the messages sent by the test adapter when informational messages, such as an early hint, are sent. Calling this function will clear the informational request messages from the inbox for the process. To assert on multiple informs, the result of the function should be stored in a variable.
#### Examples
```
conn = conn(:get, "/foo", "bar=10")
informs = Plug.Test.sent_informs(conn)
assert {"/static/application.css", [{"accept", "text/css"}]} in informs
assert {"/static/application.js", [{"accept", "application/javascript"}]} in informs
```
### sent\_pushes(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L148)
Returns the assets that have been pushed.
This function depends on gathering the messages sent by the test adapter when assets are pushed. Calling this function will clear the pushed message from the inbox for the process. To assert on multiple pushes, the result of the function should be stored in a variable.
#### Examples
```
conn = conn(:get, "/foo?bar=10")
pushes = Plug.Test.sent_pushes(conn)
assert {"/static/application.css", [{"accept", "text/css"}]} in pushes
assert {"/static/application.js", [{"accept", "application/javascript"}]} in pushes
```
### sent\_resp(conn)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/test.ex#L76)
Returns the sent response.
This function is useful when the code being invoked crashes and there is a need to verify a particular response was sent, even with the crash. It returns a tuple with `{status, headers, body}`.
phoenix Plug.Telemetry Plug.Telemetry
===============
A plug to instrument the pipeline with `:telemetry` events.
When plugged, the event prefix is a required option:
```
plug Plug.Telemetry, event_prefix: [:my, :plug]
```
In the example above, two events will be emitted:
* `[:my, :plug, :start]` - emitted when the plug is invoked. The event carries the `system_time` as measurement. The metadata is the whole [`Plug.Conn`](plug.conn) under the `:conn` key and any leftover options given to the plug under `:options`.
* `[:my, :plug, :stop]` - emitted right before the request is sent. The event carries a single measurement, `:duration`, which is the monotonic time difference between the stop and start events. It has the same metadata as the start event, except the connection has been updated.
Note this plug measures the time between its invocation until a response is sent. The `:stop` event is not guaranteed to be emitted in all error cases, so this Plug cannot be used as a Telemetry span.
Time unit
----------
The `:duration` measurements are presented in the `:native` time unit. You can read more about it in the docs for [`System.convert_time_unit/3`](https://hexdocs.pm/elixir/System.html#convert_time_unit/3).
Example
--------
```
defmodule InstrumentedPlug do
use Plug.Router
plug :match
plug Plug.Telemetry, event_prefix: [:my, :plug]
plug Plug.Parsers, parsers: [:urlencoded, :multipart]
plug :dispatch
get "/" do
send_resp(conn, 200, "Hello, world!")
end
end
```
In this example, the stop event's `duration` includes the time it takes to parse the request, dispatch it to the correct handler, and execute the handler. The events are not emitted for requests not matching any handlers, since the plug is placed after the match plug.
phoenix Plug.Upload Plug.Upload
============
A server (a [`GenServer`](https://hexdocs.pm/elixir/GenServer.html) specifically) that manages uploaded files.
Uploaded files are stored in a temporary directory and removed from that directory after the process that requested the file dies.
During the request, files are represented with a [`Plug.Upload`](plug.upload#content) struct that contains three fields:
* `:path` - the path to the uploaded file on the filesystem
* `:content_type` - the content type of the uploaded file
* `:filename` - the filename of the uploaded file given in the request
**Note**: as mentioned in the documentation for [`Plug.Parsers`](plug.parsers), the `:plug` application has to be started in order to upload files and use the [`Plug.Upload`](plug.upload#content) module.
Security
---------
The `:content_type` and `:filename` fields in the [`Plug.Upload`](plug.upload#content) struct are client-controlled. These values should be validated, via file content inspection or similar, before being trusted.
Summary
========
Types
------
[t()](#t:t/0) Functions
----------
[child\_spec(init\_arg)](#child_spec/1) Returns a specification to start this module under a supervisor.
[give\_away(upload, to\_pid, from\_pid \\ self())](#give_away/3) Assign ownership of the given upload file to another process.
[random\_file!(prefix)](#random_file!/1) Requests a random file to be created in the upload directory with the given prefix. Raises on failure.
[random\_file(prefix)](#random_file/1) Requests a random file to be created in the upload directory with the given prefix.
Types
======
### t()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/upload.ex#L34)
```
@type t() :: %Plug.Upload{
content_type: binary() | nil,
filename: binary(),
path: Path.t()
}
```
Functions
==========
### child\_spec(init\_arg)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/upload.ex#L31)
Returns a specification to start this module under a supervisor.
See [`Supervisor`](https://hexdocs.pm/elixir/Supervisor.html).
### give\_away(upload, to\_pid, from\_pid \\ self())[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/upload.ex#L70)
```
@spec give_away(t() | binary(), pid(), pid()) :: :ok | {:error, :unknown_path}
```
Assign ownership of the given upload file to another process.
Useful if you want to do some work on an uploaded file in another process since it means that the file will survive the end of the request.
### random\_file!(prefix)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/upload.ex#L179)
```
@spec random_file!(binary()) :: binary() | no_return()
```
Requests a random file to be created in the upload directory with the given prefix. Raises on failure.
### random\_file(prefix)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/upload.ex#L53)
```
@spec random_file(binary()) ::
{:ok, binary()}
| {:too_many_attempts, binary(), pos_integer()}
| {:no_tmp, [binary()]}
```
Requests a random file to be created in the upload directory with the given prefix.
| programming_docs |
phoenix Plug.Parsers.MULTIPART Plug.Parsers.MULTIPART
=======================
Parses multipart request body.
Options
--------
All options supported by [`Plug.Conn.read_body/2`](plug.conn#read_body/2) are also supported here. They are repeated here for convenience:
* `:length` - sets the maximum number of bytes to read from the request, defaults to 8\_000\_000 bytes
* `:read_length` - sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to 1\_000\_000 bytes
* `:read_timeout` - sets the timeout for each socket read, defaults to 15\_000ms
So by default, [`Plug.Parsers`](plug.parsers) will read 1\_000\_000 bytes at a time from the socket with an overall limit of 8\_000\_000 bytes.
Besides the options supported by [`Plug.Conn.read_body/2`](plug.conn#read_body/2), the multipart parser also checks for:
* `:headers` - containing the same `:length`, `:read_length` and `:read_timeout` options which are used explicitly for parsing multipart headers
* `:validate_utf8` - specifies whether multipart body parts should be validated as utf8 binaries. Defaults to true
* `:multipart_to_params` - a MFA that receives the multipart headers and the connection and it must return a tuple of `{:ok, params, conn}`
Multipart to params
--------------------
Once all multiparts are collected, they must be converted to params and this can be customize with a MFA. The default implementation of this function is equivalent to:
```
def multipart_to_params(parts, conn) do
params =
for {name, _headers, body} <- parts,
name != nil,
reduce: %{} do
acc -> Plug.Conn.Query.decode_pair({name, body}, acc)
end
{:ok, params, conn}
end
```
As you can notice, it discards all multiparts without a name. If you want to keep the unnamed parts, you can store all of them under a known prefix, such as:
```
def multipart_to_params(parts, conn) do
params =
for {name, _headers, body} <- parts, reduce: %{} do
acc -> Plug.Conn.Query.decode_pair({name || "_parts[]", body}, acc)
end
{:ok, params, conn}
end
```
Dynamic configuration
----------------------
If you need to dynamically configure how [`Plug.Parsers.MULTIPART`](plug.parsers.multipart#content) behave, for example, based on the connection or another system parameter, one option is to create your own parser that wraps it:
```
defmodule MyMultipart do
@multipart Plug.Parsers.MULTIPART
def init(opts) do
opts
end
def parse(conn, "multipart", subtype, headers, opts) do
limit = [limit: System.fetch_env!("UPLOAD_LIMIT")]
opts = @multipart.init([limit: limit] ++ opts)
@multipart.parse(conn, "multipart", subtype, headers, opts)
end
def parse(conn, _type, _subtype, _headers, _opts) do
{:next, conn}
end
end
```
phoenix Plug.Session.ETS Plug.Session.ETS
=================
Stores the session in an in-memory ETS table.
This store does not create the ETS table; it expects that an existing named table with public properties is passed as an argument.
We don't recommend using this store in production as every session will be stored in ETS and never cleaned until you create a task responsible for cleaning up old entries.
Also, since the store is in-memory, it means sessions are not shared between servers. If you deploy to more than one machine, using this store is again not recommended.
This store, however, can be used as an example for creating custom storages, based on Redis, Memcached, or a database itself.
Options
--------
* `:table` - ETS table name (required)
For more information on ETS tables, visit the Erlang documentation at <http://www.erlang.org/doc/man/ets.html>.
Storage
--------
The data is stored in ETS in the following format:
```
{sid :: String.t, data :: map, timestamp :: :erlang.timestamp}
```
The timestamp is updated whenever there is a read or write to the table and it may be used to detect if a session is still active.
Examples
---------
```
# Create an ETS table when the application starts
:ets.new(:session, [:named_table, :public, read_concurrency: true])
# Use the session plug with the table name
plug Plug.Session, store: :ets, key: "sid", table: :session
```
phoenix Plug.CSRFProtection.InvalidCrossOriginRequestError exception Plug.CSRFProtection.InvalidCrossOriginRequestError exception
=============================================================
Error raised when non-XHR requests are used for Javascript responses.
phoenix Plug.Parsers.RequestTooLargeError exception Plug.Parsers.RequestTooLargeError exception
============================================
Error raised when the request is too large.
phoenix Plug.Conn.Utils Plug.Conn.Utils
================
Utilities for working with connection data
Summary
========
Types
------
[params()](#t:params/0) Functions
----------
[content\_type(binary)](#content_type/1) Parses content type (without wildcards).
[list(binary)](#list/1) Parses a comma-separated list of header values.
[media\_type(binary)](#media_type/1) Parses media types (with wildcards).
[params(t)](#params/1) Parses headers parameters.
[token(token)](#token/1) Parses a value as defined in [RFC-1341](http://www.w3.org/Protocols/rfc1341/4_Content-Type.html).
[validate\_utf8!(binary, exception, context)](#validate_utf8!/3) Validates the given binary is valid UTF-8.
Types
======
### params()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/utils.ex#L6)
```
@type params() :: %{optional(binary()) => binary()}
```
Functions
==========
### content\_type(binary)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/utils.ex#L119)
```
@spec content_type(binary()) ::
{:ok, type :: binary(), subtype :: binary(), params()} | :error
```
Parses content type (without wildcards).
It is similar to [`media_type/1`](#media_type/1) except wildcards are not accepted in the type nor in the subtype.
#### Examples
```
iex> content_type "x-sample/json; charset=utf-8"
{:ok, "x-sample", "json", %{"charset" => "utf-8"}}
iex> content_type "x-sample/json ; charset=utf-8 ; foo=bar"
{:ok, "x-sample", "json", %{"charset" => "utf-8", "foo" => "bar"}}
iex> content_type "\r\n text/plain;\r\n charset=utf-8\r\n"
{:ok, "text", "plain", %{"charset" => "utf-8"}}
iex> content_type "text/plain"
{:ok, "text", "plain", %{}}
iex> content_type "x/*"
:error
iex> content_type "*/*"
:error
```
### list(binary)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/utils.ex#L270)
```
@spec list(binary()) :: [binary()]
```
Parses a comma-separated list of header values.
#### Examples
```
iex> list("foo, bar")
["foo", "bar"]
iex> list("foobar")
["foobar"]
iex> list("")
[]
iex> list("empties, , are,, filtered")
["empties", "are", "filtered"]
```
### media\_type(binary)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/utils.ex#L55)
```
@spec media_type(binary()) ::
{:ok, type :: binary(), subtype :: binary(), params()} | :error
```
Parses media types (with wildcards).
Type and subtype are case insensitive while the sensitiveness of params depends on their keys and therefore are not handled by this parser.
Returns:
* `{:ok, type, subtype, map_of_params}` if everything goes fine
* `:error` if the media type isn't valid
#### Examples
```
iex> media_type "text/plain"
{:ok, "text", "plain", %{}}
iex> media_type "APPLICATION/vnd.ms-data+XML"
{:ok, "application", "vnd.ms-data+xml", %{}}
iex> media_type "text/*; q=1.0"
{:ok, "text", "*", %{"q" => "1.0"}}
iex> media_type "*/*; q=1.0"
{:ok, "*", "*", %{"q" => "1.0"}}
iex> media_type "x y"
:error
iex> media_type "*/html"
:error
iex> media_type "/"
:error
iex> media_type "x/y z"
:error
```
### params(t)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/utils.ex#L164)
```
@spec params(binary()) :: params()
```
Parses headers parameters.
Keys are case insensitive and downcased, invalid key-value pairs are discarded.
#### Examples
```
iex> params("foo=bar")
%{"foo" => "bar"}
iex> params(" foo=bar ")
%{"foo" => "bar"}
iex> params("FOO=bar")
%{"foo" => "bar"}
iex> params("Foo=bar; baz=BOING")
%{"foo" => "bar", "baz" => "BOING"}
iex> params("foo=BAR ; wat")
%{"foo" => "BAR"}
iex> params("foo=\"bar\"; baz=\"boing\"")
%{"foo" => "bar", "baz" => "boing"}
iex> params("foo=\"bar;\"; baz=\"boing\"")
%{"foo" => "bar;", "baz" => "boing"}
iex> params("=")
%{}
iex> params(";")
%{}
```
### token(token)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/utils.ex#L233)
```
@spec token(binary()) :: binary() | false
```
Parses a value as defined in [RFC-1341](http://www.w3.org/Protocols/rfc1341/4_Content-Type.html).
For convenience, trims whitespace at the end of the token. Returns `false` if the token is invalid.
#### Examples
```
iex> token("foo")
"foo"
iex> token("foo-bar")
"foo-bar"
iex> token("<foo>")
false
iex> token(~s["<foo>"])
"<foo>"
iex> token(~S["<f\oo>\"<b\ar>"])
"<foo>\"<bar>"
iex> token(~s["])
false
iex> token("foo ")
"foo"
iex> token("foo bar")
false
iex> token("")
false
iex> token(" ")
""
```
### validate\_utf8!(binary, exception, context)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/utils.ex#L281)
```
@spec validate_utf8!(binary(), module(), binary()) :: :ok | no_return()
```
Validates the given binary is valid UTF-8.
phoenix Plug.HTML Plug.HTML
==========
Conveniences for generating HTML.
Summary
========
Functions
----------
[html\_escape(data)](#html_escape/1) Escapes the given HTML to string.
[html\_escape\_to\_iodata(data)](#html_escape_to_iodata/1) Escapes the given HTML to iodata.
Functions
==========
### html\_escape(data)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/html.ex#L19)
```
@spec html_escape(String.t()) :: String.t()
```
Escapes the given HTML to string.
```
iex> Plug.HTML.html_escape("foo")
"foo"
iex> Plug.HTML.html_escape("<foo>")
"<foo>"
iex> Plug.HTML.html_escape("quotes: \" & \'")
"quotes: " & '"
```
### html\_escape\_to\_iodata(data)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/html.ex#L37)
```
@spec html_escape_to_iodata(String.t()) :: iodata()
```
Escapes the given HTML to iodata.
```
iex> Plug.HTML.html_escape_to_iodata("foo")
"foo"
iex> Plug.HTML.html_escape_to_iodata("<foo>")
[[[] | "<"], "foo" | ">"]
iex> Plug.HTML.html_escape_to_iodata("quotes: \" & \'")
[[[[], "quotes: " | """], " " | "&"], " " | "'"]
```
phoenix Plug.Exception protocol Plug.Exception protocol
========================
A protocol that extends exceptions to be status-code aware.
By default, it looks for an implementation of the protocol, otherwise checks if the exception has the `:plug_status` field or simply returns 500.
Summary
========
Types
------
[action()](#t:action/0) [t()](#t:t/0) Functions
----------
[actions(exception)](#actions/1) Receives an exception and returns the possible actions that could be triggered for that error. Should return a list of actions in the following structure
[status(exception)](#status/1) Receives an exception and returns its HTTP status code.
Types
======
### action()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/exceptions.ex#L15)
```
@type action() :: %{label: String.t(), handler: {module(), atom(), list()}}
```
### t()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/exceptions.ex#L4)
```
@type t() :: term()
```
Functions
==========
### actions(exception)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/exceptions.ex#L47)
```
@spec actions(t()) :: [action()]
```
Receives an exception and returns the possible actions that could be triggered for that error. Should return a list of actions in the following structure:
```
%{
label: "Text that will be displayed in the button",
handler: {Module, :function, [args]}
}
```
Where:
* `label` a string/binary that names this action
* `handler` a MFArgs that will be executed when this action is triggered
It will be rendered in the [`Plug.Debugger`](plug.debugger) generated error page as buttons showing the `label` that upon pressing executes the MFArgs defined in the `handler`.
#### Examples
```
defimpl Plug.Exception, for: ActionableExample do
def actions(_), do: [%{label: "Print HI", handler: {IO, :puts, ["Hi!"]}}]
end
```
### status(exception)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/exceptions.ex#L21)
```
@spec status(t()) :: Plug.Conn.status()
```
Receives an exception and returns its HTTP status code.
phoenix Plug.RequestId Plug.RequestId
===============
A plug for generating a unique request id for each request.
The generated request id will be in the format "uq8hs30oafhj5vve8ji5pmp7mtopc08f".
If a request id already exists as the "x-request-id" HTTP request header, then that value will be used assuming it is between 20 and 200 characters. If it is not, a new request id will be generated.
The request id is added to the Logger metadata as `:request_id` and the response as the "x-request-id" HTTP header. To see the request id in your log output, configure your logger backends to include the `:request_id` metadata:
```
config :logger, :console, metadata: [:request_id]
```
It is recommended to include this metadata configuration in your production configuration file.
You can also access the `request_id` programmatically by calling `Logger.metadata[:request_id]`. Do not access it via the request header, as the request header value has not been validated and it may not always be present.
To use this plug, just plug it into the desired module:
```
plug Plug.RequestId
```
Options
--------
* `:http_header` - The name of the HTTP *request* header to check for existing request ids. This is also the HTTP *response* header that will be set with the request id. Default value is "x-request-id"
```
plug Plug.RequestId, http_header: "custom-request-id"
```
phoenix Plug.Conn.Cookies Plug.Conn.Cookies
==================
Conveniences for encoding and decoding cookies.
Summary
========
Functions
----------
[decode(cookie)](#decode/1) Decodes the given cookies as given in either a request or response header.
[encode(key, opts \\ %{})](#encode/2) Encodes the given cookies as expected in a response header.
Functions
==========
### decode(cookie)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/cookies.ex#L17)
Decodes the given cookies as given in either a request or response header.
If a cookie is invalid, it is automatically discarded from the result.
#### Examples
```
iex> decode("key1=value1;key2=value2")
%{"key1" => "value1", "key2" => "value2"}
```
### encode(key, opts \\ %{})[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/cookies.ex#L54)
Encodes the given cookies as expected in a response header.
phoenix Plug.ErrorHandler behaviour Plug.ErrorHandler behaviour
============================
A module to be used in your existing plugs in order to provide error handling.
```
defmodule AppRouter do
use Plug.Router
use Plug.ErrorHandler
plug :match
plug :dispatch
get "/hello" do
send_resp(conn, 200, "world")
end
@impl Plug.ErrorHandler
def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
send_resp(conn, conn.status, "Something went wrong")
end
end
```
Once this module is used, a callback named `handle_errors/2` should be defined in your plug. This callback will receive the connection already updated with a proper status code for the given exception. The second argument is a map containing:
* the exception kind (`:throw`, `:error` or `:exit`),
* the reason (an exception for errors or a term for others)
* the stacktrace
After the callback is invoked, the error is re-raised.
It is advised to do as little work as possible when handling errors and avoid accessing data like parameters and session, as the parsing of those is what could have led the error to trigger in the first place.
Also notice that these pages are going to be shown in production. If you are looking for error handling to help during development, consider using [`Plug.Debugger`](plug.debugger).
**Note:** If this module is used with [`Plug.Debugger`](plug.debugger), it must be used after [`Plug.Debugger`](plug.debugger).
Summary
========
Callbacks
----------
[handle\_errors(t, map)](#c:handle_errors/2) Handle errors from plugs.
Callbacks
==========
### handle\_errors(t, map)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/error_handler.ex#L55)
```
@callback handle_errors(Plug.Conn.t(), %{
kind: :error | :throw | :exit,
reason: Exception.t() | term(),
stack: Exception.stacktrace()
}) :: no_return()
```
Handle errors from plugs.
Called when an exception is raised during the processing of a plug.
phoenix Plug.Session Plug.Session
=============
A plug to handle session cookies and session stores.
The session is accessed via functions on [`Plug.Conn`](plug.conn). Cookies and session have to be fetched with [`Plug.Conn.fetch_session/1`](plug.conn#fetch_session/1) before the session can be accessed.
The session is also lazy. Once configured, a cookie header with the session will only be sent to the client if something is written to the session in the first place.
When using [`Plug.Session`](plug.session#content), also consider using [`Plug.CSRFProtection`](plug.csrfprotection) to avoid Cross Site Request Forgery attacks.
Session stores
---------------
See [`Plug.Session.Store`](plug.session.store) for the specification session stores are required to implement.
Plug ships with the following session stores:
* [`Plug.Session.ETS`](plug.session.ets)
* [`Plug.Session.COOKIE`](plug.session.cookie)
Options
--------
* `:store` - session store module (required);
* `:key` - session cookie key (required);
* `:domain` - see [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4);
* `:max_age` - see [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4);
* `:path` - see [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4);
* `:secure` - see [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4);
* `:http_only` - see [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4);
* `:same_site` - see [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4);
* `:extra` - see [`Plug.Conn.put_resp_cookie/4`](plug.conn#put_resp_cookie/4);
Additional options can be given to the session store, see the store's documentation for the options it accepts.
Examples
---------
```
plug Plug.Session, store: :ets, key: "_my_app_session", table: :session
```
phoenix Plug.Conn.CookieOverflowError exception Plug.Conn.CookieOverflowError exception
========================================
Error raised when the cookie exceeds the maximum size of 4096 bytes.
phoenix Plug.CSRFProtection.InvalidCSRFTokenError exception Plug.CSRFProtection.InvalidCSRFTokenError exception
====================================================
Error raised when CSRF token is invalid.
phoenix Plug.Conn.Unfetched Plug.Conn.Unfetched
====================
A struct used as default on unfetched fields.
The `:aspect` key of the struct specifies what field is still unfetched.
Examples
---------
```
unfetched = %Plug.Conn.Unfetched{aspect: :cookies}
```
Summary
========
Types
------
[t()](#t:t/0) Functions
----------
[fetch(map, key)](#fetch/2) Callback implementation for [`Access.fetch/2`](https://hexdocs.pm/elixir/Access.html#c:fetch/2).
[get(map, key, value)](#get/3) [get\_and\_update(map, key, fun)](#get_and_update/3) Callback implementation for [`Access.get_and_update/3`](https://hexdocs.pm/elixir/Access.html#c:get_and_update/3).
[pop(map, key)](#pop/2) Callback implementation for [`Access.pop/2`](https://hexdocs.pm/elixir/Access.html#c:pop/2).
Types
======
### t()[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/unfetched.ex#L14)
```
@type t() :: %Plug.Conn.Unfetched{aspect: atom()}
```
Functions
==========
### fetch(map, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/unfetched.ex#L18)
Callback implementation for [`Access.fetch/2`](https://hexdocs.pm/elixir/Access.html#c:fetch/2).
### get(map, key, value)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/unfetched.ex#L22)
### get\_and\_update(map, key, fun)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/unfetched.ex#L26)
Callback implementation for [`Access.get_and_update/3`](https://hexdocs.pm/elixir/Access.html#c:get_and_update/3).
### pop(map, key)[Source](https://github.com/elixir-plug/plug/blob/v1.13.6/lib/plug/conn/unfetched.ex#L30)
Callback implementation for [`Access.pop/2`](https://hexdocs.pm/elixir/Access.html#c:pop/2).
| programming_docs |
phoenix Plug.Conn.InvalidQueryError exception Plug.Conn.InvalidQueryError exception
======================================
Raised when the request string is malformed, for example:
* the query has bad utf-8 encoding
* the query fails to www-form decode
phoenix Plug.Parsers.URLENCODED Plug.Parsers.URLENCODED
========================
Parses urlencoded request body.
Options
--------
All options supported by [`Plug.Conn.read_body/2`](plug.conn#read_body/2) are also supported here. They are repeated here for convenience:
* `:length` - sets the maximum number of bytes to read from the request, defaults to 1\_000\_000 bytes
* `:read_length` - sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to 1\_000\_000 bytes
* `:read_timeout` - sets the timeout for each socket read, defaults to 15\_000ms
So by default, [`Plug.Parsers`](plug.parsers) will read 1\_000\_000 bytes at a time from the socket with an overall limit of 8\_000\_000 bytes.
phoenix External Uploads External Uploads
=================
> This guide continues from the configuration started in the server [Uploads guide](uploads).
>
>
Uploads to external cloud providers, such as Amazon S3, Google Cloud, etc., can be achieved by using the `:external` option in [`allow_upload/3`](phoenix.liveview#allow_upload/3).
You provide a 2-arity function to allow the server to generate metadata for each upload entry, which is passed to a user-specified JavaScript function on the client.
Typically when your function is invoked, you will generate a pre-signed URL, specific to your cloud storage provider, that will provide temporary access for the end-user to upload data directly to your cloud storage.
Chunked HTTP Uploads
---------------------
For any service that supports large file uploads via chunked HTTP requests with `Content-Range` headers, you can use the UpChunk JS library by Mux to do all the hard work of uploading the file.
You only need to wire the UpChunk instance to the LiveView UploadEntry callbacks, and LiveView will take care of the rest.
Install [UpChunk](https://github.com/muxinc/upchunk) by saving [its contents](https://unpkg.com/@mux/upchunk@2) to `assets/vendor/upchunk.js` or by installing it with `npm`:
```
$ npm install --prefix assets --save @mux/upchunk
```
Configure your uploader on [`Phoenix.LiveView.mount/3`](phoenix.liveview#c:mount/3):
```
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:uploaded_files, [])
|> allow_upload(:avatar, accept: :any, max_entries: 3, external: &presign_upload/2)}
end
```
Supply the `:external` option to [`Phoenix.LiveView.allow_upload/3`](phoenix.liveview#allow_upload/3). It requires a 2-arity function that generates a signed URL where the client will push the bytes for the upload entry.
For example, if you were using a context that provided a [`start_session`](#) function, you might write something like this:
```
defp presign_upload(entry, socket) do
{:ok, %{"Location" => link}} =
SomeTube.start_session(%{
"uploadType" => "resumable",
"x-upload-content-length" => entry.client_size
})
{:ok, %{uploader: "UpChunk", entrypoint: link}, socket}
end
```
Finally, on the client-side, we use UpChunk to create an upload from the temporary URL generated on the server and attach listeners for its events to the entry's callbacks:
```
import * as UpChunk from "@mux/upchunk"
let Uploaders = {}
Uploaders.UpChunk = function(entries, onViewError){
entries.forEach(entry => {
// create the upload session with UpChunk
let { file, meta: { entrypoint } } = entry
let upload = UpChunk.createUpload({ endpoint: entrypoint, file })
// stop uploading in the event of a view error
onViewError(() => upload.pause())
// upload error triggers LiveView error
upload.on("error", (e) => entry.error(e.detail.message))
// notify progress events to LiveView
upload.on("progress", (e) => {
if(e.detail < 100){ entry.progress(e.detail) }
})
// success completes the UploadEntry
upload.on("success", () => entry.progress(100))
})
}
// Don't forget to assign Uploaders to the liveSocket
let liveSocket = new LiveSocket("/live", Socket, {
uploaders: Uploaders,
params: {_csrf_token: csrfToken}
})
```
Direct to S3
-------------
In order to enforce all of your file constraints when uploading to S3, it is necessary to perform a multipart form POST with your file data.
This guide assumes an existing S3 bucket with the correct CORS configuration which allows uploading directly to the bucket.
An example CORS config is:
```
[
{
"AllowedHeaders": [ "*" ],
"AllowedMethods": [ "PUT", "POST" ],
"AllowedOrigins": [ your_domain_or_*_here ],
"ExposeHeaders": []
}
]
```
More information on configuring CORS for S3 buckets is available at:
<https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html>
> The following example uses a zero-dependency module called [`SimpleS3Upload`](https://gist.github.com/chrismccord/37862f1f8b1f5148644b75d20d1cb073) written by Chris McCord to generate pre-signed URLs for S3.
>
>
```
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:uploaded_files, [])
|> allow_upload(:avatar, accept: :any, max_entries: 3, external: &presign_upload/2)}
end
defp presign_upload(entry, socket) do
uploads = socket.assigns.uploads
bucket = "phx-upload-example"
key = "public/#{entry.client_name}"
config = %{
region: "us-east-1",
access_key_id: System.fetch_env!("AWS_ACCESS_KEY_ID"),
secret_access_key: System.fetch_env!("AWS_SECRET_ACCESS_KEY")
}
{:ok, fields} =
SimpleS3Upload.sign_form_upload(config, bucket,
key: key,
content_type: entry.client_type,
max_file_size: uploads[entry.upload_config].max_file_size,
expires_in: :timer.hours(1)
)
meta = %{uploader: "S3", key: key, url: "http://#{bucket}.s3-#{config.region}.amazonaws.com", fields: fields}
{:ok, meta, socket}
end
```
Here, we implemented a `presign_upload/2` function, which we passed as a captured anonymous function to `:external`. Next, we generate a pre-signed URL for the upload. Lastly, we return our `:ok` result, with a payload of metadata for the client, along with our unchanged socket. The metadata *must* contain the `:uploader` key, specifying the name of the JavaScript client-side uploader, in this case `"S3"`.
To complete the flow, we can implement our `S3` client uploader and tell the `LiveSocket` where to find it:
```
let Uploaders = {}
Uploaders.S3 = function(entries, onViewError){
entries.forEach(entry => {
let formData = new FormData()
let {url, fields} = entry.meta
Object.entries(fields).forEach(([key, val]) => formData.append(key, val))
formData.append("file", entry.file)
let xhr = new XMLHttpRequest()
onViewError(() => xhr.abort())
xhr.onload = () => xhr.status === 204 ? entry.progress(100) : entry.error()
xhr.onerror = () => entry.error()
xhr.upload.addEventListener("progress", (event) => {
if(event.lengthComputable){
let percent = Math.round((event.loaded / event.total) * 100)
if(percent < 100){ entry.progress(percent) }
}
})
xhr.open("POST", url, true)
xhr.send(formData)
})
}
let liveSocket = new LiveSocket("/live", Socket, {
uploaders: Uploaders,
params: {_csrf_token: csrfToken}
})
```
We define an `Uploaders.S3` function, which receives our entries. It then performs an AJAX request for each entry, using the `entry.progress()` and `entry.error()`. functions to report upload events back to the LiveView. Lastly, we pass the `uploaders` namespace to the `LiveSocket` constructor to tell phoenix where to find the uploaders returned within the external metadata.
[← Previous Page JavaScript interoperability](https://hexdocs.pm/phoenix_live_view/js-interop.html)
phoenix Using Gettext for internationalization Using Gettext for internationalization
=======================================
For internationalization with [gettext](https://hexdocs.pm/gettext/Gettext.html), the locale used within your Plug pipeline can be stored in the Plug session and restored within your LiveView mount. For example, after user signs in or preference changes, you can write the locale to the session:
```
def put_user_session(conn, current_user) do
locale = get_locale_for_user(current_user)
Gettext.put_locale(MyApp.Gettext, locale)
conn
|> put_session(:user_id, current_user.id)
|> put_session(:locale, locale)
end
```
Then in your LiveView `mount/3`, you can restore the locale:
```
def mount(_params, %{"locale" => locale}, socket) do
Gettext.put_locale(MyApp.Gettext, locale)
{:ok, socket}
end
```
You can also use the `on_mount` ([`Phoenix.LiveView.on_mount/1`](phoenix.liveview#on_mount/1)) hook to automatically restore the locale for every LiveView in your application:
```
defmodule MyAppWeb.RestoreLocale do
import Phoenix.LiveView
def on_mount(:default, _params, %{"locale" => locale} = _session, socket) do
Gettext.put_locale(MyApp.Gettext, locale)
{:cont, socket}
end
# for any logged out routes
def on_mount(:default, _params, _session, socket), do: {:cont, socket}
end
```
Then, add this hook to `def live_view` under `MyAppWeb`, to run it on all LiveViews by default:
```
def live_view do
quote do
use Phoenix.LiveView,
layout: {MyAppWeb.LayoutView, "live.html"}
on_mount MyAppWeb.RestoreLocale
unquote(view_helpers())
end
end
```
[← Previous Page Uploads](uploads) [Next Page → Bindings](bindings)
phoenix Phoenix.LiveViewTest.Upload Phoenix.LiveViewTest.Upload
============================
The struct returned by [`Phoenix.LiveViewTest.file_input/4`](phoenix.liveviewtest#file_input/4).
The following public fields represent the element:
* `selector` - The query selector
* `entries` - The list of selected file entries
See the [`Phoenix.LiveViewTest`](phoenix.liveviewtest) documentation for usage.
phoenix Phoenix.LiveViewTest Phoenix.LiveViewTest
=====================
Conveniences for testing Phoenix LiveViews.
In LiveView tests, we interact with views via process communication in substitution of a browser. Like a browser, our test process receives messages about the rendered updates from the view which can be asserted against to test the life-cycle and behavior of LiveViews and their children.
LiveView Testing
-----------------
The life-cycle of a LiveView as outlined in the [`Phoenix.LiveView`](phoenix.liveview) docs details how a view starts as a stateless HTML render in a disconnected socket state. Once the browser receives the HTML, it connects to the server and a new LiveView process is started, remounted in a connected socket state, and the view continues statefully. The LiveView test functions support testing both disconnected and connected mounts separately, for example:
```
import Plug.Conn
import Phoenix.ConnTest
import Phoenix.LiveViewTest
@endpoint MyEndpoint
test "disconnected and connected mount", %{conn: conn} do
conn = get(conn, "/my-path")
assert html_response(conn, 200) =~ "<h1>My Disconnected View</h1>"
{:ok, view, html} = live(conn)
end
test "redirected mount", %{conn: conn} do
assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "my-path")
end
```
Here, we start by using the familiar [`Phoenix.ConnTest`](https://hexdocs.pm/phoenix/1.6.6/Phoenix.ConnTest.html) function, `get/2` to test the regular HTTP GET request which invokes mount with a disconnected socket. Next, [`live/1`](#live/1) is called with our sent connection to mount the view in a connected state, which starts our stateful LiveView process.
In general, it's often more convenient to test the mounting of a view in a single step, provided you don't need the result of the stateless HTTP render. This is done with a single call to [`live/2`](#live/2), which performs the `get` step for us:
```
test "connected mount", %{conn: conn} do
{:ok, _view, html} = live(conn, "/my-path")
assert html =~ "<h1>My Connected View</h1>"
end
```
### Testing Events
The browser can send a variety of events to a LiveView via `phx-` bindings, which are sent to the `handle_event/3` callback. To test events sent by the browser and assert on the rendered side effect of the event, use the `render_*` functions:
* [`render_click/1`](#render_click/1) - sends a phx-click event and value, returning the rendered result of the `handle_event/3` callback.
* [`render_focus/2`](#render_focus/2) - sends a phx-focus event and value, returning the rendered result of the `handle_event/3` callback.
* [`render_blur/1`](#render_blur/1) - sends a phx-blur event and value, returning the rendered result of the `handle_event/3` callback.
* [`render_submit/1`](#render_submit/1) - sends a form phx-submit event and value, returning the rendered result of the `handle_event/3` callback.
* [`render_change/1`](#render_change/1) - sends a form phx-change event and value, returning the rendered result of the `handle_event/3` callback.
* [`render_keydown/1`](#render_keydown/1) - sends a form phx-keydown event and value, returning the rendered result of the `handle_event/3` callback.
* [`render_keyup/1`](#render_keyup/1) - sends a form phx-keyup event and value, returning the rendered result of the `handle_event/3` callback.
* [`render_hook/3`](#render_hook/3) - sends a hook event and value, returning the rendered result of the `handle_event/3` callback.
For example:
```
{:ok, view, _html} = live(conn, "/thermo")
assert view
|> element("button#inc")
|> render_click() =~ "The temperature is: 31℉"
```
In the example above, we are looking for a particular element on the page and triggering its phx-click event. LiveView takes care of making sure the element has a phx-click and automatically sends its values to the server.
You can also bypass the element lookup and directly trigger the LiveView event in most functions:
```
assert render_click(view, :inc, %{}) =~ "The temperature is: 31℉"
```
The `element` style is preferred as much as possible, as it helps LiveView perform validations and ensure the events in the HTML actually matches the event names on the server.
### Testing regular messages
LiveViews are [`GenServer`](https://hexdocs.pm/elixir/GenServer.html)'s under the hood, and can send and receive messages just like any other server. To test the side effects of sending or receiving messages, simply message the view and use the `render` function to test the result:
```
send(view.pid, {:set_temp, 50})
assert render(view) =~ "The temperature is: 50℉"
```
Testing function components
----------------------------
There are two mechanisms for testing function components. Imagine the following component:
```
def greet(assigns) do
~H"""
<div>Hello, <%= @name %>!</div>
"""
end
```
You can test it by using [`render_component/3`](#render_component/3), passing the function reference to the component as first argument:
```
import Phoenix.LiveViewTest
test "greets" do
assert render_component(&MyComponents.greet/1, name: "Mary") ==
"<div>Hello, Mary!</div>"
end
```
However, for complex components, often the simplest way to test them is by using the `~H` sigil itself:
```
import Phoenix.LiveView.Helpers
import Phoenix.LiveViewTest
test "greets" do
assigns = []
assert rendered_to_string(~H"""
<MyComponents.greet name="Mary" />
""") ==
"<div>Hello, Mary!</div>"
end
```
The difference is that we use `rendered_to_string` to convert the rendered template to a string for testing.
Testing stateful components
----------------------------
There are two main mechanisms for testing stateful components. You can use [`render_component/2`](#render_component/2) to test how a component is mounted and rendered once:
```
assert render_component(MyComponent, id: 123, user: %User{}) =~
"some markup in component"
```
However, if you want to test how components are mounted by a LiveView and interact with DOM events, you must use the regular [`live/2`](#live/2) macro to build the LiveView with the component and then scope events by passing the view and a **DOM selector** in a list:
```
{:ok, view, html} = live(conn, "/users")
html = view |> element("#user-13 a", "Delete") |> render_click()
refute html =~ "user-13"
refute view |> element("#user-13") |> has_element?()
```
In the example above, LiveView will lookup for an element with ID=user-13 and retrieve its `phx-target`. If `phx-target` points to a component, that will be the component used, otherwise it will fallback to the view.
Summary
========
Functions
----------
[assert\_patch(view, timeout \\ 100)](#assert_patch/2) Asserts a live patch will happen within `timeout` milliseconds. The default `timeout` is 100.
[assert\_patch(view, to, timeout)](#assert_patch/3) Asserts a live patch will happen to a given path within `timeout` milliseconds. The default `timeout` is 100.
[assert\_patched(view, to)](#assert_patched/2) Asserts a live patch was performed, and returns the new path.
[assert\_push\_event(view, event, payload, timeout \\ 100)](#assert_push_event/4) Asserts an event will be pushed within `timeout`.
[assert\_redirect(view, timeout \\ 100)](#assert_redirect/2) Asserts a redirect will happen within `timeout` milliseconds. The default `timeout` is 100.
[assert\_redirect(view, to, timeout)](#assert_redirect/3) Asserts a redirect will happen to a given path within `timeout` milliseconds. The default `timeout` is 100.
[assert\_redirected(view, to)](#assert_redirected/2) Asserts a redirect was performed.
[assert\_reply(view, payload, timeout \\ 100)](#assert_reply/3) Asserts a hook reply was returned from a `handle_event` callback.
[element(view, selector, text\_filter \\ nil)](#element/3) Returns an element to scope a function to.
[file\_input(view, form\_selector, name, entries)](#file_input/4) Builds a file input for testing uploads within a form.
[find\_live\_child(parent, child\_id)](#find_live_child/2) Gets the nested LiveView child by `child_id` from the `parent` LiveView.
[follow\_redirect(reason, conn, to \\ nil)](#follow_redirect/3) Follows the redirect from a `render_*` action or an `{:error, redirect}` tuple.
[follow\_trigger\_action(form, conn)](#follow_trigger_action/2) Receives a `form_element` and asserts that `phx-trigger-action` has been set to true, following up on that request.
[form(view, selector, form\_data \\ %{})](#form/3) Returns a form element to scope a function to.
[has\_element?(element)](#has_element?/1) Checks if the given element exists on the page.
[has\_element?(view, selector, text\_filter \\ nil)](#has_element?/3) Checks if the given `selector` with `text_filter` is on `view`.
[live(conn, path \\ nil)](#live/2) Spawns a connected LiveView process.
[live\_children(parent)](#live_children/1) Returns the current list of LiveView children for the `parent` LiveView.
[live\_isolated(conn, live\_view, opts \\ [])](#live_isolated/3) Spawns a connected LiveView process mounted in isolation as the sole rendered element.
[live\_redirect(view, opts)](#live_redirect/2) Performs a live redirect from one LiveView to another.
[open\_browser(view\_or\_element, open\_fun \\ &open\_with\_system\_cmd/1)](#open_browser/2) Open the default browser to display current HTML of `view_or_element`.
[page\_title(view)](#page_title/1) Returns the most recent title that was updated via a `page_title` assign.
[preflight\_upload(upload)](#preflight_upload/1) Performs a preflight upload request.
[put\_connect\_info(conn, params)](#put_connect_info/2) deprecated [put\_connect\_params(conn, params)](#put_connect_params/2) Puts connect params to be used on LiveView connections.
[refute\_redirected(view, to)](#refute_redirected/2) Refutes a redirect to a given path was performed.
[render(view\_or\_element)](#render/1) Returns the HTML string of the rendered view or element.
[render\_blur(element, value \\ %{})](#render_blur/2) Sends a blur event given by `element` and returns the rendered result.
[render\_blur(view, event, value)](#render_blur/3) Sends a blur event to the view and returns the rendered result.
[render\_change(element, value \\ %{})](#render_change/2) Sends a form change event given by `element` and returns the rendered result.
[render\_change(view, event, value)](#render_change/3) Sends a form change event to the view and returns the rendered result.
[render\_click(element, value \\ %{})](#render_click/2) Sends a click event given by `element` and returns the rendered result.
[render\_click(view, event, value)](#render_click/3) Sends a click `event` to the `view` with `value` and returns the rendered result.
[render\_component(component, assigns \\ Macro.escape(%{}), opts \\ [])](#render_component/3) Renders a component.
[render\_focus(element, value \\ %{})](#render_focus/2) Sends a focus event given by `element` and returns the rendered result.
[render\_focus(view, event, value)](#render_focus/3) Sends a focus event to the view and returns the rendered result.
[render\_hook(view\_or\_element, event, value \\ %{})](#render_hook/3) Sends a hook event to the view or an element and returns the rendered result.
[render\_keydown(element, value \\ %{})](#render_keydown/2) Sends a keydown event given by `element` and returns the rendered result.
[render\_keydown(view, event, value)](#render_keydown/3) Sends a keydown event to the view and returns the rendered result.
[render\_keyup(element, value \\ %{})](#render_keyup/2) Sends a keyup event given by `element` and returns the rendered result.
[render\_keyup(view, event, value)](#render_keyup/3) Sends a keyup event to the view and returns the rendered result.
[render\_patch(view, path)](#render_patch/2) Simulates a `live_patch` to the given `path` and returns the rendered result.
[render\_submit(element, value \\ %{})](#render_submit/2) Sends a form submit event given by `element` and returns the rendered result.
[render\_submit(view, event, value)](#render_submit/3) Sends a form submit event to the view and returns the rendered result.
[render\_upload(upload, entry\_name, percent \\ 100)](#render_upload/3) Performs an upload of a file input and renders the result.
[rendered\_to\_string(rendered)](#rendered_to_string/1) Converts a rendered template to a string.
[with\_target(view, target)](#with_target/2) Sets the target of the view for events.
Functions
==========
### assert\_patch(view, timeout \\ 100)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1190)
Asserts a live patch will happen within `timeout` milliseconds. The default `timeout` is 100.
It returns the new path.
To assert on the flash message, you can assert on the result of the rendered LiveView.
#### Examples
```
render_click(view, :event_that_triggers_patch)
assert_patch view
render_click(view, :event_that_triggers_patch)
assert_patch view, 30
render_click(view, :event_that_triggers_patch)
path = assert_patch view
assert path =~ ~r/path/+/
```
### assert\_patch(view, to, timeout)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1216)
Asserts a live patch will happen to a given path within `timeout` milliseconds. The default `timeout` is 100.
It always returns `:ok`.
To assert on the flash message, you can assert on the result of the rendered LiveView.
#### Examples
```
render_click(view, :event_that_triggers_patch)
assert_patch view, "/path"
render_click(view, :event_that_triggers_patch)
assert_patch view, "/path", 30
```
### assert\_patched(view, to)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1234)
Asserts a live patch was performed, and returns the new path.
To assert on the flash message, you can assert on the result of the rendered LiveView.
#### Examples
```
render_click(view, :event_that_triggers_redirect)
assert_patched view, "/path"
```
### assert\_push\_event(view, event, payload, timeout \\ 100)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1470)
Asserts an event will be pushed within `timeout`.
#### Examples
```
assert_push_event view, "scores", %{points: 100, user: "josé"}
```
### assert\_redirect(view, timeout \\ 100)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1255)
Asserts a redirect will happen within `timeout` milliseconds. The default `timeout` is 100.
It returns a tuple containing the new path and the flash messages from said redirect, if any. Note the flash will contain string keys.
#### Examples
```
render_click(view, :event_that_triggers_redirect)
{path, flash} = assert_redirect view
assert flash["info"] == "Welcome"
assert path =~ ~r/path\/\d+/
render_click(view, :event_that_triggers_redirect)
assert_redirect view, 30
```
### assert\_redirect(view, to, timeout)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1279)
Asserts a redirect will happen to a given path within `timeout` milliseconds. The default `timeout` is 100.
It returns the flash messages from said redirect, if any. Note the flash will contain string keys.
#### Examples
```
render_click(view, :event_that_triggers_redirect)
flash = assert_redirect view, "/path"
assert flash["info"] == "Welcome"
render_click(view, :event_that_triggers_redirect)
assert_redirect view, "/path", 30
```
### assert\_redirected(view, to)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1298)
Asserts a redirect was performed.
It returns the flash messages from said redirect, if any. Note the flash will contain string keys.
#### Examples
```
render_click(view, :event_that_triggers_redirect)
flash = assert_redirected view, "/path"
assert flash["info"] == "Welcome"
```
### assert\_reply(view, payload, timeout \\ 100)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1485)
Asserts a hook reply was returned from a `handle_event` callback.
#### Examples
```
assert_reply view, %{result: "ok", transaction_id: _}
```
### element(view, selector, text\_filter \\ nil)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1054)
Returns an element to scope a function to.
It expects the current LiveView, a query selector, and a text filter.
An optional text filter may be given to filter the results by the query selector. If the text filter is a string or a regex, it will match any element that contains the string (including as a substring) or matches the regex.
So a link containing the text "unopened" will match `element("a", "opened")`. To prevent this, a regex could specify that "opened" appear without the prefix "un". For example, `element("a", ~r{(?<!un)opened})`. But it may be clearer to add an HTML attribute to make the element easier to select.
After the text filter is applied, only one element must remain, otherwise an error is raised.
If no text filter is given, then the query selector itself must return a single element.
```
assert view
|> element("#term a:first-child", "Increment")
|> render() =~ "Increment</a>"
```
Attribute selectors are also supported, and may be used on special cases like ids which contain periods:
```
assert view
|> element(~s{[href="/foo"][id="foo.bar.baz"]})
|> render() =~ "Increment</a>"
```
### file\_input(view, form\_selector, name, entries)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1108)
Builds a file input for testing uploads within a form.
Given the form DOM selector, the upload name, and a list of maps of client metadata for the upload, the returned file input can be passed to [`render_upload/2`](#render_upload/2).
Client metadata takes the following form:
* `:last_modified` - the last modified timestamp
* `:name` - the name of the file
* `:content` - the binary content of the file
* `:size` - the byte size of the content
* `:type` - the MIME type of the file
#### Examples
```
avatar = file_input(lv, "#my-form-id", :avatar, [%{
last_modified: 1_594_171_879_000,
name: "myfile.jpeg",
content: File.read!("myfile.jpg"),
size: 1_396_009,
type: "image/jpeg"
}])
assert render_upload(avatar, "myfile.jpeg") =~ "100%"
```
### find\_live\_child(parent, child\_id)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L922)
Gets the nested LiveView child by `child_id` from the `parent` LiveView.
#### Examples
```
{:ok, view, _html} = live(conn, "/thermo")
assert clock_view = find_live_child(view, "clock")
assert render_click(clock_view, :snooze) =~ "snoozing"
```
### follow\_redirect(reason, conn, to \\ nil)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1528)
Follows the redirect from a `render_*` action or an `{:error, redirect}` tuple.
Imagine you have a LiveView that redirects on a `render_click` event. You can make sure it immediately redirects after the `render_click` action by calling [`follow_redirect/3`](#follow_redirect/3):
```
live_view
|> render_click("redirect")
|> follow_redirect(conn)
```
Or in the case of an error tuple:
```
assert {:error, {:redirect, %{to: "/somewhere"}}} = result = live(conn, "my-path")
{:ok, view, html} = follow_redirect(result, conn)
```
[`follow_redirect/3`](#follow_redirect/3) expects a connection as second argument. This is the connection that will be used to perform the underlying request.
If the LiveView redirects with a live redirect, this macro returns `{:ok, live_view, disconnected_html}` with the content of the new LiveView, the same as the `live/3` macro. If the LiveView redirects with a regular redirect, this macro returns `{:ok, conn}` with the rendered redirected page. In any other case, this macro raises.
Finally, note that you can optionally assert on the path you are being redirected to by passing a third argument:
```
live_view
|> render_click("redirect")
|> follow_redirect(conn, "/redirected/page")
```
### follow\_trigger\_action(form, conn)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1649)
Receives a `form_element` and asserts that `phx-trigger-action` has been set to true, following up on that request.
Imagine you have a LiveView that sends an HTTP form submission. Say that it sets the `phx-trigger-action` to true, as a response to a submit event. You can follow the trigger action like this:
```
form = form(live_view, selector, %{"form" => "data"})
# First we submit the form. Optionally verify that phx-trigger-action
# is now part of the form.
assert render_submit(form) =~ ~r/phx-trigger-action/
# Now follow the request made by the form
conn = follow_trigger_action(form, conn)
assert conn.method == "POST"
assert conn.params == %{"form" => "data"}
```
### form(view, selector, form\_data \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1078)
Returns a form element to scope a function to.
It expects the current LiveView, a query selector, and the form data. The query selector must return a single element.
The form data will be validated directly against the form markup and make sure the data you are changing/submitting actually exists, failing otherwise.
#### Examples
```
assert view
|> form("#term", user: %{name: "hello"})
|> render_submit() =~ "Name updated"
```
This function is meant to mimic what the user can actually do, so you cannot set hidden input values. However, hidden values can be given when calling [`render_submit/2`](#render_submit/2) or [`render_change/2`](#render_change/2), see their docs for examples.
### has\_element?(element)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L936)
Checks if the given element exists on the page.
#### Examples
```
assert view |> element("#some-element") |> has_element?()
```
### has\_element?(view, selector, text\_filter \\ nil)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L950)
Checks if the given `selector` with `text_filter` is on `view`.
See [`element/3`](#element/3) for more information.
#### Examples
```
assert has_element?(view, "#some-element")
```
### live(conn, path \\ nil)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L216)
Spawns a connected LiveView process.
If a `path` is given, then a regular `get(conn, path)` is done and the page is upgraded to a `LiveView`. If no path is given, it assumes a previously rendered `%Plug.Conn{}` is given, which will be converted to a `LiveView` immediately.
#### Examples
```
{:ok, view, html} = live(conn, "/path")
assert view.module == MyLive
assert html =~ "the count is 3"
assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "/path")
```
### live\_children(parent)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L909)
Returns the current list of LiveView children for the `parent` LiveView.
Children are returned in the order they appear in the rendered HTML.
#### Examples
```
{:ok, view, _html} = live(conn, "/thermo")
assert [clock_view] = live_children(view)
assert render_click(clock_view, :snooze) =~ "snoozing"
```
### live\_isolated(conn, live\_view, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L262)
Spawns a connected LiveView process mounted in isolation as the sole rendered element.
Useful for testing LiveViews that are not directly routable, such as those built as small components to be re-used in multiple parents. Testing routable LiveViews is still recommended whenever possible since features such as live navigation require routable LiveViews.
#### Options
* `:session` - the session to be given to the LiveView
All other options are forwarded to the LiveView for rendering. Refer to [`Phoenix.LiveView.Helpers.live_render/3`](phoenix.liveview.helpers#live_render/3) for a list of supported render options.
#### Examples
```
{:ok, view, html} =
live_isolated(conn, MyAppWeb.ClockLive, session: %{"tz" => "EST"})
```
Use [`put_connect_params/2`](#put_connect_params/2) to put connect params for a call to [`Phoenix.LiveView.get_connect_params/1`](phoenix.liveview#get_connect_params/1) in [`Phoenix.LiveView.mount/3`](phoenix.liveview#c:mount/3):
```
{:ok, view, html} =
conn
|> put_connect_params(%{"param" => "value"})
|> live_isolated(AppWeb.ClockLive, session: %{"tz" => "EST"})
```
### live\_redirect(view, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1586)
Performs a live redirect from one LiveView to another.
When redirecting between two LiveViews of the same `live_session`, mounts the new LiveView and shutsdown the previous one, which mimics general browser live navigation behaviour.
When attempting to navigate from a LiveView of a different `live_session`, an error redirect condition is returned indicating a failed `live_redirect` from the client.
#### Examples
```
assert {:ok, page_live, _html} = live(conn, "/page/1")
assert {:ok, page2_live, _html} = live(conn, "/page/2")
assert {:error, {:redirect, _}} = live_redirect(page2_live, to: "/admin")
```
### open\_browser(view\_or\_element, open\_fun \\ &open\_with\_system\_cmd/1)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1378)
Open the default browser to display current HTML of `view_or_element`.
#### Examples
```
view
|> element("#term a:first-child", "Increment")
|> open_browser()
assert view
|> form("#term", user: %{name: "hello"})
|> open_browser()
|> render_submit() =~ "Name updated"
```
### page\_title(view)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1165)
Returns the most recent title that was updated via a `page_title` assign.
#### Examples
```
render_click(view, :event_that_triggers_page_title_update)
assert page_title(view) =~ "my title"
```
### preflight\_upload(upload)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1740)
Performs a preflight upload request.
Useful for testing external uploaders to retrieve the `:external` entry metadata.
#### Examples
```
avatar = file_input(lv, "#my-form-id", :avatar, [%{name: ..., ...}, ...])
assert {:ok, %{ref: _ref, config: %{chunk_size: _}}} = preflight_upload(avatar)
```
### put\_connect\_info(conn, params)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L194)
This function is deprecated. set the relevant connect\_info fields in the connection instead. ### put\_connect\_params(conn, params)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L189)
Puts connect params to be used on LiveView connections.
See [`Phoenix.LiveView.get_connect_params/1`](phoenix.liveview#get_connect_params/1).
### refute\_redirected(view, to)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1334)
Refutes a redirect to a given path was performed.
It returns :ok if the specified redirect isn't already in the mailbox.
#### Examples
```
render_click(view, :event_that_triggers_redirect_to_path)
:ok = refute_redirected view, "/wrong_path"
```
### render(view\_or\_element)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L970)
Returns the HTML string of the rendered view or element.
If a view is provided, the entire LiveView is rendered. If a view after calling [`with_target/2`](#with_target/2) or an element are given, only that particular context is returned.
#### Examples
```
{:ok, view, _html} = live(conn, "/thermo")
assert render(view) =~ ~s|<button id="alarm">Snooze</div>|
assert view
|> element("#alarm")
|> render() == "Snooze"
```
### render\_blur(element, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L788)
Sends a blur event given by `element` and returns the rendered result.
The `element` is created with [`element/3`](#element/3) and must point to a single element on the page with a `phx-blur` attribute in it. The event name given set on `phx-blur` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("#inactive")
|> render_blur() =~ "Tap to wake"
```
### render\_blur(view, event, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L805)
Sends a blur event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_blur(view, :inactive) =~ "Tap to wake"
```
### render\_change(element, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L662)
Sends a form change event given by `element` and returns the rendered result.
The `element` is created with [`element/3`](#element/3) and must point to a single element on the page with a `phx-change` attribute in it. The event name given set on `phx-change` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values.
If you need to pass any extra values or metadata, such as the "\_target" parameter, you can do so by giving a map under the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("form")
|> render_change(%{deg: 123}) =~ "123 exceeds limits"
# Passing metadata
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("form")
|> render_change(%{_target: ["deg"], deg: 123}) =~ "123 exceeds limits"
```
As with [`render_submit/2`](#render_submit/2), hidden input field values can be provided like so:
```
refute view
|> form("#term", user: %{name: "hello"})
|> render_change(%{user: %{"hidden_field" => "example"}}) =~ "can't be blank"
```
### render\_change(view, event, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L678)
Sends a form change event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_change(view, :validate, %{deg: 123}) =~ "123 exceeds limits"
```
### render\_click(element, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L556)
Sends a click event given by `element` and returns the rendered result.
The `element` is created with [`element/3`](#element/3) and must point to a single element on the page with a `phx-click` attribute in it. The event name given set on `phx-click` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument.
If the element is does not have a `phx-click` attribute but it is a link (the `<a>` tag), the link will be followed accordingly:
* if the link is a `live_patch`, the current view will be patched
* if the link is a `live_redirect`, this function will return `{:error, {:live_redirect, %{to: url}}}`, which can be followed with [`follow_redirect/2`](#follow_redirect/2)
* if the link is a regular link, this function will return `{:error, {:redirect, %{to: url}}}`, which can be followed with [`follow_redirect/2`](#follow_redirect/2)
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("button", "Increment")
|> render_click() =~ "The temperature is: 30℉"
```
### render\_click(view, event, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L573)
Sends a click `event` to the `view` with `value` and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temperature is: 30℉"
assert render_click(view, :inc) =~ "The temperature is: 31℉"
```
### render\_component(component, assigns \\ Macro.escape(%{}), opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L458)
Renders a component.
The first argument may either be a function component, as an anonymous function:
```
assert render_component(&Weather.city/1, name: "Kraków") =~
"some markup in component"
```
Or a stateful component as a module. In this case, this function will mount, update, and render the component. The `:id` option is a required argument:
```
assert render_component(MyComponent, id: 123, user: %User{}) =~
"some markup in component"
```
If your component is using the router, you can pass it as argument:
```
assert render_component(MyComponent, %{id: 123, user: %User{}}, router: SomeRouter) =~
"some markup in component"
```
### render\_focus(element, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L830)
Sends a focus event given by `element` and returns the rendered result.
The `element` is created with [`element/3`](#element/3) and must point to a single element on the page with a `phx-focus` attribute in it. The event name given set on `phx-focus` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("#inactive")
|> render_focus() =~ "Tap to wake"
```
### render\_focus(view, event, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L847)
Sends a focus event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_focus(view, :inactive) =~ "Tap to wake"
```
### render\_hook(view\_or\_element, event, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L873)
Sends a hook event to the view or an element and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_hook(view, :refresh, %{deg: 32}) =~ "The temp is: 32℉"
```
If you are pushing events from a hook to a component, then you must pass an `element`, created with [`element/3`](#element/3), as first argument and it must point to a single element on the page with a `phx-target` attribute in it:
```
{:ok, view, _html} = live(conn, "/thermo")
assert view
|> element("#thermo-component")
|> render_hook(:refresh, %{deg: 32}) =~ "The temp is: 32℉"
```
### render\_keydown(element, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L702)
Sends a keydown event given by `element` and returns the rendered result.
The `element` is created with [`element/3`](#element/3) and must point to a single element on the page with a `phx-keydown` or `phx-window-keydown` attribute in it. The event name given set on `phx-keydown` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert view |> element("#inc") |> render_keydown() =~ "The temp is: 31℉"
```
### render\_keydown(view, event, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L722)
Sends a keydown event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_keydown(view, :inc) =~ "The temp is: 31℉"
```
### render\_keyup(element, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L746)
Sends a keyup event given by `element` and returns the rendered result.
The `element` is created with [`element/3`](#element/3) and must point to a single element on the page with a `phx-keyup` or `phx-window-keyup` attribute in it. The event name given set on `phx-keyup` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert view |> element("#inc") |> render_keyup() =~ "The temp is: 31℉"
```
### render\_keyup(view, event, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L763)
Sends a keyup event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_keyup(view, :inc) =~ "The temp is: 31℉"
```
### render\_patch(view, path)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L894)
Simulates a `live_patch` to the given `path` and returns the rendered result.
### render\_submit(element, value \\ %{})[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L605)
Sends a form submit event given by `element` and returns the rendered result.
The `element` is created with [`element/3`](#element/3) and must point to a single element on the page with a `phx-submit` attribute in it. The event name given set on `phx-submit` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values, including hidden input fields, can be given with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("form")
|> render_submit(%{deg: 123, avatar: upload}) =~ "123 exceeds limits"
```
To submit a form along with some with hidden input values:
```
assert view
|> form("#term", user: %{name: "hello"})
|> render_submit(%{user: %{"hidden_field" => "example"}}) =~ "Name updated"
```
### render\_submit(view, event, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L621)
Sends a form submit event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}` tuple.
#### Examples
```
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_submit(view, :refresh, %{deg: 32}) =~ "The temp is: 32℉"
```
### render\_upload(upload, entry\_name, percent \\ 100)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L1713)
Performs an upload of a file input and renders the result.
See [`file_input/4`](#file_input/4) for details on building a file input.
#### Examples
Given the following LiveView template:
```
<%= for entry <- @uploads.avatar.entries do %>
<%= entry.name %>: <%= entry.progress %>%
<% end %>
```
Your test case can assert the uploaded content:
```
avatar = file_input(lv, "#my-form-id", :avatar, [
%{
last_modified: 1_594_171_879_000,
name: "myfile.jpeg",
content: File.read!("myfile.jpg"),
size: 1_396_009,
type: "image/jpeg"
}
])
assert render_upload(avatar, "myfile.jpeg") =~ "100%"
```
By default, the entire file is chunked to the server, but an optional percentage to chunk can be passed to test chunk-by-chunk uploads:
```
assert render_upload(avatar, "myfile.jpeg", 49) =~ "49%"
assert render_upload(avatar, "myfile.jpeg", 51) =~ "100%"
```
### rendered\_to\_string(rendered)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L518)
Converts a rendered template to a string.
#### Examples
```
iex> import Phoenix.LiveView.Helpers
iex> assigns = []
iex> ~H"""
...> <div>example</div>
...> """
...> |> rendered_to_string()
"<div>example</div>"
```
### with\_target(view, target)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/test/live_view_test.ex#L989)
Sets the target of the view for events.
This emulates `phx-target` directly in tests, without having to dispatch the event to a specific element. This can be useful for invoking events to one or multiple components at the same time:
```
view
|> with_target("#user-1,#user-2")
|> render_click("Hide", %{})
```
| programming_docs |
phoenix Changelog Changelog
==========
0.17.11 (2022-07-11)
---------------------
### Enhancements
* Add `replaceTransport` to LiveSocket
### Bug fixes
* Cancel debounced events from firing after a live navigation event
* Fix hash anchor failing to scroll to anchor element on live navigation
* Do not debounce `phx-blur` events
0.17.10 (2022-05-25)
---------------------
### Bug fixes
* [Formatter] Preserve single quote delimiter on attrs
* [Formatter] Do not format inline elements surrounded by texts without whitespaces
* [Formatter] Keep text and eex along when there isn't a whitespace
* [Formatter] Fix intentional line breaks after eex expressions
* [Formatter] Handle self close tags as inline
* [Formatter] Do not format inline elements without whitespaces among them
* [Formatter] Do not format when attr contenteditable is present
### Enhancements
* [Formatter] Introduce special attr phx-no-format to skip formatting
0.17.9 (2022-04-07)
--------------------
### Bug fixes
* Fix sticky LiveViews failing to be patched during live navigation
* Do not raise on dynamic `phx-update` value
0.17.8 (2022-04-06)
--------------------
### Enhancements
* Add HEEx formatter
* Support `phx-change` on individual inputs
* Dispatch `MouseEvent` on client
* Add `:bubbles` option to `JS.dispatch` to control event bubbling
* Expose underlying `liveSocket` instance on hooks
* Enable client debug by default on localhost
### Bug fixes
* Fix hook and sticky LiveView issues caused by back-to-back live redirects from mount
* Fix hook destroyed callback failing to be invoked for children of phx-remove in some cases
* Do not failsafe reload the page on push timeout if disconnected
* Do not bubble navigation click events to regular phx-click's
* No longer generate `csrf_token` for forms without action, reducing the payload during phx-change/phx-submit events
0.17.7 (2022-02-07)
--------------------
### Enhancements
* Optimize nested for comprehension diffs
### Bug fixes
* Fix error when `live_redirect` links are clicked when not connected in certain cases
0.17.6 (2022-01-18)
--------------------
### Enhancements
* Add `JS.set_attribute` and `JS.remove_attribute`
* Add `sticky: true` option to `live_render` to maintain a nested child on across live redirects
* Dispatch `phx:show-start`, `phx:show-end`, `phx:hide-start` and `phx:hide-end` on `JS.show|hide|toggle`
* Add `get_connect_info/2` that also works on disconnected render
* Add `LiveSocket` constructor options for configuration failsafe behavior via new `maxReloads`, `reloadJitterMin`, `reloadJitterMax`, `failsafeJitter` options
### Bug fixes
* Show form errors after submit even when no changes occur on server
* Fix `phx-disable-with` failing to disable elements outside of forms
* Fix phx ref tracking leaving elements in awaiting state when targeting an external LiveView
* Fix diff on response failing to await for active transitions in certain cases
* Fix `phx-click-away` not respecting `phx-target`
* Fix "disconnect" broadcast failing to failsafe refresh the page
* Fix `JS.push` with `:target` failing to send to correct component in certain cases
### Deprecations
* Deprecate [`Phoenix.LiveView.get_connect_info/1`](phoenix.liveview#get_connect_info/1) in favor of `get_connect_info/2`
* Deprecate [`Phoenix.LiveViewTest.put_connect_info/2`](phoenix.liveviewtest#put_connect_info/2) in favor of calling the relevant functions in [`Plug.Conn`](https://hexdocs.pm/plug/1.13.3/Plug.Conn.html)
* Deprecate returning "raw" values from upload callbacks on [`Phoenix.LiveView.consume_uploaded_entry/3`](phoenix.liveview#consume_uploaded_entry/3) and [`Phoenix.LiveView.consume_uploaded_entries/3`](phoenix.liveview#consume_uploaded_entries/3). The callback must return either `{:ok, value}` or `{:postpone, value}`. Returning any other value will emit a warning.
0.17.5 (2021-11-02)
--------------------
### Bug fixes
* Do not trigger `phx-click-away` if element is not visible
* Fix `phx-remove` failing to tear down nested live children
0.17.4 (2021-11-01)
--------------------
### Bug fixes
* Fix variable scoping issues causing various content block or duplication rendering bugs
0.17.3 (2021-10-28)
--------------------
### Enhancements
* Support 3-tuple for JS class transitions to support staged animations where a transition class is applied with a starting and ending class
* Allow JS commands to be executed on DOM nodes outside of the LiveView container
### Optimization
* Avoid duplicate statics inside comprehension. In previous versions, comprehensions were able to avoid duplication only in the content of their root. Now we recursively traverse all comprehension nodes and send the static only once for the whole comprehension. This should massively reduce the cost of sending comprehensions over the wire
### Bug fixes
* Fix HTML engine bug causing expressions to be duplicated or not rendered correctly
* Fix HTML engine bug causing slots to not be re-rendered when they should have
* Fix form recovery being sent to wrong target
0.17.2 (2021-10-22)
--------------------
### Bug fixes
* Fix HTML engine bug causing attribute expressions to be incorrectly evaluated in certain cases
* Fix show/hide/toggle custom display not being restored
* Fix default `to` target for `JS.show|hide|dispatch`
* Fix form input targeting
0.17.1 (2021-10-21)
--------------------
### Bug fixes
* Fix SVG element support for `phx` binding interactions
0.17.0 (2021-10-21)
--------------------
### Breaking Changes
####
`on_mount` changes
The hook API introduced in LiveView 0.16 has been improved based on feedback. LiveView 0.17 removes the custom module-function callbacks for the [`Phoenix.LiveView.on_mount/1`](phoenix.liveview#on_mount/1) macro and the `:on_mount` option for [`Phoenix.LiveView.Router.live_session/3`](phoenix.liveview.router#live_session/3) in favor of supporting a custom argument. For clarity, the module function to be invoked during the mount lifecycle stage will always be named `on_mount/4`.
For example, if you had invoked `on_mount/1` like so:
```
on_mount MyAppWeb.MyHook
on_mount {MyAppWeb.MyHook, :assign_current_user}
```
and defined your callbacks as:
```
# my_hook.ex
def mount(_params, _session, _socket) do
end
def assign_current_user(_params, _session, _socket) do
end
```
Change the callback to:
```
# my_hook.ex
def on_mount(:default, _params, _session, _socket) do
end
def on_mount(:assign_current_user, _params, _session, _socket) do
end
```
When given only a module name, the first argument to `on_mount/4` will be the atom `:default`.
#### LEEx templates in stateful LiveComponents
Stateful LiveComponents (where an `:id` is given) must now return HEEx templates (`~H` sigil or `.heex` extension). LEEx templates (`~L` sigil or `.leex` extension) are no longer supported. This addresses bugs and allows stateful components to be rendered more efficiently client-side.
####
`phx-disconnected` class has been replaced with `phx-loading`
Due to a bug in the newly released Safari 15, the previously used `.phx-disconnected` class has been replaced by a new `.phx-loading` class. The reason for the change is `phx.new` included a `.phx-disconnected` rule in the generated `app.css` which triggers the Safari bug. Renaming the class avoids applying the erroneous rule for existing applications. Folks can upgrade by simply renaming their `.phx-disconnected` rules to `.phx-loading`.
####
`phx-capture-click` has been deprecated in favor of `phx-click-away`
The new `phx-click-away` binding replaces `phx-capture-click` and is much more versatile because it can detect "click focus" being lost on containers.
#### Removal of previously deprecated functionality
Some functionality that was previously deprecated has been removed:
* Implicit assigns in `live_component` do-blocks is no longer supported
* Passing a `@socket` to `live_component` will now raise if possible
### Enhancements
* Allow slots in function components: they are marked as `<:slot_name>` and can be rendered with `<%= render_slot @slot_name %>`
* Add `JS` command for executing JavaScript utility operations on the client with an extended push API
* Optimize string attributes:
+ If the attribute is a string interpolation, such as `<div class={"foo bar #{@baz}"}>`, only the interpolation part is marked as dynamic
+ If the attribute can be empty, such as "class" and "style", keep the attribute name as static
* Add a function component for rendering [`Phoenix.LiveComponent`](phoenix.livecomponent). Instead of `<%= live_component FormComponent, id: "form" %>`, you must now do: `<.live_component module={FormComponent} id="form" />`
### Bug fixes
* Fix LiveViews with form recovery failing to properly mount following a reconnect when preceded by a live redirect
* Fix stale session causing full redirect fallback when issuing a `push_redirect` from mount
* Add workaround for Safari bug causing `<img>` tags with srcset and video with autoplay to fail to render
* Support EEx interpolation inside HTML comments in HEEx templates
* Support HTML tags inside script tags (as in regular HTML)
* Raise if using quotes in attribute names
* Include the filename in error messages when it is not possible to parse interpolated attributes
* Make sure the test client always sends the full URL on `live_patch`/`live_redirect`. This mirrors the behaviour of the JavaScript client
* Do not reload flash from session on `live_redirect`s
* Fix select drop-down flashes in Chrome when the DOM is patched during focus
### Deprecations
* `<%= live_component MyModule, id: @user.id, user: @user %>` is deprecated in favor of `<.live_component module={MyModule} id={@user.id} user={@user} />`. Notice the new API requires using HEEx templates. This change allows us to further improve LiveComponent and bring new features such as slots to them.
* `render_block/2` in deprecated in favor of `render_slot/2`
0.16.4 (2021-09-22)
--------------------
### Enhancements
* Improve HEEx error messages
* Relax HTML tag validation to support mixed case tags
* Support self closing HTML tags
* Remove requirement for `handle_params` to be defined for lifecycle hooks
### Bug fixes
* Fix pushes failing to include channel `join_ref` on messages
0.16.3 (2021-09-03)
--------------------
### Bug fixes
* Fix `on_mount` hooks calling view mount before redirecting when the hook issues a halt redirect.
0.16.2 (2021-09-03)
--------------------
### Enhancements
* Improve error messages on tokenization
* Improve error message if `@inner_block` is missing
### Bug fixes
* Fix `phx-change` form recovery event being sent to wrong component on reconnect when component order changes
0.16.1 (2021-08-26)
--------------------
### Enhancements
* Relax `phoenix_html` dependency requirement
* Allow testing functional components by passing a function reference to [`Phoenix.LiveViewTest.render_component/3`](phoenix.liveviewtest#render_component/3)
### Bug fixes
* Do not generate CSRF tokens for non-POST forms
* Do not add compile-time dependencies on `on_mount` declarations
0.16.0 (2021-08-10)
--------------------
### Security Considerations Upgrading from 0.15
LiveView v0.16 optimizes live redirects by supporting navigation purely over the existing WebSocket connection. This is accomplished by the new `live_session/3` feature of [`Phoenix.LiveView.Router`](phoenix.liveview.router). The [security guide](security-model) has always stressed the following:
> ... As we have seen, LiveView begins its life-cycle as a regular HTTP request. Then a stateful connection is established. Both the HTTP request and the stateful connection receives the client data via parameters and session. This means that any session validation must happen both in the HTTP request (plug pipeline) and the stateful connection (LiveView mount) ...
>
>
These guidelines continue to be valid, but it is now essential that the stateful connection enforces authentication and session validation within the LiveView mount lifecycle because **a `live_redirect` from the client will not go through the plug pipeline** as a hard-refresh or initial HTTP render would. This means authentication, authorization, etc that may be done in the [`Plug.Conn`](https://hexdocs.pm/plug/1.13.3/Plug.Conn.html) pipeline must also be performed within the LiveView mount lifecycle.
Live sessions allow you to support a shared security model by allowing `live_redirect`s to only be issued between routes defined under the same live session name. If a client attempts to live redirect to a different live session, it will be refused and a graceful client-side redirect will trigger a regular HTTP request to the attempted URL.
See the [`Phoenix.LiveView.Router.live_session/3`](phoenix.liveview.router#live_session/3) docs for more information and example usage.
### New HTML Engine
LiveView v0.16 introduces HEEx (HTML + EEx) templates and the concept of function components via [`Phoenix.Component`](phoenix.component). The new HEEx templates validate the markup in the template while also providing smarter change tracking as well as syntax conveniences to make it easier to build composable components.
A function component is any function that receives a map of assigns and returns a `~H` template:
```
defmodule MyComponent do
use Phoenix.Component
def btn(assigns) do
~H"""
<button class="btn"><%= @text %></button>
"""
end
end
```
This component can now be used as in your HEEx templates as:
```
<MyComponent.btn text="Save">
```
The introduction of HEEx and function components brings a series of deprecation warnings, some introduced in this release and others which will be added in the future. Note HEEx templates require Elixir v1.12+.
### Upgrading and deprecations
The main deprecation in this release is that the `~L` sigil and the `.leex` extension are now soft-deprecated. The docs have been updated to discourage them and using them will emit warnings in future releases. We recommend using the `~H` sigil and the `.heex` extension for all future templates in your application. You should also plan to migrate the old templates accordingly using the recommendations below.
Migrating from `LEEx` to `HEEx` is relatively straightforward. There are two main differences. First of all, HEEx does not allow interpolation inside tags. So instead of:
```
<div id="<%= @id %>">
...
</div>
```
One should use the HEEx syntax:
```
<div id={@id}>
...
</div>
```
The other difference is in regards to `form_for`. Some templates may do the following:
```
~L"""
<%= f = form_for @changeset, "#" %>
<%= input f, :foo %>
</form>
"""
```
However, when converted to `~H`, it is not valid HTML: there is a `</form>` tag but its opening is hidden inside the Elixir code. On LiveView v0.16, there is a function component named `form`:
```
~H"""
<.form let={f} for={@changeset}>
<%= input f, :foo %>
</.form>
"""
```
We understand migrating all templates from `~L` to `~H` can be a daunting task. Therefore we plan to support `~L` in LiveViews for a long time. However, we can't do the same for stateful LiveComponents, as some important client-side features and optimizations will depend on the `~H` sigil. Therefore **our recommendation is to replace `~L` by `~H` first in live components**, particularly stateful live components.
Furthermore, stateless `live_component` (i.e. live components without an `:id`) will be deprecated in favor of the new function components. Our plan is to support them for a reasonable period of time, but you should avoid creating new ones in your application.
### Breaking Changes
LiveView 0.16 removes the `:layout` and `:container` options from `Phoenix.LiveView.Routing.live/4` in favor of the `:root_layout` and `:container` options on `Phoenix.Router.live_session/3`.
For instance, if you have the following in LiveView 0.15 and prior:
```
live "/path", MyAppWeb.PageLive, layout: {MyAppWeb.LayoutView, "custom_layout.html"}
```
Change it to:
```
live_session :session_name, root_layout: {MyAppWeb.LayoutView, "custom_layout.html"} do
live "/path", MyAppWeb.PageLive
end
```
On the client, the `phoenix_live_view` package no longer provides a default export for `LiveSocket`.
If you have the following in your JavaScript entrypoint (typically located at `assets/js/app.js`):
```
import LiveSocket from "phoenix_live_view"
```
Change it to:
```
import { LiveSocket } from "phoenix_live_view"
```
Additionally on the client, the root LiveView element no longer exposes the LiveView module name, therefore the `phx-view` attribute is never set. Similarly, the `viewName` property of client hooks has been removed.
Codebases calling a custom function `component/3` should rename it or specify its module to avoid a conflict, as LiveView introduces a macro with that name and it is special cased by the underlying engine.
### Enhancements
* Introduce HEEx templates
* Introduce [`Phoenix.Component`](phoenix.component)
* Introduce `Phoenix.Router.live_session/3` for optimized live redirects
* Introduce `on_mount` and `attach_hook` hooks which provide a mechanism to tap into key stages of the LiveView lifecycle
* Add upload methods to client-side hooks
* [Helpers] Optimize `live_img_preview` rendering
* [Helpers] Introduce `form` function component which wraps `Phoenix.HTML.form_for`
* [LiveViewTest] Add `with_target` for scoping components directly
* [LiveViewTest] Add `refute_redirected`
* [LiveViewTest] Support multiple `phx-target` values to mirror JS client
* [LiveViewTest] Add `follow_trigger_action`
* [JavaScript Client] Add `sessionStorage` option `LiveSocket` constructor to support client storage overrides
* [JavaScript Client] Do not failsafe reload the page in the background when a tab is unable to connect if the page is not visible
### Bug fixes
* Make sure components are loaded on `render_component` to ensure all relevant callbacks are invoked
* Fix `Phoenix.LiveViewTest.page_title` returning `nil` in some cases
* Fix buttons being re-enabled when explicitly set to disabled on server
* Fix live patch failing to update URL when live patch link is patched again via `handle_params` within the same callback lifecycle
* Fix `phx-no-feedback` class not applied when page is live-patched
* Fix `DOMException, querySelector, not a valid selector` when performing DOM lookups on non-standard IDs
* Fix select dropdown flashing close/opened when assigns are updated on Chrome/macOS
* Fix error with multiple `live_file_input` in one form
* Fix race condition in `showError` causing null `querySelector`
* Fix statics not resolving correctly across recursive diffs
* Fix no function clause matching in `Phoenix.LiveView.Diff.many_to_iodata`
* Fix upload input not being cleared after files are uploaded via a component
* Fix channel crash when uploading during reconnect
* Fix duplicate progress events being sent for large uploads
### Deprecations
* Implicit assigns when passing a `do-end` block to `live_component` is deprecated
* The `~L` sigil and the `.leex` extension are now soft-deprecated in favor of `~H` and `.heex`
* Stateless live components (a `live_component` call without an `:id`) are deprecated in favor of the new function component feature
0.15.7 (2021-05-24)
--------------------
### Bug fixes
* Fix broken webpack build throwing missing morphdom dependency
0.15.6 (2021-05-24)
--------------------
### Bug fixes
* Fix live patch failing to update URL when live patch link is patched again from `handle_params`
* Fix regression in `LiveViewTest.render_upload/3` when using channel uploads and progress callback
* Fix component uploads not being cleaned up on remove
* Fix [`KeyError`](https://hexdocs.pm/elixir/KeyError.html) on LiveView reconnect when an active upload was previously in progress
### Enhancements
* Support function components via `component/3`
* Optimize progress events to send less messages for larger file sizes
* Allow session and local storage client overrides
### Deprecations
* Deprecate `@socket/socket` argument on `live_component/3` call
0.15.5 (2021-04-20)
--------------------
### Enhancements
* Add `upload_errors/1` for returning top-level upload errors
### Bug fixes
* Fix `consume_uploaded_entry/3` with external uploads causing inconsistent entries state
* Fix `push_event` losing events when a single diff produces multiple events from different components
* Fix deep merging of component tree sharing
0.15.4 (2021-01-26)
--------------------
### Bug fixes
* Fix nested `live_render`'s causing remound of child LiveView even when ID does not change
* Do not attempt push hook events unless connected
* Fix preflighted refs causing `auto_upload: true` to fail to submit form
* Replace single upload entry when `max_entries` is 1 instead of accumulating multiple file selections
* Fix `static_path` in `open_browser` failing to load stylesheets
0.15.3 (2021-01-02)
--------------------
### Bug fixes
* Fix `push_redirect` back causing timeout on the client
0.15.2 (2021-01-01)
--------------------
### Backwards incompatible changes
* Remove `beforeDestroy` from `phx-hook` callbacks
### Bug fixes
* Fix form recovery failing to send input on first connection failure
* Fix hooks not getting remounted after LiveView reconnect
* Fix hooks `reconnected` callback being fired with no prior disconnect
0.15.1 (2020-12-20)
--------------------
### Enhancements
* Ensure all click events bubble for mobile Safari
* Run `consume_uploaded_entries` in LiveView caller process
### Bug fixes
* Fix hooks not getting remounted after LiveView recovery
* Fix bug causing reload with jitter on timeout from previously closed channel
* Fix component child nodes being lost when component patch goes from single root node to multiple child siblings
* Fix `phx-capture-click` triggering on mouseup during text selection
* Fix LiveView `push_event`'s not clearing up in components
* Fix `<textarea>` being patched by LiveView while focused
0.15.0 (2020-11-20)
--------------------
### Enhancements
* Add live uploads support for file progress, interactive file selection, and direct to cloud support
* Implement [`Phoenix.LiveViewTest.open_browser/2`](phoenix.liveviewtest#open_browser/2) that opens up a browser with the LiveView page
### Backwards incompatible changes
* Remove `@inner_content` in components and introduce `render_block` for rendering component `@inner_block`
* Remove `@live_module` in socket templates in favor of `@socket.view`
### Bug fixes
* Make sure URLs are decoded after they are split
* Do not recover forms without inputs
* Fix race condition when components are removed and then immediately re-added before the client can notify their CIDs have been destroyed
* Do not render LiveView if only events/replies have been added to the socket
* Properly merge different components when sharing component subtrees on initial render
* Allow variables inside do-blocks to be tainted
* Fix `push_redirect` from mount hanging on the client and causing a fallback to full page reload when following a clicked `live_redirect` on the client
0.14.8 (2020-10-30)
--------------------
### Bug fixes
* Fix compatibility with latest Plug
0.14.7 (2020-09-25)
--------------------
### Bug fixes
* Fix `redirect(socket, external: ...)` when returned from an event
* Properly follow location hashes on live patch/redirect
* Fix failure in [`Phoenix.LiveViewTest`](phoenix.liveviewtest) when `phx-update` has non-HTML nodes as children
* Fix `phx_trigger_action` submitting the form before the DOM updates are complete
0.14.6 (2020-09-21)
--------------------
### Bug fixes
* Fix race condition on `phx-trigger-action` causing reconnects before server form submit
0.14.5 (2020-09-20)
--------------------
### Enhancements
* Optimize DOM prepend and append operations
* Add [`Phoenix.LiveView.send_update_after/3`](phoenix.liveview#send_update_after/3)
### Bug fixes
* Fix scroll position when using back/forward with `live_redirect`'s
* Handle recursive components when generating diffs
* Support hard redirects on mount
* Properly track nested components on deletion on [`Phoenix.LiveViewTest`](phoenix.liveviewtest)
0.14.4 (2020-07-30)
--------------------
### Bug fixes
* Fix hidden inputs throwing selection range error
0.14.3 (2020-07-24)
--------------------
### Enhancements
* Support `render_layout` with LiveEEx
### Bug fixes
* Fix focused inputs being overwritten by latent patch
* Fix LiveView error when `"_target"` input name contains array
* Fix change tracking when passing a do-block to components
0.14.2 (2020-07-21)
--------------------
### Bug fixes
* Fix Map of assigns together with `@inner_content` causing `no function clause matching in Keyword.put/3` error
* Fix `LiveViewTest` failing to patch children properly for append/prepend based phx-update's
* Fix argument error when providing `:as` option to a `live` route
* Fix page becoming unresponsive when the server crashes while handling a live patch
* Fix empty diff causing pending data-ref based updates, such as classes and `phx-disable-with` content to not be updated
* Fix bug where throttling keydown events would eat key presses
* Fix `<textarea>`'s failing to be disabled on form submit
* Fix text node DOM memory leak when using `phx-update` append/prepend
### Enhancements
* Allow `:router` to be given to `render_component`
* Display file on compile warning for `~L`
* Log error on client when using a hook without a DOM ID
* Optimize `phx-update` append/prepend based DOM updates
0.14.1 (2020-07-09)
--------------------
### Bug fixes
* Fix nested `live_render`'s failing to be torn down when removed from the DOM in certain cases
* Fix LEEx issue for nested conditions failing to be re-evaluated
0.14.0 (2020-07-07)
--------------------
### Bug fixes
* Fix IE11 issue where `document.activeElement` creates a null reference
* Fix setup and teardown of root views when explicitly calling `liveSocket.disconnect()` followed by `liveSocket.connect()`
* Fix `error_tag` failing to be displayed for non-text based inputs such as selects and checkboxes as the `phx-no-feedback` class was always applied
* Fix `phx-error` class being applied on `live_redirect`
* Properly handle Elixir's special variables, such as `__MODULE__`
* No longer set disconnected class during patch
* Track flash keys to fix back-to-back flashes from being discarded
* Properly handle empty component diffs in the client for cases where the component has already been removed on the server
* Make sure components in nested live views do not conflict
* Fix `phx-static` not being sent from the client for child views
* Do not fail when trying to delete a view that was already deleted
* Ensure `beforeDestroy` is called on hooks in children of a removed element
### Enhancements
* Allow the whole component static subtree to be shared when the component already exists on the client
* Add telemetry events to `mount`, `handle_params`, and `handle_event`
* Add `push_event` for pushing events and data from the server to the client
* Add client `handleEvent` hook method for receiving events pushed from the server
* Add ability to receive a reply to a `pushEvent` from the server via `{:reply, map, socket}`
* Use event listener for popstate to avoid conflicting with user-defined popstate handlers
* Log error on client when rendering a component with no direct DOM children
* Make `assigns.myself` a struct to catch mistakes
* Log if component doesn't exist on `send_update`, raise if module is unavailable
0.13.3 (2020-06-04)
--------------------
### Bug fixes
* Fix duplicate debounced events from being triggered on blur with timed debounce
* Fix client error when `live_redirect`ed route results in a redirect to a non-live route on the server
* Fix DOM siblings being removed when a rootless component is updated
* Fix debounced input failing to send last change when blurred via Tab, Meta, or other non-printable keys
### Enhancements
* Add `dom` option to `LiveSocket` with `onBeforeElUpdated` callback for external client library support of broad DOM operations
0.13.2 (2020-05-27)
--------------------
### Bug fixes
* Fix a bug where swapping a root template with components would cause the LiveView to crash
0.13.1 (2020-05-26)
--------------------
### Bug fixes
* Fix forced page refresh when `push_redirect` from a `live_redirect`
### Enhancements
* Optimize component diffs to avoid sending empty diffs
* Optimize components to share static values
* [LiveViewTest] Automatically synchronize before render events
0.13.0 (2020-05-21)
--------------------
### Backwards incompatible changes
* No longer send event metadata by default. Metadata is now opt-in and user defined at the `LiveSocket` level. To maintain backwards compatibility with pre-0.13 behaviour, you can provide the following metadata option:
```
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
metadata: {
click: (e, el) => {
return {
altKey: e.altKey,
shiftKey: e.shiftKey,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
x: e.x || e.clientX,
y: e.y || e.clientY,
pageX: e.pageX,
pageY: e.pageY,
screenX: e.screenX,
screenY: e.screenY,
offsetX: e.offsetX,
offsetY: e.offsetY,
detail: e.detail || 1,
}
},
keydown: (e, el) => {
return {
altGraphKey: e.altGraphKey,
altKey: e.altKey,
code: e.code,
ctrlKey: e.ctrlKey,
key: e.key,
keyIdentifier: e.keyIdentifier,
keyLocation: e.keyLocation,
location: e.location,
metaKey: e.metaKey,
repeat: e.repeat,
shiftKey: e.shiftKey
}
}
}
})
```
### Bug fixes
* Fix error caused by Chrome sending a keydown event on native UI autocomplete without a `key`
* Fix server error when a live navigation request issues a redirect
* Fix double window bindings when explicit calls to LiveSocket connect/disconnect/connect
### Enhancements
* Add [`Phoenix.LiveView.get_connect_info/1`](phoenix.liveview#get_connect_info/1)
* Add [`Phoenix.LiveViewTest.put_connect_info/2`](phoenix.liveviewtest#put_connect_info/2) and [`Phoenix.LiveViewTest.put_connect_params/2`](phoenix.liveviewtest#put_connect_params/2)
* Add support for tracking static asset changes on the page across cold server deploys
* Add support for passing a `@myself` target to a hook's `pushEventTo` target
* Add configurable metadata for events with new `metadata` LiveSocket option
* Add `"_mounts"` key in connect params which specifies the number of times a LiveView has mounted
0.12.1 (2020-04-19)
--------------------
### Bug fixes
* Fix component `innerHTML` being discarded when a sibling DOM element appears above it, in cases where the component lacks a DOM ID
* Fix Firefox reconnecting briefly during hard redirects
* Fix `phx-disable-with` and other pending attributes failing to be restored when an empty patch is returned by server
* Ensure LiveView module is loaded before mount to prevent first application request logging errors if the very first request is to a connected LiveView
0.12.0 (2020-04-16)
--------------------
This version of LiveView comes with an overhaul of the testing module, more closely integrating your LiveView template with your LiveView events. For example, in previous versions, you could write this test:
```
render_click(live_view, "increment_by", %{by: 1})
```
However, there is no guarantee that there is any element on the page with a `phx-click="increment"` attribute and `phx-value-by` set to 1. With LiveView 0.12.0, you can now write:
```
live_view
|> element("#term .buttons a", "Increment")
|> render_click()
```
The new implementation will check there is a button at `#term .buttons a`, with "Increment" as text, validate that it has a `phx-click` attribute and automatically submit to it with all relevant `phx-value` entries. This brings us closer to integration/acceptance test frameworks without any of the overhead and complexities of running a headless browser.
### Enhancements
* Add `assert_patch/3` and `assert_patched/2` for asserting on patches
* Add `follow_redirect/3` to automatically follow redirects from `render_*` events
* Add `phx-trigger-action` form annotation to trigger an HTTP form submit on next DOM patch
### Bug fixes
* Fix `phx-target` `@myself` targeting a sibling LiveView component with the same component ID
* Fix `phx:page-loading-stop` firing before the DOM patch has been performed
* Fix `phx-update="prepend"` failing to properly patch the DOM when the same ID is updated back to back
* Fix redirects on mount failing to copy flash
### Backwards incompatible changes
* `phx-error-for` has been removed in favor of `phx-feedback-for`. `phx-feedback-for` will set a `phx-no-feedback` class whenever feedback has to be hidden
* `Phoenix.LiveViewTest.children/1` has been renamed to [`Phoenix.LiveViewTest.live_children/1`](phoenix.liveviewtest#live_children/1)
* `Phoenix.LiveViewTest.find_child/2` has been renamed to [`Phoenix.LiveViewTest.find_live_child/2`](phoenix.liveviewtest#find_live_child/2)
* [`Phoenix.LiveViewTest.assert_redirect/3`](phoenix.liveviewtest#assert_redirect/3) no longer matches on the flash, instead it returns the flash
* [`Phoenix.LiveViewTest.assert_redirect/3`](phoenix.liveviewtest#assert_redirect/3) no longer matches on the patch redirects, use `assert_patch/3` instead
* `Phoenix.LiveViewTest.assert_remove/3` has been removed. If the LiveView crashes, it will cause the test to crash too
* Passing a path with DOM IDs to `render_*` test functions is deprecated. Furthermore, they now require a `phx-target="<%= @id %>"` on the given DOM ID:
```
<div id="component-id" phx-target="component-id">
...
</div>
```
```
html = render_submit([view, "#component-id"], event, value)
```
In any case, this API is deprecated and you should migrate to the new element based API.
0.11.1 (2020-04-08)
--------------------
### Bug fixes
* Fix readonly states failing to be undone after an empty diff
* Fix dynamically added child failing to be joined by the client
* Fix teardown bug causing stale client sessions to attempt a rejoin on reconnect
* Fix orphaned prepend/append content across joins
* Track `unless` in LiveEEx engine
### Backwards incompatible changes
* `render_event`/`render_click` and friends now expect a DOM ID selector to be given when working with components. For example, instead of `render_click([live, "user-13"])`, you should write `render_click([live, "#user-13"])`, mirroring the `phx-target` API.
* Accessing the socket assigns directly `@socket.assigns[...]` in a template will now raise the exception `Phoenix.LiveView.Socket.AssignsNotInSocket`. The socket assigns are available directly inside the template as LiveEEx `assigns`, such as `@foo` and `@bar`. Any assign access should be done using the assigns in the template where proper change tracking takes place.
### Enhancements
* Trigger debounced events immediately on input blur
* Support `defaults` option on `LiveSocket` constructor to configure default `phx-debounce` and `phx-throttle` values, allowing `<input ... phx-debounce>`
* Add `detail` key to click event metadata for detecting double/triple clicks
0.11.0 (2020-04-06)
--------------------
### Backwards incompatible changes
* Remove `socket.assigns` during render to avoid change tracking bugs. If you were previously relying on passing `@socket` to functions then referencing socket assigns, pass the explicit assign instead to your functions from the template.
* Removed `assets/css/live_view.css`. If you want to show a progress bar then in `app.css`, replace
```
- @import "../../../../deps/phoenix_live_view/assets/css/live_view.css";
+ @import "../node_modules/nprogress/nprogress.css";
```
and add `nprogress` to `assets/package.json`. Full details in the [Progress animation guide](https://hexdocs.pm/phoenix_live_view/0.11.0/installation.html#progress-animation)
### Bug fixes
* Fix client issue with greater than two levels of LiveView nesting
* Fix bug causing entire LiveView to be re-rendering with only a component changed
* Fix issue where rejoins would not trigger `phx:page-loading-stop`
### Enhancements
* Support deep change tracking so `@foo.bar` only executes and diffs when bar changes
* Add `@myself` assign, to allow components to target themselves instead of relying on a DOM ID, for example: `phx-target="<%= @myself %>"`
* Optimize various client rendering scenarios for faster DOM patching of components and append/prepended content
* Add `enableProfiling()` and `disableProfiling()` to `LiveSocket` for client performance profiling to aid the development process
* Allow LiveViews to be rendered inside LiveComponents
* Add support for clearing flash inside components
0.10.0 (2020-03-18)
--------------------
### Backwards incompatible changes
* Rename socket assign `@live_view_module` to `@live_module`
* Rename socket assign `@live_view_action` to `@live_action`
* LiveView no longer uses the default app layout and `put_live_layout` is no longer supported. Instead, use `put_root_layout`. Note, however, that the layout given to `put_root_layout` must use `@inner_content` instead of `<%= render(@view_module, @view_template, assigns) %>` and that the root layout will also be used by regular views. Check the [Live Layouts](https://hexdocs.pm/phoenix_live_view/0.10.0/Phoenix.LiveView.html#module-live-layouts) section of the docs.
### Bug fixes
* Fix loading states causing nested LiveViews to be removed during live navigation
* Only trigger `phx-update="ignore"` hook if data attributes have changed
* Fix LiveEEx fingerprint bug causing no diff to be sent in certain cases
### Enhancements
* Support collocated templates where an `.html.leex` template of the same basename of the LiveView will be automatically used for `render/1`
* Add `live_title_tag/2` helper for automatic prefix/suffix on `@page_title` updates
0.9.0 (2020-03-08)
-------------------
### Bug fixes
* Do not set ignored inputs and buttons as readonly
* Only decode paths in URIs
* Only destroy main descendents when replacing main
* Fix sibling component patches when siblings at same root DOM tree
* Do not pick the layout from `:use` on child LiveViews
* Respect when the layout is set to `false` in the router and on mount
* Fix sibling component patch when component siblings lack a container
* Make flash optional (i.e. LiveView will still work if you don't `fetch_flash` before)
### Enhancements
* Raise if `:flash` is given as an assign
* Support user-defined metadata in router
* Allow the router to be accessed as `socket.router`
* Allow `MFArgs` as the `:session` option in the `live` router macro
* Trigger page loading event when main LV errors
* Automatically clear the flash on live navigation examples - only the newly assigned flash is persisted
0.8.1 (2020-02-27)
-------------------
### Enhancements
* Support `phx-disable-with` on live redirect and live patch links
### Bug Fixes
* Fix focus issue on date and time inputs
* Fix LiveViews failing to mount when page restored from back/forward cache following a `redirect` on the server
* Fix IE coercing `undefined` to string when issuing pushState
* Fix IE error when focused element is null
* Fix client error when using components and live navigation where a dynamic template is rendered
* Fix latent component diff causing error when component removed from DOM before patch arrives
* Fix race condition where a component event received on the server for a component already removed by the server raised a match error
0.8.0 (2020-02-22)
-------------------
### Backwards incompatible changes
* Remove `Phoenix.LiveView.Flash` in favor of `:fetch_live_flash` imported by [`Phoenix.LiveView.Router`](phoenix.liveview.router)
* Live layout must now access the child contents with `@inner_content` instead of invoking the LiveView directly
* Returning `:stop` tuples from LiveView `mount` or `handle_[params|call|cast|info|event]` is no longer supported. LiveViews are stopped when issuing a `redirect` or `push_redirect`
### Enhancements
* Add `put_live_layout` plug to put the root layout used for live routes
* Allow `redirect` and `push_redirect` from mount
* Use acknowledgement tracking to avoid patching inputs until the server has processed the form event
* Add css loading states to all phx bound elements with event specific css classes
* Dispatch `phx:page-loading-start` and `phx:page-loading-stop` on window for live navigation, initial page loads, and form submits, for user controlled page loading integration
* Allow any phx bound element to specify `phx-page-loading` to dispatch loading events above when the event is pushed
* Add client side latency simulator with new `enableLatencySim(milliseconds)` and `disableLatencySim()`
* Add `enableDebug()` and `disableDebug()` to `LiveSocket` for ondemand browser debugging from the web console
* Do not connect LiveSocket WebSocket or bind client events unless a LiveView is found on the page
* Add `transport_pid/1` to return the websocket transport pid when the socket is connected
### Bug Fixes
* Fix issue where a failed mount from a `live_redirect` would reload the current URL instead of the attempted new URL
0.7.1 (2020-02-13)
-------------------
### Bug Fixes
* Fix checkbox bug failing to send `phx-change` event to the server in certain cases
* Fix checkbox bug failing to maintain checked state when a checkbox is programmatically updated by the server
* Fix select bug in Firefox causing the highlighted index to jump when a patch is applied during hover state
0.7.0 (2020-02-12)
-------------------
### Backwards incompatible changes
* `live_redirect` was removed in favor of `push_patch` (for updating the URL and params of the current LiveView) and `push_redirect` (for updating the URL to another LiveView)
* `live_link` was removed in favor of `live_patch` (for updating the URL and params of the current LiveView) and `live_redirect` (for updating the URL to another LiveView)
* `Phoenix.LiveViewTest.assert_redirect` no longer accepts an anonymous function in favor of executing the code prior to asserting the redirects, just like `assert_receive`.
### Enhancements
* Support `@live_view_action` in LiveViews to simplify tracking of URL state
* Recovery form input data automatically on disconnects or crash recovery
* Add `phx-auto-recover` form binding for specialized recovery
* Scroll to top of page while respecting anchor hash targets on `live_patch` and `live_redirect`
* Add `phx-capture-click` to use event capturing to bind a click event as it propagates inwards from the target
* Revamp flash support so it works between static views, live views, and components
* Add `phx-key` binding to scope `phx-window-keydown` and `phx-window-keyup` events
### Bug Fixes
* Send `phx-value-*` on key events
* Trigger `updated` hook callbacks on `phx-update="ignore"` container when the container's attributes have changed
* Fix nested `phx-update="append"` raising ArgumentError in LiveViewTest
* Fix updates not being applied in rare cases where an leex template is wrapped in an if expression
0.6.0 (2020-01-22)
-------------------
### Deprecations
* LiveView `mount/2` has been deprecated in favor of `mount/3`. The params are now passed as the first argument to `mount/3`, followed by the session and socket.
### Backwards incompatible changes
* The socket session now accepts only string keys
### Enhancements
* Allow window beforeunload to be cancelled without losing websocket connection
### Bug Fixes
* Fix handle\_params not decoding URL path parameters properly
* Fix LiveViewTest error when routing at root path
* Fix URI encoded params failing to be decoded in `handle_params`
* Fix component target failing to locate correct component when the target is on an input tag
0.5.2 (2020-01-17)
-------------------
### Bug Fixes
* Fix optimization bug causing some DOM nodes to be removed on updates
0.5.1 (2020-01-15)
-------------------
### Bug Fixes
* Fix phx-change bug causing phx-target to not be used
0.5.0 (2020-01-15)
-------------------
LiveView now makes the connection session automatically available in LiveViews. However, to do so, you need to configure your endpoint accordingly, **otherwise LiveView will fail to connect**.
The steps are:
1. Find `plug Plug.Session, ...` in your endpoint.ex and move the options `...` to a module attribute:
```
@session_options [
...
]
```
2. Change the `plug Plug.Session` to use said attribute:
```
plug Plug.Session, @session_options
```
3. Also pass the `@session_options` to your LiveView socket:
```
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]]
```
4. You should define the CSRF meta tag inside <head> in your layout, before `app.js` is included:
```
<%= csrf_meta_tag() %>
<script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
```
5. Then in your app.js:
```
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}});
```
Also note that **the session from now on will have string keys**. LiveView will warn if atom keys are used.
### Enhancements
* Respect new tab behavior in `live_link`
* Add `beforeUpdate` and `beforeDestroy` JS hooks
* Make all assigns defined on the socket mount available on the layout on first render
* Provide support for live layouts with new `:layout` option
* Detect duplicate IDs on the front-end when DEBUG mode is enabled
* Automatically forward the session to LiveView
* Support "live\_socket\_id" session key for identifying (and disconnecting) LiveView sockets
* Add support for `hibernate_after` on LiveView processes
* Support redirecting to full URLs on `live_redirect` and `redirect`
* Add `offsetX` and `offsetY` to click event metadata
* Allow `live_link` and `live_redirect` to exist anywhere in the page and it will always target the main LiveView (the one defined at the router)
### Backwards incompatible changes
* `phx-target="window"` has been removed in favor of `phx-window-keydown`, `phx-window-focus`, etc, and the `phx-target` binding has been repurposed for targeting LiveView and LiveComponent events from the client
* [`Phoenix.LiveView`](phoenix.liveview) no longer defined `live_render` and `live_link`. These functions have been moved to [`Phoenix.LiveView.Helpers`](phoenix.liveview.helpers) which can now be fully imported in your views. In other words, replace `import Phoenix.LiveView, only: [live_render: ..., live_link: ...]` by `import Phoenix.LiveView.Helpers`
0.4.1 (2019-11-07)
-------------------
### Bug Fixes
* Fix bug causing blurred inputs
0.4.0 (2019-11-07)
-------------------
### Enhancements
* Add [`Phoenix.LiveComponent`](phoenix.livecomponent) to compartmentalize state, markup, and events in LiveView
* Handle outdated clients by refreshing the page with jitter when a valid, but outdated session is detected
* Only dispatch live link clicks to router LiveView
* Refresh the page for graceful error recovery on failed mount when the socket is in a connected state
### Bug Fixes
* Fix `phx-hook` destroyed callback failing to be called in certain cases
* Fix back/forward bug causing LiveView to fail to remount
0.3.1 (2019-09-23)
-------------------
### Backwards incompatible changes
* `live_isolated` in tests no longer requires a router and a pipeline (it now expects only 3 arguments)
* Raise if `handle_params` is used on a non-router LiveView
### Bug Fixes
* [LiveViewTest] Fix function clause errors caused by HTML comments
0.3.0 (2019-09-19)
-------------------
### Enhancements
* Add `phx-debounce` and `phx-throttle` bindings to rate limit events
### Backwards incompatible changes
* IE11 support now requires two additional polyfills, `mdn-polyfills/CustomEvent` and `mdn-polyfills/String.prototype.startsWith`
### Bug Fixes
* Fix IE11 support caused by unsupported `getAttributeNames` lookup
* Fix Floki dependency compilation warnings
0.2.1 (2019-09-17)
-------------------
### Bug Fixes
* [LiveView.Router] Fix module concat failing to build correct layout module when using custom namespace
* [LiveViewTest] Fix `phx-update` append/prepend containers not building proper DOM content
* [LiveViewTest] Fix `phx-update` append/prepend containers not updating existing child containers with matching IDs
0.2.0 (2019-09-12)
-------------------
### Enhancements
* [LiveView] Add new `:container` option to `use Phoenix.LiveView`
* [LiveViewTest] Add `live_isolated` test helper for testing LiveViews which are not routable
### Backwards incompatible changes
* Replace `configure_temporary_assigns/2` with 3-tuple mount return, supporting a `:temporary_assigns` key
* Do not allow `redirect`/`live_redirect` on mount nor in child live views
* All `phx-update` containers now require a unique ID
* `LiveSocket` JavaScript constructor now requires explicit dependency injection of Phoenix Socket constructor. For example:
```
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"
let liveSocket = new LiveSocket("/live", Socket, {...})
```
### Bug Fixes
* Fix `phx-update=append/prepend` failing to join new nested live views or wire up new phx-hooks
* Fix number input handling causing some browsers to reset form fields on invalid inputs
* Fix multi-select decoding causing server error
* Fix multi-select change tracking failing to submit an event when a value is deselected
* Fix live redirect loop triggered under certain scenarios
* Fix params failing to update on re-mounts after live\_redirect
* Fix blur event metadata being sent with type of `"focus"`
0.1.2 (2019-08-28)
-------------------
### Backwards incompatible changes
* `phx-value` has no effect, use `phx-value-*` instead
* The `:path_params` key in session has no effect (use `handle_params` in `LiveView` instead)
0.1.1 (2019-08-27)
-------------------
### Enhancements
* Use optimized `insertAdjacentHTML` for faster append/prepend and proper css animation handling
* Allow for replacing previously appended/prepended elements by replacing duplicate IDs during append/prepend instead of adding new DOM nodes
### Bug Fixes
* Fix duplicate append/prepend updates when parent content is updated
* Fix JS hooks not being applied for appending and prepended content
0.1.0 (2019-08-25)
-------------------
### Enhancements
* The LiveView `handle_in/3` callback now receives a map of metadata about the client event
* For `phx-change` events, `handle_in/3` now receives a `"_target"` param representing the keyspace of the form input name which triggered the change
* Multiple values may be provided for any phx binding by using the `phx-value-` prefix, such as `phx-value-myval1`, `phx-value-myval2`, etc
* Add control over the DOM patching via `phx-update`, which can be set to `"replace"`, `"append"`, `"prepend"` or `"ignore"`
### Backwards incompatible changes
* `phx-ignore` was renamed to `phx-update="ignore"`
[← Previous Page API Reference](api-reference) [Next Page → Installation](installation)
| programming_docs |
phoenix Phoenix.LiveViewTest.Element Phoenix.LiveViewTest.Element
=============================
The struct returned by [`Phoenix.LiveViewTest.element/3`](phoenix.liveviewtest#element/3).
The following public fields represent the element:
* `selector` - The query selector
* `text_filter` - The text to further filter the element
See the [`Phoenix.LiveViewTest`](phoenix.liveviewtest) documentation for usage.
phoenix Phoenix.LiveView.Component Phoenix.LiveView.Component
===========================
The struct returned by components in .heex templates.
This component is never meant to be output directly into the template. It should always be handled by the diffing algorithm.
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/engine.ex#L12)
```
@type t() :: %Phoenix.LiveView.Component{
assigns: map(),
component: module(),
id: binary()
}
```
phoenix Phoenix.LiveView.Helpers Phoenix.LiveView.Helpers
=========================
A collection of helpers to be imported into your views.
Summary
========
Functions
----------
[assigns\_to\_attributes(assigns, exclude \\ [])](#assigns_to_attributes/2) Filters the assigns as a list of keywords for use in dynamic tag attributes.
[component(func, assigns \\ [])](#component/2) Renders a component defined by the given function.
[form(assigns)](#form/1) Renders a form function component.
[inner\_block(name, list)](#inner_block/2) Define a inner block, generally used by slots.
[live\_component(assigns)](#live_component/1) A function component for rendering [`Phoenix.LiveComponent`](phoenix.livecomponent) within a parent LiveView.
[live\_component(component, assigns, do\_block \\ [])](#live_component/3) deprecated Deprecated API for rendering `LiveComponent`.
[live\_file\_input(conf, opts \\ [])](#live_file_input/2) Builds a file input tag for a LiveView upload.
[live\_flash(other, key)](#live_flash/2) Returns the flash message from the LiveView flash assign.
[live\_img\_preview(entry, opts \\ [])](#live_img_preview/2) Generates an image preview on the client for a selected file.
[live\_patch(text, opts)](#live_patch/2) Generates a link that will patch the current LiveView.
[live\_redirect(text, opts)](#live_redirect/2) Generates a link that will redirect to a new LiveView of the same live session.
[live\_render(conn\_or\_socket, view, opts \\ [])](#live_render/3) Renders a LiveView within a template.
[live\_title\_tag(title, opts \\ [])](#live_title_tag/2) Renders a title tag with automatic prefix/suffix on `@page_title` updates.
[render\_block(inner\_block, argument \\ [])](#render_block/2) deprecated Renders the `@inner_block` assign of a component with the given `argument`.
[render\_slot(slot, argument \\ nil)](#render_slot/2) Renders a slot entry with the given optional `argument`.
[sigil\_H(arg, list)](#sigil_H/2) The `~H` sigil for writing HEEx templates inside source files.
[sigil\_L(arg, list)](#sigil_L/2) deprecated Provides `~L` sigil with HTML safe Live EEx syntax inside source files.
[upload\_errors(conf)](#upload_errors/1) Returns the entry errors for an upload.
[upload\_errors(conf, entry)](#upload_errors/2) Returns the entry errors for an upload.
Functions
==========
### assigns\_to\_attributes(assigns, exclude \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L236)
Filters the assigns as a list of keywords for use in dynamic tag attributes.
Useful for transforming caller assigns into dynamic attributes while stripping reserved keys from the result.
#### Examples
Imagine the following `my_link` component which allows a caller to pass a `new_window` assign, along with any other attributes they would like to add to the element, such as class, data attributes, etc:
```
<.my_link href="/" id={@id} new_window={true} class="my-class">Home</.my_link>
```
We could support the dynamic attributes with the following component:
```
def my_link(assigns) do
target = if assigns[:new_window], do: "_blank", else: false
extra = assigns_to_attributes(assigns, [:new_window])
assigns =
assigns
|> Phoenix.LiveView.assign(:target, target)
|> Phoenix.LiveView.assign(:extra, extra)
~H"""
<a href={@href} target={@target} {@extra}>
<%= render_slot(@inner_block) %>
</a>
"""
end
```
The above would result in the following rendered HTML:
```
<a href="/" target="_blank" id="1" class="my-class">Home</a>
```
The second argument (optional) to `assigns_to_attributes` is a list of keys to exclude. It typically includes reserved keys by the component itself, which either do not belong in the markup, or are already handled explicitly by the component.
### component(func, assigns \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L629)
Renders a component defined by the given function.
This function is rarely invoked directly by users. Instead, it is used by `~H` to render [`Phoenix.Component`](phoenix.component)s. For example, the following:
```
<MyApp.Weather.city name="Kraków" />
```
Is the same as:
```
<%= component(&MyApp.Weather.city/1, name: "Kraków") %>
```
### form(assigns)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L1098)
Renders a form function component.
This function is built on top of [`Phoenix.HTML.Form.form_for/4`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Form.html#form_for/4). For more information about options and how to build inputs, see [`Phoenix.HTML.Form`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Form.html).
#### Options
The following attribute is required:
* `:for` - the form source data
The following attributes are optional:
* `:action` - the action to submit the form on. This attribute must be given if you intend to submit the form to a URL without LiveView.
* `:as` - the server side parameter in which all params for this form will be collected (i.e. `as: :user_params` would mean all fields for this form will be accessed as `conn.params.user_params` server side). Automatically inflected when a changeset is given.
* `:multipart` - when true, sets enctype to "multipart/form-data". Required when uploading files
* `:method` - the HTTP method. It is only used if an `:action` is given. If the method is not "get" nor "post", an input tag with name `_method` is generated along-side the form tag. Defaults to "post".
* `:csrf_token` - a token to authenticate the validity of requests. One is automatically generated when an action is given and the method is not "get". When set to false, no token is generated.
* `:errors` - use this to manually pass a keyword list of errors to the form (for example from `conn.assigns[:errors]`). This option is only used when a connection is used as the form source and it will make the errors available under `f.errors`
* `:id` - the ID of the form attribute. If an ID is given, all form inputs will also be prefixed by the given ID
All further assigns will be passed to the form tag.
#### Examples
### Inside LiveView
The `:for` attribute is typically an [`Ecto.Changeset`](../ecto/ecto.changeset):
```
<.form let={f} for={@changeset} phx-change="change_name">
<%= text_input f, :name %>
</.form>
<.form let={user_form} for={@changeset} multipart phx-change="change_user" phx-submit="save_user">
<%= text_input user_form, :name %>
<%= submit "Save" %>
</.form>
```
Notice how both examples use `phx-change`. The LiveView must implement the `phx-change` event and store the input values as they arrive on change. This is important because, if an unrelated change happens on the page, LiveView should re-render the inputs with their updated values. Without `phx-change`, the inputs would otherwise be cleared. Alternatively, you can use `phx-update="ignore"` on the form to discard any updates.
The `:for` attribute can also be an atom, in case you don't have an existing data layer but you want to use the existing form helpers. In this case, you need to pass the input values explicitly as they change (or use `phx-update="ignore"` as per the previous paragraph):
```
<.form let={user_form} for={:user} multipart phx-change="change_user" phx-submit="save_user">
<%= text_input user_form, :name, value: @user_name %>
<%= submit "Save" %>
</.form>
```
However, if you don't have a data layer, it may be more straight-forward to drop the `form` component altogether and simply rely on HTML:
```
<form multipart phx-change="change_user" phx-submit="save_user">
<input type="text" name="user[name]" value={@user_name}>
<input type="submit" name="Save">
</form>
```
### Outside LiveView
The `form` component can still be used to submit forms outside of LiveView. In such cases, the `action` attribute MUST be given. Without said attribute, the `form` method and csrf token are discarded.
```
<.form let={f} for={@changeset} action={Routes.comment_path(:create, @comment)}>
<%= text_input f, :body %>
</.form>
```
### inner\_block(name, list)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L781)
Define a inner block, generally used by slots.
This macro is mostly used by HTML engines that provides a `slot` implementation and rarely called directly. The `name` must be the assign name the slot/block will be stored under.
If you're using HEEx templates, you should use its higher level `<:slot>` notation instead. See [`Phoenix.Component`](phoenix.component) for more information.
### live\_component(assigns)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L469)
A function component for rendering [`Phoenix.LiveComponent`](phoenix.livecomponent) within a parent LiveView.
While `LiveView`s can be nested, each LiveView starts its own process. A `LiveComponent` provides similar functionality to `LiveView`, except they run in the same process as the `LiveView`, with its own encapsulated state. That's why they are called stateful components.
See [`Phoenix.LiveComponent`](phoenix.livecomponent) for more information.
#### Examples
`.live_component` requires the component `:module` and its `:id` to be given:
```
<.live_component module={MyApp.WeatherComponent} id="thermostat" city="Kraków" />
```
The `:id` is used to identify this `LiveComponent` throughout the LiveView lifecycle. Note the `:id` won't necessarily be used as the DOM ID. That's up to the component.
### live\_component(component, assigns, do\_block \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L537)
This macro is deprecated. Use .live\_component (live\_component/1) instead. Deprecated API for rendering `LiveComponent`.
#### Upgrading
In order to migrate from `<%= live_component ... %>` to `<.live_component>`, you must first:
1. Migrate from `~L` sigil and `.leex` templates to `~H` sigil and `.heex` templates
2. Then instead of:
```
<%= live_component MyModule, id: "hello" do %>
...
<% end %>
```
You should do:
```
<.live_component module={MyModule} id="hello">
...
</.live_component>
```
3. If your component is using [`render_block/2`](#render_block/2), replace it by [`render_slot/2`](#render_slot/2)
### live\_file\_input(conf, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L936)
Builds a file input tag for a LiveView upload.
Options may be passed through to the tag builder for custom attributes.
#### Drag and Drop
Drag and drop is supported by annotating the droppable container with a `phx-drop-target` attribute pointing to the DOM ID of the file input. By default, the file input ID is the upload `ref`, so the following markup is all that is required for drag and drop support:
```
<div class="container" phx-drop-target={@uploads.avatar.ref}>
...
<%= live_file_input @uploads.avatar %>
</div>
```
#### Examples
```
<%= live_file_input @uploads.avatar %>
```
### live\_flash(other, key)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L837)
Returns the flash message from the LiveView flash assign.
#### Examples
```
<p class="alert alert-info"><%= live_flash(@flash, :info) %></p>
<p class="alert alert-danger"><%= live_flash(@flash, :error) %></p>
```
### live\_img\_preview(entry, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L901)
Generates an image preview on the client for a selected file.
#### Examples
```
<%= for entry <- @uploads.avatar.entries do %>
<%= live_img_preview entry, width: 75 %>
<% end %>
```
### live\_patch(text, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L273)
Generates a link that will patch the current LiveView.
When navigating to the current LiveView, [`Phoenix.LiveView.handle_params/3`](phoenix.liveview#c:handle_params/3) is immediately invoked to handle the change of params and URL state. Then the new state is pushed to the client, without reloading the whole page while also maintaining the current scroll position. For live redirects to another LiveView, use [`live_redirect/2`](#live_redirect/2).
#### Options
* `:to` - the required path to link to.
* `:replace` - the flag to replace the current history or push a new state. Defaults `false`.
All other options are forwarded to the anchor tag.
#### Examples
```
<%= live_patch "home", to: Routes.page_path(@socket, :index) %>
<%= live_patch "next", to: Routes.live_path(@socket, MyLive, @page + 1) %>
<%= live_patch to: Routes.live_path(@socket, MyLive, dir: :asc), replace: false do %>
Sort By Price
<% end %>
```
### live\_redirect(text, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L327)
Generates a link that will redirect to a new LiveView of the same live session.
The current LiveView will be shut down and a new one will be mounted in its place, without reloading the whole page. This can also be used to remount the same LiveView, in case you want to start fresh. If you want to navigate to the same LiveView without remounting it, use [`live_patch/2`](#live_patch/2) instead.
*Note*: The live redirects are only supported between two LiveViews defined under the same live session. See [`Phoenix.LiveView.Router.live_session/3`](phoenix.liveview.router#live_session/3) for more details.
#### Options
* `:to` - the required path to link to.
* `:replace` - the flag to replace the current history or push a new state. Defaults `false`.
All other options are forwarded to the anchor tag.
#### Examples
```
<%= live_redirect "home", to: Routes.page_path(@socket, :index) %>
<%= live_redirect "next", to: Routes.live_path(@socket, MyLive, @page + 1) %>
<%= live_redirect to: Routes.live_path(@socket, MyLive, dir: :asc), replace: false do %>
Sort By Price
<% end %>
```
### live\_render(conn\_or\_socket, view, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L430)
Renders a LiveView within a template.
This is useful in two situations:
* When rendering a child LiveView inside a LiveView
* When rendering a LiveView inside a regular (non-live) controller/view
#### Options
* `:session` - a map of binary keys with extra session data to be serialized and sent to the client. All session data currently in the connection is automatically available in LiveViews. You can use this option to provide extra data. Remember all session data is serialized and sent to the client, so you should always keep the data in the session to a minimum. For example, instead of storing a User struct, you should store the "user\_id" and load the User when the LiveView mounts.
* `:container` - an optional tuple for the HTML tag and DOM attributes to be used for the LiveView container. For example: `{:li, style: "color: blue;"}`. By default it uses the module definition container. See the "Containers" section below for more information.
* `:id` - both the DOM ID and the ID to uniquely identify a LiveView. An `:id` is automatically generated when rendering root LiveViews but it is a required option when rendering a child LiveView.
* `:sticky` - an optional flag to maintain the LiveView across live redirects, even if it is nested within another LiveView. If you are rendering the sticky view within your live layout, make sure that the sticky view itself does not use the same layout. You can do so by returning `{:ok, socket, layout: false}` from mount.
#### Examples
When rendering from a controller/view, you can call:
```
<%= live_render(@conn, MyApp.ThermostatLive) %>
```
Or:
```
<%= live_render(@conn, MyApp.ThermostatLive, session: %{"home_id" => @home.id}) %>
```
Within another LiveView, you must pass the `:id` option:
```
<%= live_render(@socket, MyApp.ThermostatLive, id: "thermostat") %>
```
#### Containers
When a `LiveView` is rendered, its contents are wrapped in a container. By default, the container is a `div` tag with a handful of `LiveView` specific attributes.
The container can be customized in different ways:
* You can change the default `container` on `use Phoenix.LiveView`:
```
use Phoenix.LiveView, container: {:tr, id: "foo-bar"}
```
* You can override the container tag and pass extra attributes when calling `live_render` (as well as on your `live` call in your router):
```
live_render socket, MyLiveView, container: {:tr, class: "highlight"}
```
### live\_title\_tag(title, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L978)
Renders a title tag with automatic prefix/suffix on `@page_title` updates.
#### Examples
```
<%= live_title_tag assigns[:page_title] || "Welcome", prefix: "MyApp – " %>
<%= live_title_tag assigns[:page_title] || "Welcome", suffix: " – MyApp" %>
```
### render\_block(inner\_block, argument \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L667)
This macro is deprecated. Use render\_slot/2 instead. Renders the `@inner_block` assign of a component with the given `argument`.
```
<%= render_block(@inner_block, value: @value)
```
This function is deprecated for function components. Use [`render_slot/2`](#render_slot/2) instead.
### render\_slot(slot, argument \\ nil)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L731)
Renders a slot entry with the given optional `argument`.
```
<%= render_slot(@inner_block, @form) %>
```
If multiple slot entries are defined for the same slot, [`render_slot/2`](#render_slot/2) will automatically render all entries, merging their contents. In case you want to use the entries' attributes, you need to iterate over the list to access each slot individually.
For example, imagine a table component:
```
<.table rows={@users}>
<:col let={user} label="Name">
<%= user.name %>
</:col>
<:col let={user} label="Address">
<%= user.address %>
</:col>
</.table>
```
At the top level, we pass the rows as an assign and we define a `:col` slot for each column we want in the table. Each column also has a `label`, which we are going to use in the table header.
Inside the component, you can render the table with headers, rows, and columns:
```
def table(assigns) do
~H"""
<table>
<tr>
<%= for col <- @col do %>
<th><%= col.label %></th>
<% end %>
</tr>
<%= for row <- @rows do %>
<tr>
<%= for col <- @col do %>
<td><%= render_slot(col, row) %></td>
<% end %>
</tr>
<% end %>
</table>
"""
end
```
### sigil\_H(arg, list)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L180)
The `~H` sigil for writing HEEx templates inside source files.
> Note: `HEEx` requires Elixir >= `1.12.0` in order to provide accurate file:line:column information in error messages. Earlier Elixir versions will work but will show inaccurate error messages.
>
>
> Note: The HEEx HTML formatter requires Elixir >= 1.13.0. See the [`Phoenix.LiveView.HTMLFormatter`](phoenix.liveview.htmlformatter) for more information on template formatting.
>
>
`HEEx` is a HTML-aware and component-friendly extension of Elixir Embedded language ([`EEx`](https://hexdocs.pm/eex/EEx.html)) that provides:
* Built-in handling of HTML attributes
* An HTML-like notation for injecting function components
* Compile-time validation of the structure of the template
* The ability to minimize the amount of data sent over the wire
#### Example
```
~H"""
<div title="My div" class={@class}>
<p>Hello <%= @name %></p>
<MyApp.Weather.city name="Kraków"/>
</div>
"""
```
#### Syntax
`HEEx` is built on top of Embedded Elixir ([`EEx`](https://hexdocs.pm/eex/EEx.html)). In this section, we are going to cover the basic constructs in `HEEx` templates as well as its syntax extensions.
### Interpolation
Both `HEEx` and [`EEx`](https://hexdocs.pm/eex/EEx.html) templates use `<%= ... %>` for interpolating code inside the body of HTML tags:
```
<p>Hello, <%= @name %></p>
```
Similarly, conditionals and other block Elixir constructs are supported:
```
<%= if @show_greeting? do %>
<p>Hello, <%= @name %></p>
<% end %>
```
Note we don't include the equal sign `=` in the closing `<% end %>` tag (because the closing tag does not output anything).
There is one important difference between `HEEx` and Elixir's builtin [`EEx`](https://hexdocs.pm/eex/EEx.html). `HEEx` uses a specific annotation for interpolating HTML tags and attributes. Let's check it out.
### HEEx extension: Defining attributes
Since `HEEx` must parse and validate the HTML structure, code interpolation using `<%= ... %>` and `<% ... %>` are restricted to the body (inner content) of the HTML/component nodes and it cannot be applied within tags.
For instance, the following syntax is invalid:
```
<div class="<%= @class %>">
...
</div>
```
Instead do:
```
<div class={@class}>
...
</div>
```
You can put any Elixir expression between `{ ... }`. For example, if you want to set classes, where some are static and others are dynamic, you can using string interpolation:
```
<div class={"btn btn-#{@type}"}>
...
</div>
```
The following attribute values have special meaning:
* `true` - if a value is `true`, the attribute is rendered with no value at all. For example, `<input required={true}>` is the same as `<input required>`;
* `false` or `nil` - if a value is `false` or `nil`, the attribute is not rendered;
* `list` (only for the `class` attribute) - each element of the list is processed as a different class. `nil` and `false` elements are discarded.
For multiple dynamic attributes, you can use the same notation but without assigning the expression to any specific attribute.
```
<div {@dynamic_attrs}>
...
</div>
```
The expression inside `{...}` must be either a keyword list or a map containing the key-value pairs representing the dynamic attributes.
You can pair this notation [`assigns_to_attributes/2`](#assigns_to_attributes/2) to strip out any internal LiveView attributes and user-defined assigns from being expanded into the HTML tag:
```
<div {assigns_to_attributes(assigns, [:visible])}>
...
</div>
```
The above would add all caller attributes into the HTML, but strip out LiveView assigns like slots, as well as user-defined assigns like `:visible` that are not meant to be added to the HTML itself. This approach is useful to allow a component to accept arbitrary HTML attributes like class, ARIA attributes, etc.
### HEEx extension: Defining function components
Function components are stateless components implemented as pure functions with the help of the [`Phoenix.Component`](phoenix.component) module. They can be either local (same module) or remote (external module).
`HEEx` allows invoking these function components directly in the template using an HTML-like notation. For example, a remote function:
```
<MyApp.Weather.city name="Kraków"/>
```
A local function can be invoked with a leading dot:
```
<.city name="Kraków"/>
```
where the component could be defined as follows:
```
defmodule MyApp.Weather do
use Phoenix.Component
def city(assigns) do
~H"""
The chosen city is: <%= @name %>.
"""
end
def country(assigns) do
~H"""
The chosen country is: <%= @name %>.
"""
end
end
```
It is typically best to group related functions into a single module, as opposed to having many modules with a single `render/1` function. Function components support other important features, such as slots. You can learn more about components in [`Phoenix.Component`](phoenix.component).
### sigil\_L(arg, list)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L21)
This macro is deprecated. Use ~H instead. Provides `~L` sigil with HTML safe Live EEx syntax inside source files.
```
iex> ~L"""
...> Hello <%= "world" %>
...> """
{:safe, ["Hello ", "world", "\n"]}
```
### upload\_errors(conf)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L860)
Returns the entry errors for an upload.
The following error may be returned:
* `:too_many_files` - The number of selected files exceeds the `:max_entries` constraint
#### Examples
```
def error_to_string(:too_many_files), do: "You have selected too many files"
<%= for err <- upload_errors(@uploads.avatar) do %>
<div class="alert alert-danger">
<%= error_to_string(err) %>
</div>
<% end %>
```
### upload\_errors(conf, entry)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/helpers.ex#L885)
Returns the entry errors for an upload.
The following errors may be returned:
* `:too_large` - The entry exceeds the `:max_file_size` constraint
* `:not_accepted` - The entry does not match the `:accept` MIME types
#### Examples
```
def error_to_string(:too_large), do: "Too large"
def error_to_string(:not_accepted), do: "You have selected an unacceptable file type"
<%= for entry <- @uploads.avatar.entries do %>
<%= for err <- upload_errors(@uploads.avatar, entry) do %>
<div class="alert alert-danger">
<%= error_to_string(err) %>
</div>
<% end %>
<% end %>
```
| programming_docs |
phoenix Phoenix.LiveComponent behaviour Phoenix.LiveComponent behaviour
================================
LiveComponents are a mechanism to compartmentalize state, markup, and events in LiveView.
LiveComponents are defined by using [`Phoenix.LiveComponent`](phoenix.livecomponent#content) and are used by calling [`Phoenix.LiveView.Helpers.live_component/1`](phoenix.liveview.helpers#live_component/1) in a parent LiveView. They run inside the LiveView process but have their own state and life-cycle. For this reason, they are also often called "stateful components". This is a contrast to [`Phoenix.Component`](phoenix.component), also known as "function components", which are stateless.
The smallest LiveComponent only needs to define a [`render/1`](#c:render/1) function:
```
defmodule HeroComponent do
# If you generated an app with mix phx.new --live,
# the line below would be: use MyAppWeb, :live_component
use Phoenix.LiveComponent
def render(assigns) do
~H"""
<div class="hero"><%= @content %></div>
"""
end
end
```
A LiveComponent is rendered as:
```
<.live_component module={HeroComponent} id="hero" content={@content} />
```
You must always pass the `module` and `id` attributes. The `id` will be available as an assign and it must be used to uniquely identify the component. All other attributes will be available as assigns inside the LiveComponent.
Life-cycle
-----------
Stateful components are identified by the component module and their ID. Therefore, two stateful components with the same module and ID are treated as the same component. We often tie the component ID to some application based ID:
```
<.live_component module={UserComponent} id={@user.id} user={@user} />
```
When [`live_component/1`](phoenix.liveview.helpers#live_component/1) is called, [`mount/1`](#c:mount/1) is called once, when the component is first added to the page. [`mount/1`](#c:mount/1) receives the `socket` as argument. Then [`update/2`](#c:update/2) is invoked with all of the assigns given to [`live_component/1`](phoenix.liveview.helpers#live_component/1). If [`update/2`](#c:update/2) is not defined all assigns are simply merged into the socket. After the component is updated, [`render/1`](#c:render/1) is called with all assigns. On first render, we get:
```
mount(socket) -> update(assigns, socket) -> render(assigns)
```
On further rendering:
```
update(assigns, socket) -> render(assigns)
```
The given `id` is not automatically used as the DOM ID. If you want to set a DOM ID, it is your responsibility to do so when rendering:
```
defmodule UserComponent do
use Phoenix.LiveComponent
def render(assigns) do
~H"""
<div id={"user-#{@id}"} class="user">
<%= @user.name %>
</div>
"""
end
end
```
Targeting Component Events
---------------------------
Stateful components can also implement the [`handle_event/3`](#c:handle_event/3) callback that works exactly the same as in LiveView. For a client event to reach a component, the tag must be annotated with a `phx-target`. If you want to send the event to yourself, you can simply use the `@myself` assign, which is an *internal unique reference* to the component instance:
```
<a href="#" phx-click="say_hello" phx-target={@myself}>
Say hello!
</a>
```
Note that `@myself` is not set for stateless components, as they cannot receive events.
If you want to target another component, you can also pass an ID or a class selector to any element inside the targeted component. For example, if there is a `UserComponent` with the DOM ID of `"user-13"`, using a query selector, we can send an event to it with:
```
<a href="#" phx-click="say_hello" phx-target="#user-13">
Say hello!
</a>
```
In both cases, [`handle_event/3`](#c:handle_event/3) will be called with the "say\_hello" event. When [`handle_event/3`](#c:handle_event/3) is called for a component, only the diff of the component is sent to the client, making them extremely efficient.
Any valid query selector for `phx-target` is supported, provided that the matched nodes are children of a LiveView or LiveComponent, for example to send the `close` event to multiple components:
```
<a href="#" phx-click="close" phx-target="#modal, #sidebar">
Dismiss
</a>
```
Preloading and update
----------------------
Stateful components also support an optional [`preload/1`](#c:preload/1) callback. The [`preload/1`](#c:preload/1) callback is useful when multiple components of the same type are rendered on the page and you want to preload or augment their data in batches.
For each rendering, the optional [`preload/1`](#c:preload/1) and [`update/2`](#c:update/2) callbacks are called before [`render/1`](#c:render/1).
So on first render, the following callbacks will be invoked:
```
preload(list_of_assigns) -> mount(socket) -> update(assigns, socket) -> render(assigns)
```
On subsequent renders, these callbacks will be invoked:
```
preload(list_of_assigns) -> update(assigns, socket) -> render(assigns)
```
To provide a more complete understanding of why both callbacks are necessary, let's see an example. Imagine you are implementing a component and the component needs to load some state from the database. For example:
```
<.live_component module={UserComponent} id={user_id} />
```
A possible implementation would be to load the user on the [`update/2`](#c:update/2) callback:
```
def update(assigns, socket) do
user = Repo.get!(User, assigns.id)
{:ok, assign(socket, :user, user)}
end
```
However, the issue with said approach is that, if you are rendering multiple user components in the same page, you have a N+1 query problem. The [`preload/1`](#c:preload/1) callback helps address this problem as it is invoked with a list of assigns for all components of the same type. For example, instead of implementing [`update/2`](#c:update/2) as above, one could implement:
```
def preload(list_of_assigns) do
list_of_ids = Enum.map(list_of_assigns, & &1.id)
users =
from(u in User, where: u.id in ^list_of_ids, select: {u.id, u})
|> Repo.all()
|> Map.new()
Enum.map(list_of_assigns, fn assigns ->
Map.put(assigns, :user, users[assigns.id])
end)
end
```
Now only a single query to the database will be made. In fact, the preloading algorithm is a breadth-first tree traversal, which means that even for nested components, the amount of queries are kept to a minimum.
Finally, note that [`preload/1`](#c:preload/1) must return an updated `list_of_assigns`, keeping the assigns in the same order as they were given.
Slots
------
LiveComponent can also receive slots, in the same way as a [`Phoenix.Component`](phoenix.component):
```
<.live_component module={MyComponent} id={@data.id} >
<div>Inner content here</div>
</.live_component>
```
If the LiveComponent defines an [`update/2`](#c:update/2), be sure that the socket it returns includes the `:inner_block` assign it received.
See the docs for [`Phoenix.Component`](phoenix.component) for more information.
Live patches and live redirects
--------------------------------
A template rendered inside a component can use [`Phoenix.LiveView.Helpers.live_patch/2`](phoenix.liveview.helpers#live_patch/2) and [`Phoenix.LiveView.Helpers.live_redirect/2`](phoenix.liveview.helpers#live_redirect/2) calls. The [`live_patch/2`](phoenix.liveview.helpers#live_patch/2) is always handled by the parent`LiveView`, as components do not provide `handle_params`.
Managing state
---------------
Now that we have learned how to define and use components, as well as how to use [`preload/1`](#c:preload/1) as a data loading optimization, it is important to talk about how to manage state in components.
Generally speaking, you want to avoid both the parent LiveView and the LiveComponent working on two different copies of the state. Instead, you should assume only one of them to be the source of truth. Let's discuss the two different approaches in detail.
Imagine a scenario where a LiveView represents a board with each card in it as a separate stateful LiveComponent. Each card has a form to allow update of the card title directly in the component, as follows:
```
defmodule CardComponent do
use Phoenix.LiveComponent
def render(assigns) do
~H"""
<form phx-submit="..." phx-target={@myself}>
<input name="title"><%= @card.title %></input>
...
</form>
"""
end
...
end
```
We will see how to organize the data flow to keep either the board LiveView or the card LiveComponents as the source of truth.
### LiveView as the source of truth
If the board LiveView is the source of truth, it will be responsible for fetching all of the cards in a board. Then it will call [`live_component/1`](phoenix.liveview.helpers#live_component/1) for each card, passing the card struct as argument to `CardComponent`:
```
<%= for card <- @cards do %>
<.live_component module={CardComponent} card={card} id={card.id} board_id={@id} />
<% end %>
```
Now, when the user submits the form, `CardComponent.handle_event/3` will be triggered. However, if the update succeeds, you must not change the card struct inside the component. If you do so, the card struct in the component will get out of sync with the LiveView. Since the LiveView is the source of truth, you should instead tell the LiveView that the card was updated.
Luckily, because the component and the view run in the same process, sending a message from the LiveComponent to the parent LiveView is as simple as sending a message to `self()`:
```
defmodule CardComponent do
...
def handle_event("update_title", %{"title" => title}, socket) do
send self(), {:updated_card, %{socket.assigns.card | title: title}}
{:noreply, socket}
end
end
```
The LiveView then receives this event using [`Phoenix.LiveView.handle_info/2`](phoenix.liveview#c:handle_info/2):
```
defmodule BoardView do
...
def handle_info({:updated_card, card}, socket) do
# update the list of cards in the socket
{:noreply, updated_socket}
end
end
```
Because the list of cards in the parent socket was updated, the parent LiveView will be re-rendered, sending the updated card to the component. So in the end, the component does get the updated card, but always driven from the parent.
Alternatively, instead of having the component send a message directly to the parent view, the component could broadcast the update using [`Phoenix.PubSub`](https://hexdocs.pm/phoenix_pubsub/2.0.0/Phoenix.PubSub.html). Such as:
```
defmodule CardComponent do
...
def handle_event("update_title", %{"title" => title}, socket) do
message = {:updated_card, %{socket.assigns.card | title: title}}
Phoenix.PubSub.broadcast(MyApp.PubSub, board_topic(socket), message)
{:noreply, socket}
end
defp board_topic(socket) do
"board:" <> socket.assigns.board_id
end
end
```
As long as the parent LiveView subscribes to the `board:<ID>` topic, it will receive updates. The advantage of using PubSub is that we get distributed updates out of the box. Now, if any user connected to the board changes a card, all other users will see the change.
### LiveComponent as the source of truth
If each card LiveComponent is the source of truth, then the board LiveView must no longer fetch the card structs from the database. Instead, the board LiveView must only fetch the card ids, then render each component only by passing an ID:
```
<%= for card_id <- @card_ids do %>
<.live_component module={CardComponent} id={card_id} board_id={@id} />
<% end %>
```
Now, each CardComponent will load its own card. Of course, doing so per card could be expensive and lead to N queries, where N is the number of cards, so we can use the [`preload/1`](#c:preload/1) callback to make it efficient.
Once the card components are started, they can each manage their own card, without concerning themselves with the parent LiveView.
However, note that components do not have a [`Phoenix.LiveView.handle_info/2`](phoenix.liveview#c:handle_info/2) callback. Therefore, if you want to track distributed changes on a card, you must have the parent LiveView receive those events and redirect them to the appropriate card. For example, assuming card updates are sent to the "board:ID" topic, and that the board LiveView is subscribed to said topic, one could do:
```
def handle_info({:updated_card, card}, socket) do
send_update CardComponent, id: card.id, board_id: socket.assigns.id
{:noreply, socket}
end
```
With [`Phoenix.LiveView.send_update/3`](phoenix.liveview#send_update/3), the `CardComponent` given by `id` will be invoked, triggering both preload and update callbacks, which will load the most up to date data from the database.
Cost of stateful components
----------------------------
The internal infrastructure LiveView uses to keep track of stateful components is very lightweight. However, be aware that in order to provide change tracking and to send diffs over the wire, all of the components' assigns are kept in memory - exactly as it is done in LiveViews themselves.
Therefore it is your responsibility to keep only the assigns necessary in each component. For example, avoid passing all of LiveView's assigns when rendering a component:
```
<.live_component module={MyComponent} {assigns} />
```
Instead pass only the keys that you need:
```
<.live_component module={MyComponent} user={@user} org={@org} />
```
Luckily, because LiveViews and LiveComponents are in the same process, they share the data structure representations in memory. For example, in the code above, the view and the component will share the same copies of the `@user` and `@org` assigns.
You should also avoid using stateful components to provide abstract DOM components. As a guideline, a good LiveComponent encapsulates application concerns and not DOM functionality. For example, if you have a page that shows products for sale, you can encapsulate the rendering of each of those products in a component. This component may have many buttons and events within it. On the opposite side, do not write a component that is simply encapsulating generic DOM components. For instance, do not do this:
```
defmodule MyButton do
use Phoenix.LiveComponent
def render(assigns) do
~H"""
<button class="css-framework-class" phx-click="click">
<%= @text %>
</button>
"""
end
def handle_event("click", _, socket) do
_ = socket.assigns.on_click.()
{:noreply, socket}
end
end
```
Instead, it is much simpler to create a function component:
```
def my_button(%{text: _, click: _} = assigns) do
~H"""
<button class="css-framework-class" phx-click={@click}>
<%= @text %>
</button>
"""
end
```
If you keep components mostly as an application concern with only the necessary assigns, it is unlikely you will run into issues related to stateful components.
Limitations
------------
### Live Components require a single HTML tag at the root
Live Components require a single HTML tag at the root. It is not possible to have components that render only text or multiple tags.
### SVG support
Given components compartmentalize markup on the server, they are also rendered in isolation on the client, which provides great performance benefits on the client too.
However, when rendering components on the client, the client needs to choose the mime type of the component contents, which defaults to HTML. This is the best default but in some cases it may lead to unexpected results.
For example, if you are rendering SVG, the SVG will be interpreted as HTML. This may work just fine for most components but you may run into corner cases. For example, the `<image>` SVG tag may be rewritten to the `<img>` tag, since `<image>` is an obsolete HTML tag.
Luckily, there is a simple solution to this problem. Since SVG allows `<svg>` tags to be nested, you can wrap the component content into an `<svg>` tag. This will ensure that it is correctly interpreted by the browser.
Summary
========
Callbacks
----------
[handle\_event( event, unsigned\_params, socket )](#c:handle_event/3) [mount(socket)](#c:mount/1) [preload(list\_of\_assigns)](#c:preload/1) [render(assigns)](#c:render/1) [update(assigns, socket)](#c:update/2) Callbacks
==========
### handle\_event( event, unsigned\_params, socket )[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_component.ex#L466)
```
@callback handle_event(
event :: binary(),
unsigned_params :: Phoenix.LiveView.unsigned_params(),
socket :: Phoenix.LiveView.Socket.t()
) ::
{:noreply, Phoenix.LiveView.Socket.t()}
| {:reply, map(), Phoenix.LiveView.Socket.t()}
```
### mount(socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_component.ex#L451)
```
@callback mount(socket :: Phoenix.LiveView.Socket.t()) ::
{:ok, Phoenix.LiveView.Socket.t()}
| {:ok, Phoenix.LiveView.Socket.t(), keyword()}
```
### preload(list\_of\_assigns)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_component.ex#L454)
```
@callback preload(list_of_assigns :: [Phoenix.LiveView.Socket.assigns()]) ::
list_of_assigns :: [Phoenix.LiveView.Socket.assigns()]
```
### render(assigns)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_component.ex#L460)
```
@callback render(assigns :: Phoenix.LiveView.Socket.assigns()) ::
Phoenix.LiveView.Rendered.t()
```
### update(assigns, socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_component.ex#L457)
```
@callback update(
assigns :: Phoenix.LiveView.Socket.assigns(),
socket :: Phoenix.LiveView.Socket.t()
) ::
{:ok, Phoenix.LiveView.Socket.t()}
```
phoenix Phoenix.LiveView.Comprehension Phoenix.LiveView.Comprehension
===============================
The struct returned by for-comprehensions in .heex templates.
See a description about its fields and use cases in [`Phoenix.LiveView.Engine`](phoenix.liveview.engine) docs.
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/engine.ex#L64)
```
@type t() :: %Phoenix.LiveView.Comprehension{
dynamics: [
[
iodata()
| Phoenix.LiveView.Rendered.t()
| t()
| Phoenix.LiveView.Component.t()
]
],
fingerprint: integer(),
static: [String.t()]
}
```
phoenix Uploads Uploads
========
LiveView supports interactive file uploads with progress for both direct to server uploads as well as direct-to-cloud [external uploads](uploads-external) on the client.
### Built-in Features
* Accept specification - Define accepted file types, max number of entries, max file size, etc. When the client selects file(s), the file metadata is automatically validated against the specification. See [`Phoenix.LiveView.allow_upload/3`](phoenix.liveview#allow_upload/3).
* Reactive entries - Uploads are populated in an `@uploads` assign in the socket. Entries automatically respond to progress, errors, cancellation, etc.
* Drag and drop - Use the `phx-drop-target` attribute to enable. See [`Phoenix.LiveView.Helpers.live_file_input/2`](phoenix.liveview.helpers#live_file_input/2).
Allow uploads
--------------
You enable an upload, typically on mount, via [`allow_upload/3`](phoenix.liveview#allow_upload/3):
```
@impl Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:uploaded_files, [])
|> allow_upload(:avatar, accept: ~w(.jpg .jpeg), max_entries: 2)}
end
```
That's it for now! We will come back to the LiveView to implement some form- and upload-related callbacks later, but most of the functionality around uploads takes place in the template.
Render reactive elements
-------------------------
Use the [`Phoenix.LiveView.Helpers.live_file_input/2`](phoenix.liveview.helpers#live_file_input/2) file input generator to render a file input for the upload:
```
<%# lib/my_app_web/live/upload_live.html.heex %>
<form id="upload-form" phx-submit="save" phx-change="validate">
<%= live_file_input @uploads.avatar %>
<button type="submit">Upload</button>
</form>
```
> **Important:** You must bind `phx-submit` and `phx-change` on the form.
>
>
Note that while [`live_file_input/2`](phoenix.liveview.helpers#live_file_input/2) allows you to set additional attributes on the file input, many attributes such as `id`, `accept`, and `multiple` will be set automatically based on the [`allow_upload/3`](phoenix.liveview#allow_upload/3) spec.
Reactive updates to the template will occur as the end-user interacts with the file input.
### Upload entries
Uploads are populated in an `@uploads` assign in the socket. Each allowed upload contains a *list* of entries, irrespective of the `:max_entries` value in the [`allow_upload/3`](phoenix.liveview#allow_upload/3) spec. These entry structs contain all the information about an upload, including progress, client file info, errors, etc.
Let's look at an annotated example:
```
<%# lib/my_app_web/live/upload_live.html.heex %>
<%# use phx-drop-target with the upload ref to enable file drag and drop %>
<section phx-drop-target={@uploads.avatar.ref}>
<%# render each avatar entry %>
<%= for entry <- @uploads.avatar.entries do %>
<article class="upload-entry">
<figure>
<%# Phoenix.LiveView.Helpers.live_img_preview/2 renders a client-side preview %>
<%= live_img_preview entry %>
<figcaption><%= entry.client_name %></figcaption>
</figure>
<%# entry.progress will update automatically for in-flight entries %>
<progress value={entry.progress} max="100"> <%= entry.progress %>% </progress>
<%# a regular click event whose handler will invoke Phoenix.LiveView.cancel_upload/3 %>
<button phx-click="cancel-upload" phx-value-ref={entry.ref} aria-label="cancel">×</button>
<%# Phoenix.LiveView.Helpers.upload_errors/2 returns a list of error atoms %>
<%= for err <- upload_errors(@uploads.avatar, entry) do %>
<p class="alert alert-danger"><%= error_to_string(err) %></p>
<% end %>
</article>
<% end %>
<%# Phoenix.LiveView.Helpers.upload_errors/1 returns a list of error atoms %>
<%= for err <- upload_errors(@uploads.avatar) do %>
<p class="alert alert-danger"><%= error_to_string(err) %></p>
<% end %>
</section>
```
The `section` element in the example acts as the `phx-drop-target` for the `:avatar` upload. Users can interact with the file input or they can drop files over the element to add new entries.
Upload entries are created when a file is added to the form input and each will exist until it has been consumed, following a successfully completed upload.
### Entry validation
Validation occurs automatically based on any conditions that were specified in [`allow_upload/3`](phoenix.liveview#allow_upload/3) however, as mentioned previously you are required to bind `phx-change` on the form in order for the validation to be performed. Therefore you must implement at least a minimal callback:
```
@impl Phoenix.LiveView
def handle_event("validate", _params, socket) do
{:noreply, socket}
end
```
Entries for files that do not match the [`allow_upload/3`](phoenix.liveview#allow_upload/3) spec will contain errors. Use [`Phoenix.LiveView.Helpers.upload_errors/2`](phoenix.liveview.helpers#upload_errors/2) and your own helper function to render a friendly error message:
```
def error_to_string(:too_large), do: "Too large"
def error_to_string(:not_accepted), do: "You have selected an unacceptable file type"
```
For error messages that affect all entries, use [`Phoenix.LiveView.Helpers.upload_errors/1`](phoenix.liveview.helpers#upload_errors/1), and your own helper function to render a friendly error message:
```
def error_to_string(:too_many_files), do: "You have selected too many files"
```
### Cancel an entry
Upload entries may also be canceled, either programmatically or as a result of a user action. For instance, to handle the click event in the template above, you could do the following:
```
@impl Phoenix.LiveView
def handle_event("cancel-upload", %{"ref" => ref}, socket) do
{:noreply, cancel_upload(socket, :avatar, ref)}
end
```
Consume uploaded entries
-------------------------
When the end-user submits a form containing a [`live_file_input/2`](phoenix.liveview.helpers#live_file_input/2), the JavaScript client first uploads the file(s) before invoking the callback for the form's `phx-submit` event.
Within the callback for the `phx-submit` event, you invoke the [`Phoenix.LiveView.consume_uploaded_entries/3`](phoenix.liveview#consume_uploaded_entries/3) function to process the completed uploads, persisting the relevant upload data alongside the form data:
```
@impl Phoenix.LiveView
def handle_event("save", _params, socket) do
uploaded_files =
consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
dest = Path.join([:code.priv_dir(:my_app), "static", "uploads", Path.basename(path)])
# The `static/uploads` directory must exist for `File.cp!/2` to work.
File.cp!(path, dest)
{:ok, Routes.static_path(socket, "/uploads/#{Path.basename(dest)}")}
end)
{:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))}
end
```
> **Note**: While client metadata cannot be trusted, max file size validations are enforced as each chunk is received when performing direct to server uploads.
>
>
For more information on implementing client-side, direct-to-cloud uploads, see the [External Uploads guide](uploads-external).
Appendix A: UploadLive
-----------------------
A complete example of the LiveView from this guide:
```
# lib/my_app_web/live/upload_live.ex
defmodule MyAppWeb.UploadLive do
use MyAppWeb, :live_view
@impl Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:uploaded_files, [])
|> allow_upload(:avatar, accept: ~w(.jpg .jpeg), max_entries: 2)}
end
@impl Phoenix.LiveView
def handle_event("validate", _params, socket) do
{:noreply, socket}
end
@impl Phoenix.LiveView
def handle_event("cancel-upload", %{"ref" => ref}, socket) do
{:noreply, cancel_upload(socket, :avatar, ref)}
end
@impl Phoenix.LiveView
def handle_event("save", _params, socket) do
uploaded_files =
consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
dest = Path.join([:code.priv_dir(:my_app), "static", "uploads", Path.basename(path)])
File.cp!(path, dest)
{:ok, Routes.static_path(socket, "/uploads/#{Path.basename(dest)}")}
end)
{:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))}
end
defp error_to_string(:too_large), do: "Too large"
defp error_to_string(:too_many_files), do: "You have selected too many files"
defp error_to_string(:not_accepted), do: "You have selected an unacceptable file type"
end
```
[← Previous Page Telemetry](telemetry) [Next Page → Using Gettext for internationalization](using-gettext)
| programming_docs |
phoenix Error and exception handling Error and exception handling
=============================
As with any other Elixir code, exceptions may happen during the LiveView life-cycle. In this section we will describe how LiveView reacts to errors at different stages.
Expected scenarios
-------------------
In this section, we will talk about error cases that you expect to happen within your application. For example, a user filling in a form with invalid data is expected. In a LiveView, we typically handle those cases by storing a change in the LiveView state, which causes the LiveView to be re-rendered with the error message.
We may also use `flash` messages for this. For example, imagine you have a page to manage all "Team members" in an organization. However, if there is only one member left in the organization, they should not be allowed to leave. You may want to handle this by using flash messages:
```
if MyApp.Org.leave(socket.assigns.current_org, member) do
{:noreply, socket}
else
{:noreply, put_flash(socket, :error, "last member cannot leave organization")}
end
```
However, one may argue that, if the last member of an organization cannot leave it, it may be better to not even show the "Leave" button in the UI when the organization has only one member.
Given the button does not appear in the UI, triggering the "leave" when the organization has now only one member is an unexpected scenario. This means we can probably rewrite the code above to:
```
true = MyApp.Org.leave(socket.assigns.current_org, member)
{:noreply, socket}
```
If `leave` returns false by any chance, it will just raise. Or you can even provide a `leave!` function that raises a specific exception:
```
MyApp.Org.leave!(socket.assigns.current_org, member)
{:noreply, socket}
```
However, what will happen with a LiveView in case of exceptions? Let's talk about unexpected scenarios.
Unexpected scenarios
---------------------
Elixir developers tend to write assertive code. This means that, if we expect `leave` to always return true, we can explicitly match on its result, as we did above:
```
true = MyApp.Org.leave(socket.assigns.current_org, member)
{:noreply, socket}
```
If `leave` fails and returns `false`, an exception is raised. It is common for Elixir developers to use exceptions for unexpected scenarios in their Phoenix applications.
For example, if you are building an application where a user may belong to one or more organizations, when accessing the organization page, you may want to check that the user has access to it like this:
```
organizations_query = Ecto.assoc(socket.assigns.current_user, :organizations)
Repo.get!(organizations_query, params["org_id"])
```
The code above builds a query that returns all organizations that belongs to the current user and then validates that the given "org\_id" belongs to the user. If there is no such "org\_id" or if the user has no access to it, an `Ecto.NoResultsError` exception is raised.
During a regular controller request, this exception will be converted to a 404 exception and rendered as a custom error page, as [detailed here](../phoenix/custom_error_pages). To understand how a LiveView reacts to exceptions, we need to consider two scenarios: exceptions on mount and during any event.
Exceptions on mount
--------------------
Given the code on mount runs both on the initial disconnected render and the connected render, an exception on mount will trigger the following events:
Exceptions during disconnected render:
1. An exception on mount is caught and converted to an exception page by Phoenix error views - pretty much like the way it works with controllers
Exceptions during connected render:
1. An exception on mount will crash the LiveView process - which will be logged
2. Once the client has noticed the crash during `mount`, it will fully reload the page
3. Reloading the page will start a disconnected render, that will cause `mount` to be invoked again and most likely raise the same exception. Except this time it will be caught and converted to an exception page by Phoenix error views
In other words, LiveView will reload the page in case of errors, making it fail as if LiveView was not involved in the rendering in the first place.
Exceptions on events (`handle_info`, `handle_event`, etc)
----------------------------------------------------------
If the error happens during an event, the LiveView process will crash. The client will notice the error and remount the LiveView - without reloading the page. This is enough to update the page and show the user the latest information.
For example, let's say two users try to leave the organization at the same time. In this case, both of them see the "Leave" button, but our `leave` function call will succeed only for one of them:
```
true = MyApp.Org.leave(socket.assigns.current_org, member)
{:noreply, socket}
```
When the exception raises, the client will remount the LiveView. Once you remount, your code will now notice that there is only one user in the organization and therefore no longer show the "Leave" button. In other words, by remounting, we often update the state of the page, allowing exceptions to be automatically handled.
Note that the choice between conditionally checking on the result of the `leave` function with an `if`, or simply asserting it returns `true`, is completely up to you. If the likelihood of everyone leaving the organization at the same time is low, then you may as well treat it as an unexpected scenario. Although other developers will be more comfortable by explicitly handling those cases. In both scenarios, LiveView has you covered.
[← Previous Page Assigns and HEEx templates](assigns-eex) [Next Page → Live layouts](live-layouts)
phoenix Phoenix.LiveView.Controller Phoenix.LiveView.Controller
============================
Helpers for rendering LiveViews from a controller.
Summary
========
Functions
----------
[live\_render(conn, view, opts \\ [])](#live_render/3) Renders a live view from a Plug request and sends an HTML response from within a controller.
Functions
==========
### live\_render(conn, view, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/controller.ex#L38)
Renders a live view from a Plug request and sends an HTML response from within a controller.
It also automatically sets the `@live_module` assign with the value of the LiveView to be rendered.
#### Options
See [`Phoenix.LiveView.Helpers.live_render/3`](phoenix.liveview.helpers#live_render/3) for all supported options.
#### Examples
```
defmodule ThermostatController do
use MyAppWeb, :controller
# "use MyAppWeb, :controller" should import Phoenix.LiveView.Controller.
# If it does not, you can either import it there or uncomment the line below:
# import Phoenix.LiveView.Controller
def show(conn, %{"id" => thermostat_id}) do
live_render(conn, ThermostatLive, session: %{
"thermostat_id" => thermostat_id,
"current_user_id" => get_session(conn, :user_id)
})
end
end
```
phoenix Phoenix.LiveView.Router Phoenix.LiveView.Router
========================
Provides LiveView routing for Phoenix routers.
Summary
========
Functions
----------
[fetch\_live\_flash(conn, \_)](#fetch_live_flash/2) Fetches the LiveView and merges with the controller flash.
[live(path, live\_view, action \\ nil, opts \\ [])](#live/4) Defines a LiveView route.
[live\_session(name, opts \\ [], list)](#live_session/3) Defines a live session for live redirects within a group of live routes.
Functions
==========
### fetch\_live\_flash(conn, \_)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/router.ex#L315)
Fetches the LiveView and merges with the controller flash.
Replaces the default `:fetch_flash` plug used by [`Phoenix.Router`](https://hexdocs.pm/phoenix/1.6.6/Phoenix.Router.html).
#### Examples
```
defmodule MyAppWeb.Router do
use LiveGenWeb, :router
import Phoenix.LiveView.Router
pipeline :browser do
...
plug :fetch_live_flash
end
...
end
```
### live(path, live\_view, action \\ nil, opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/router.ex#L98)
Defines a LiveView route.
A LiveView can be routed to by using the `live` macro with a path and the name of the LiveView:
```
live "/thermostat", ThermostatLive
```
By default, you can generate a route to this LiveView by using the `live_path` helper:
```
live_path(@socket, ThermostatLive)
```
#### Actions and live navigation
It is common for a LiveView to have multiple states and multiple URLs. For example, you can have a single LiveView that lists all articles on your web app. For each article there is an "Edit" button which, when pressed, opens up a modal on the same page to edit the article. It is a best practice to use live navigation in those cases, so when you click edit, the URL changes to "/articles/1/edit", even though you are still within the same LiveView. Similarly, you may also want to show a "New" button, which opens up the modal to create new entries, and you want this to be reflected in the URL as "/articles/new".
In order to make it easier to recognize the current "action" your LiveView is on, you can pass the action option when defining LiveViews too:
```
live "/articles", ArticleLive.Index, :index
live "/articles/new", ArticleLive.Index, :new
live "/articles/:id/edit", ArticleLive.Index, :edit
```
When an action is given, the generated route helpers are named after the LiveView itself (in the same way as for a controller). For the example above, we will have:
```
article_index_path(@socket, :index)
article_index_path(@socket, :new)
article_index_path(@socket, :edit, 123)
```
The current action will always be available inside the LiveView as the `@live_action` assign, that can be used to render a LiveComponent:
```
<%= if @live_action == :new do %>
<.live_component module={MyAppWeb.ArticleLive.FormComponent} id="form" />
<% end %>
```
Or can be used to show or hide parts of the template:
```
<%= if @live_action == :edit do %>
<%= render("form.html", user: @user) %>
<% end %>
```
Note that `@live_action` will be `nil` if no action is given on the route definition.
#### Options
* `:container` - an optional tuple for the HTML tag and DOM attributes to be used for the LiveView container. For example: `{:li, style: "color: blue;"}`. See [`Phoenix.LiveView.Helpers.live_render/3`](phoenix.liveview.helpers#live_render/3) for more information and examples.
* `:as` - optionally configures the named helper. Defaults to `:live` when using a LiveView without actions or defaults to the LiveView name when using actions.
* `:metadata` - a map to optional feed metadata used on telemetry events and route info, for example: `%{route_name: :foo, access: :user}`.
* `:private` - an optional map of private data to put in the plug connection. for example: `%{route_name: :foo, access: :user}`.
#### Examples
```
defmodule MyApp.Router
use Phoenix.Router
import Phoenix.LiveView.Router
scope "/", MyApp do
pipe_through [:browser]
live "/thermostat", ThermostatLive
live "/clock", ClockLive
live "/dashboard", DashboardLive, container: {:main, class: "row"}
end
end
iex> MyApp.Router.Helpers.live_path(MyApp.Endpoint, MyApp.ThermostatLive)
"/thermostat"
```
### live\_session(name, opts \\ [], list)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/router.ex#L191)
Defines a live session for live redirects within a group of live routes.
[`live_session/3`](#live_session/3) allow routes defined with [`live/4`](#live/4) to support `live_redirect` from the client with navigation purely over the existing websocket connection. This allows live routes defined in the router to mount a new root LiveView without additional HTTP requests to the server.
#### Security Considerations
You must always perform authentication and authorization in your LiveViews. If your application handle both regular HTTP requests and LiveViews, then you must perform authentication and authorization on both. This is important because `live_redirect`s *do not go through the plug pipeline*.
`live_session` can be used to draw boundaries between groups of LiveViews. Redirecting between `live_session`s will always force a full page reload and establish a brand new LiveView connection. This is useful when LiveViews require different authentication strategies or simply when they use different root layouts (as the root layout is not updated between live redirects).
Please [read our guide on the security model](security-model) for a detailed description and general tips on authentication, authorization, and more.
#### Options
* `:session` - The optional extra session map or MFA tuple to be merged with the LiveView session. For example, `%{"admin" => true}`, `{MyMod, :session, []}`. For MFA, the function is invoked, passing the [`Plug.Conn`](https://hexdocs.pm/plug/1.13.3/Plug.Conn.html) struct is prepended to the arguments list.
* `:root_layout` - The optional root layout tuple for the initial HTTP render to override any existing root layout set in the router.
* `:on_mount` - The optional list of hooks to attach to the mount lifecycle *of each LiveView in the session*. See [`Phoenix.LiveView.on_mount/1`](phoenix.liveview#on_mount/1). Passing a single value is also accepted.
#### Examples
```
scope "/", MyAppWeb do
pipe_through :browser
live_session :default do
live "/feed", FeedLive, :index
live "/status", StatusLive, :index
live "/status/:id", StatusLive, :show
end
live_session :admin, on_mount: MyAppWeb.AdminLiveAuth do
live "/admin", AdminDashboardLive, :index
live "/admin/posts", AdminPostLive, :index
end
end
```
In the example above, we have two live sessions. Live navigation between live views in the different sessions is not possible and will always require a full page reload. This is important in the example above because the `:admin` live session has authentication requirements, defined by `on_mount: MyAppWeb.AdminLiveAuth`, that the other LiveViews do not have.
If you have both regular HTTP routes (via get, post, etc) and `live` routes, then you need to perform the same authentication and authorization rules in both. For example, if you were to add a `get "/admin/health"` entry point inside the `:admin` live session above, then you must create your own plug that performs the same authentication and authorization rules as `MyAppWeb.AdminLiveAuth`, and then pipe through it:
```
live_session :admin, on_mount: MyAppWeb.AdminLiveAuth do
# Regular routes
pipe_through [MyAppWeb.AdminPlugAuth]
get "/admin/health"
# Live routes
live "/admin", AdminDashboardLive, :index
live "/admin/posts", AdminPostLive, :index
end
```
The opposite is also true, if you have regular http routes and you want to add your own `live` routes, the same authentication and authorization checks executed by the plugs listed in `pipe_through` must be ported to LiveViews and be executed via `on_mount` hooks.
phoenix Phoenix.LiveComponent.CID Phoenix.LiveComponent.CID
==========================
The struct representing an internal unique reference to the component instance, available as the `@myself` assign in stateful components.
Read more about the uses of `@myself` in the [`Phoenix.LiveComponent`](phoenix.livecomponent) docs.
phoenix Phoenix.LiveView.UploadEntry Phoenix.LiveView.UploadEntry
=============================
The struct representing an upload entry.
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/upload_config.ex#L22)
```
@type t() :: %Phoenix.LiveView.UploadEntry{
cancelled?: boolean(),
client_last_modified: integer() | nil,
client_name: String.t() | nil,
client_size: integer() | nil,
client_type: String.t() | nil,
done?: boolean(),
preflighted?: term(),
progress: integer(),
ref: String.t() | nil,
upload_config: String.t() | :atom,
upload_ref: String.t(),
uuid: String.t() | nil,
valid?: boolean()
}
```
phoenix Telemetry Telemetry
==========
LiveView currently exposes the following [`telemetry`](https://hexdocs.pm/telemetry) events:
* `[:phoenix, :live_view, :mount, :start]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) immediately before [`mount/3`](phoenix.liveview#c:mount/3) is invoked.
+ Measurement:
```
%{system_time: System.monotonic_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
params: unsigned_params | :not_mounted_at_router,
session: map,
uri: String.t() | nil
}
```
* `[:phoenix, :live_view, :mount, :stop]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) when the [`mount/3`](phoenix.liveview#c:mount/3) callback completes successfully.
+ Measurement:
```
%{duration: native_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
params: unsigned_params | :not_mounted_at_router,
session: map,
uri: String.t() | nil
}
```
* `[:phoenix, :live_view, :mount, :exception]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) when an exception is raised in the [`mount/3`](phoenix.liveview#c:mount/3) callback.
+ Measurement: `%{duration: native_time}`
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
kind: atom,
reason: term,
params: unsigned_params | :not_mounted_at_router,
session: map,
uri: String.t() | nil
}
```
* `[:phoenix, :live_view, :handle_params, :start]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) immediately before [`handle_params/3`](phoenix.liveview#c:handle_params/3) is invoked.
+ Measurement:
```
%{system_time: System.monotonic_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
params: unsigned_params,
uri: String.t()
}
```
* `[:phoenix, :live_view, :handle_params, :stop]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) when the [`handle_params/3`](phoenix.liveview#c:handle_params/3) callback completes successfully.
+ Measurement:
```
%{duration: native_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
params: unsigned_params,
uri: String.t()
}
```
* `[:phoenix, :live_view, :handle_params, :exception]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) when the when an exception is raised in the [`handle_params/3`](phoenix.liveview#c:handle_params/3) callback.
+ Measurement:
```
%{duration: native_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
kind: atom,
reason: term,
params: unsigned_params,
uri: String.t()
}
```
* `[:phoenix, :live_view, :handle_event, :start]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) immediately before [`handle_event/3`](phoenix.liveview#c:handle_event/3) is invoked.
+ Measurement:
```
%{system_time: System.monotonic_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
event: String.t(),
params: unsigned_params
}
```
* `[:phoenix, :live_view, :handle_event, :stop]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) when the [`handle_event/3`](phoenix.liveview#c:handle_event/3) callback completes successfully.
+ Measurement:
```
%{duration: native_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
event: String.t(),
params: unsigned_params
}
```
* `[:phoenix, :live_view, :handle_event, :exception]` - Dispatched by a [`Phoenix.LiveView`](phoenix.liveview) when an exception is raised in the [`handle_event/3`](phoenix.liveview#c:handle_event/3) callback.
+ Measurement:
```
%{duration: native_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
kind: atom,
reason: term,
event: String.t(),
params: unsigned_params
}
```
* `[:phoenix, :live_component, :handle_event, :start]` - Dispatched by a [`Phoenix.LiveComponent`](phoenix.livecomponent) immediately before [`handle_event/3`](phoenix.livecomponent#c:handle_event/3) is invoked.
+ Measurement:
```
%{system_time: System.monotonic_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
component: atom,
event: String.t(),
params: unsigned_params
}
```
* `[:phoenix, :live_component, :handle_event, :stop]` - Dispatched by a [`Phoenix.LiveComponent`](phoenix.livecomponent) when the [`handle_event/3`](phoenix.livecomponent#c:handle_event/3) callback completes successfully.
+ Measurement:
```
%{duration: native_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
component: atom,
event: String.t(),
params: unsigned_params
}
```
* `[:phoenix, :live_component, :handle_event, :exception]` - Dispatched by a [`Phoenix.LiveComponent`](phoenix.livecomponent) when an exception is raised in the [`handle_event/3`](phoenix.livecomponent#c:handle_event/3) callback.
+ Measurement:
```
%{duration: native_time}
```
+ Metadata:
```
%{
socket: Phoenix.LiveView.Socket.t,
kind: atom,
reason: term,
component: atom,
event: String.t(),
params: unsigned_params
}
```
[← Previous Page Security considerations of the LiveView model](security-model) [Next Page → Uploads](uploads)
| programming_docs |
phoenix Live navigation Live navigation
================
LiveView provides functionality to allow page navigation using the [browser's pushState API](https://developer.mozilla.org/en-US/docs/Web/API/History_API). With live navigation, the page is updated without a full page reload.
You can trigger live navigation in two ways:
* From the client - this is done by replacing [`Phoenix.HTML.Link.link/2`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Link.html#link/2) by [`Phoenix.LiveView.Helpers.live_patch/2`](phoenix.liveview.helpers#live_patch/2) or [`Phoenix.LiveView.Helpers.live_redirect/2`](phoenix.liveview.helpers#live_redirect/2)
* From the server - this is done by replacing [`Phoenix.Controller.redirect/2`](https://hexdocs.pm/phoenix/1.6.6/Phoenix.Controller.html#redirect/2) calls by [`Phoenix.LiveView.push_patch/2`](phoenix.liveview#push_patch/2) or [`Phoenix.LiveView.push_redirect/2`](phoenix.liveview#push_redirect/2).
For example, in a template you may write:
```
<%= live_patch "next", to: Routes.live_path(@socket, MyLive, @page + 1) %>
```
or in a LiveView:
```
{:noreply, push_patch(socket, to: Routes.live_path(socket, MyLive, page + 1))}
```
The "patch" operations must be used when you want to navigate to the current LiveView, simply updating the URL and the current parameters, without mounting a new LiveView. When patch is used, the [`handle_params/3`](phoenix.liveview#c:handle_params/3) callback is invoked and the minimal set of changes are sent to the client. See the next section for more information.
The "redirect" operations must be used when you want to dismount the current LiveView and mount a new one. In those cases, an Ajax request is made to fetch the necessary information about the new LiveView, which is mounted in place of the current one within the current layout. While redirecting, a `phx-loading` class is added to the LiveView, which can be used to indicate to the user a new page is being loaded.
At the end of the day, regardless if you invoke [`link/2`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Link.html#link/2), [`live_patch/2`](phoenix.liveview.helpers#live_patch/2), and [`live_redirect/2`](phoenix.liveview.helpers#live_redirect/2) from the client, or [`redirect/2`](https://hexdocs.pm/phoenix/1.6.6/Phoenix.Controller.html#redirect/2), [`push_patch/2`](phoenix.liveview#push_patch/2), and [`push_redirect/2`](phoenix.liveview#push_redirect/2) from the server, the user will end-up on the same page. The difference between those is mostly the amount of data sent over the wire:
* [`link/2`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Link.html#link/2) and [`redirect/2`](https://hexdocs.pm/phoenix/1.6.6/Phoenix.Controller.html#redirect/2) do full page reloads
* [`live_redirect/2`](phoenix.liveview.helpers#live_redirect/2) and [`push_redirect/2`](phoenix.liveview#push_redirect/2) mounts a new LiveView while keeping the current layout
* [`live_patch/2`](phoenix.liveview.helpers#live_patch/2) and [`push_patch/2`](phoenix.liveview#push_patch/2) updates the current LiveView and sends only the minimal diff while also maintaining the scroll position
An easy rule of thumb is to stick with [`live_redirect/2`](phoenix.liveview.helpers#live_redirect/2) and [`push_redirect/2`](phoenix.liveview#push_redirect/2) and use the patch helpers only in the cases where you want to minimize the amount of data sent when navigating within the same LiveView (for example, if you want to change the sorting of a table while also updating the URL).
`handle_params/3`
------------------
The [`handle_params/3`](phoenix.liveview#c:handle_params/3) callback is invoked after [`mount/3`](phoenix.liveview#c:mount/3) and before the initial render. It is also invoked every time [`live_patch/2`](phoenix.liveview.helpers#live_patch/2) or [`push_patch/2`](phoenix.liveview#push_patch/2) are used. It receives the request parameters as first argument, the url as second, and the socket as third.
For example, imagine you have a `UserTable` LiveView to show all users in the system and you define it in the router as:
```
live "/users", UserTable
```
Now to add live sorting, you could do:
```
<%= live_patch "Sort by name", to: Routes.live_path(@socket, UserTable, %{sort_by: "name"}) %>
```
When clicked, since we are navigating to the current LiveView, [`handle_params/3`](phoenix.liveview#c:handle_params/3) will be invoked. Remember you should never trust the received params, so you must use the callback to validate the user input and change the state accordingly:
```
def handle_params(params, _uri, socket) do
socket =
case params["sort_by"] do
sort_by when sort_by in ~w(name company) -> assign(socket, sort_by: sort_by)
_ -> socket
end
{:noreply, load_users(socket)}
end
```
Note we returned `{:noreply, socket}`, where `:noreply` means no additional information is sent to the client. As with other `handle_*` callbacks, changes to the state inside [`handle_params/3`](phoenix.liveview#c:handle_params/3) will trigger a new server render.
Note the parameters given to [`handle_params/3`](phoenix.liveview#c:handle_params/3) are the same as the ones given to [`mount/3`](phoenix.liveview#c:mount/3). So how do you decide which callback to use to load data? Generally speaking, data should always be loaded on [`mount/3`](phoenix.liveview#c:mount/3), since [`mount/3`](phoenix.liveview#c:mount/3) is invoked once per LiveView life-cycle. Only the params you expect to be changed via [`live_patch/2`](phoenix.liveview.helpers#live_patch/2) or [`push_patch/2`](phoenix.liveview#push_patch/2) must be loaded on [`handle_params/3`](phoenix.liveview#c:handle_params/3).
For example, imagine you have a blog. The URL for a single post is: "/blog/posts/:post\_id". In the post page, you have comments and they are paginated. You use [`live_patch/2`](phoenix.liveview.helpers#live_patch/2) to update the shown comments every time the user paginates, updating the URL to "/blog/posts/:post\_id?page=X". In this example, you will access `"post_id"` on [`mount/3`](phoenix.liveview#c:mount/3) and the page of comments on [`handle_params/3`](phoenix.liveview#c:handle_params/3).
Furthermore, it is very important to not access the same parameters on both [`mount/3`](phoenix.liveview#c:mount/3) and [`handle_params/3`](phoenix.liveview#c:handle_params/3). For example, do NOT do this:
```
def mount(%{"post_id" => post_id}, session, socket) do
# do something with post_id
end
def handle_params(%{"post_id" => post_id, "page" => page}, url, socket) do
# do something with post_id and page
end
```
If you do that, because [`mount/3`](phoenix.liveview#c:mount/3) is called once and [`handle_params/3`](phoenix.liveview#c:handle_params/3) multiple times, the "post\_id" read on mount can get out of sync with the one in [`handle_params/3`](phoenix.liveview#c:handle_params/3). So once a parameter is read on mount, it should not be read elsewhere. Instead, do this:
```
def mount(%{"post_id" => post_id}, session, socket) do
# do something with post_id
end
def handle_params(%{"sort_by" => sort_by}, url, socket) do
post_id = socket.assigns.post.id
# do something with sort_by
end
```
Replace page address
---------------------
LiveView also allows the current browser URL to be replaced. This is useful when you want certain events to change the URL but without polluting the browser's history. This can be done by passing the `replace: true` option to any of the navigation helpers.
Multiple LiveViews in the same page
------------------------------------
LiveView allows you to have multiple LiveViews in the same page by calling [`Phoenix.LiveView.Helpers.live_render/3`](phoenix.liveview.helpers#live_render/3) in your templates. However, only the LiveViews defined directly in your router can use the "Live Navigation" functionality described here. This is important because LiveViews work closely with your router, guaranteeing you can only navigate to known routes.
[← Previous Page Live layouts](live-layouts) [Next Page → Security considerations of the LiveView model](security-model)
phoenix Assigns and HEEx templates Assigns and HEEx templates
===========================
All of the data in a LiveView is stored in the socket as assigns. The [`Phoenix.LiveView.assign/2`](phoenix.liveview#assign/2) and [`Phoenix.LiveView.assign/3`](phoenix.liveview#assign/3) functions help store those values. Those values can be accessed in the LiveView as `socket.assigns.name` but they are accessed inside LiveView templates as `@name`.
Phoenix template language is called HEEx (HTML+EEx). Those templates are either files with the `.heex` extension or they are created directly in source files via the `~H` sigil. You can learn more about the HEEx syntax by checking the docs for [the `~H` sigil](phoenix.liveview.helpers#sigil_H/2).
In this section, we are going to cover how LiveView minimizes the payload over the wire by understanding the interplay between assigns and templates.
Change tracking
----------------
When you first render a `.heex` template, it will send all of the static and dynamic parts of the template to the client. Imagine the following template:
```
<h1><%= expand_title(@title) %></h1>
```
It has two static parts, `<h1>` and `</h1>` and one dynamic part made of `expand_title(@title)`. Further rendering of this template won't resend the static parts and it will only resend the dynamic part if it changes.
The tracking of changes is done via assigns. If the `@title` assign changes, then LiveView will execute `expand_title(@title)` and send the new content. If `@title` is the same, nothing is executed and nothing is sent.
Change tracking also works when accessing map/struct fields. Take this template:
```
<div id={"user_#{@user.id}"}>
<%= @user.name %>
</div>
```
If the `@user.name` changes but `@user.id` doesn't, then LiveView will re-render only `@user.name` and it will not execute or resend `@user.id` at all.
The change tracking also works when rendering other templates as long as they are also `.heex` templates:
```
<%= render "child_template.html", assigns %>
```
Or when using function components:
```
<.show_name name={@user.name} />
```
The assign tracking feature also implies that you MUST avoid performing direct operations in the template. For example, if you perform a database query in your template:
```
<%= for user <- Repo.all(User) do %>
<%= user.name %>
<% end %>
```
Then Phoenix will never re-render the section above, even if the number of users in the database changes. Instead, you need to store the users as assigns in your LiveView before it renders the template:
```
assign(socket, :users, Repo.all(User))
```
Generally speaking, **data loading should never happen inside the template**, regardless if you are using LiveView or not. The difference is that LiveView enforces this best practice.
Pitfalls
---------
There are two common pitfalls to keep in mind when using the `~H` sigil or `.heex` templates inside LiveViews.
When it comes to `do/end` blocks, change tracking is supported only on blocks given to Elixir's basic constructs, such as `if`, `case`, `for`, and similar. If the do/end block is given to a library function or user function, such as `content_tag`, change tracking won't work. For example, imagine the following template that renders a `div`:
```
<%= content_tag :div, id: "user_#{@id}" do %>
<%= @name %>
<%= @description %>
<% end %>
```
LiveView knows nothing about `content_tag`, which means the whole `div` will be sent whenever any of the assigns change. Luckily, HEEx templates provide a nice syntax for building tags, so there is rarely a need to use `content_tag` inside `.heex` templates:
```
<div id={"user_#{@id}"}>
<%= @name %>
<%= @description %>
</div>
```
The next pitfall is related to variables. Due to the scope of variables, LiveView has to disable change tracking whenever variables are used in the template, with the exception of variables introduced by Elixir basic `case`, `for`, and other block constructs. Therefore, you **must avoid** code like this in your LiveView templates:
```
<% some_var = @x + @y %>
<%= some_var %>
```
Instead, use a function:
```
<%= sum(@x, @y) %>
```
Similarly, **do not** define variables at the top of your `render` function:
```
def render(assigns) do
sum = assigns.x + assigns.y
~H"""
<%= sum %>
"""
end
```
Instead explicitly precompute the assign in your LiveView, outside of render:
```
assign(socket, sum: socket.assigns.x + socket.assigns.y)
```
Generally speaking, avoid accessing variables inside LiveViews, as code that access variables is always executed on every render. This also applies to the `assigns` variable. The exception are variables introduced by Elixir's block constructs. For example, accessing the `post` variable defined by the comprehension below works as expected:
```
<%= for post <- @posts do %>
...
<% end %>
```
To sum up:
1. Avoid passing block expressions to library and custom functions, instead prefer to use the conveniences in `HEEx` templates
2. Avoid defining local variables, except within Elixir's constructs
[← Previous Page Installation](installation) [Next Page → Error and exception handling](error-handling)
phoenix Security considerations of the LiveView model Security considerations of the LiveView model
==============================================
LiveView begins its life-cycle as a regular HTTP request. Then a stateful connection is established. Both the HTTP request and the stateful connection receive the client data via parameters and session.
This means that any session validation must happen both in the HTTP request (plug pipeline) and the stateful connection (LiveView mount).
Authentication vs authorization
--------------------------------
When speaking about security, there are two terms commonly used: authentication and authorization. Authentication is about identifying a user. Authorization is about telling if a user has access to a certain resource or feature in the system.
In a regular web application, once a user is authenticated, for example by entering their email and password, or by using a third-party service such as Google, Twitter, or Facebook, a token identifying the user is stored in the session, which is a cookie (a key-value pair) stored in the user's browser.
Every time there is a request, we read the value from the session, and, if valid, we fetch the user stored in the session from the database. The session is automatically validated by Phoenix and tools like [`mix phx.gen.auth`](https://hexdocs.pm/phoenix/1.6.6/Mix.Tasks.Phx.Gen.Auth.html) can generate the building blocks of an authentication system for you.
Once the user is authenticated, they may perform many actions on the page, and some of those actions require specific permissions. This is called authorization and the specific rules often change per application.
In a regular web application, we perform authentication and authorization checks on every request. In LiveView, we should also run those exact same checks, always. Once the user is authenticated, we typically validate the sessions on the `mount` callback. Authorization rules generally happen on `mount` (for instance, is the user allowed to see this page?) and also on `handle_event` (is the user allowed to delete this item?).
Mounting considerations
------------------------
If you perform user authentication and confirmation on every HTTP request via Plugs, such as this:
```
plug :ensure_user_authenticated
plug :ensure_user_confirmed
```
Then the [`mount/3`](phoenix.liveview#c:mount/3) callback of your LiveView should execute those same verifications:
```
def mount(_params, %{"user_id" => user_id} = _session, socket) do
socket = assign(socket, current_user: Accounts.get_user!(user_id))
socket =
if socket.assigns.current_user.confirmed_at do
socket
else
redirect(socket, to: "/login")
end
{:ok, socket}
end
```
LiveView v0.17 includes the `on_mount` ([`Phoenix.LiveView.on_mount/1`](phoenix.liveview#on_mount/1)) hook, which allows you to encapsulate this logic and execute it on every mount, as you would with plug:
```
defmodule MyAppWeb.UserLiveAuth do
import Phoenix.LiveView
def on_mount(:default, _params, %{"user_id" => user_id} = _session, socket) do
socket = assign_new(socket, :current_user, fn ->
Accounts.get_user!(user_id)
end)
if socket.assigns.current_user.confirmed_at do
{:cont, socket}
else
{:halt, redirect(socket, to: "/login")}
end
end
end
```
We use [`assign_new/3`](phoenix.liveview#assign_new/3). This is a convenience to avoid fetching the `current_user` multiple times across LiveViews.
Now we can use the hook whenever relevant:
```
defmodule MyAppWeb.PageLive do
use MyAppWeb, :live_view
on_mount MyAppWeb.UserLiveAuth
...
end
```
If you prefer, you can add the hook to `def live_view` under `MyAppWeb`, to run it on all LiveViews by default:
```
def live_view do
quote do
use Phoenix.LiveView,
layout: {MyAppWeb.LayoutView, "live.html"}
on_mount MyAppWeb.UserLiveAuth
unquote(view_helpers())
end
end
```
Events considerations
----------------------
Every time the user performs an action on your system, you should verify if the user is authorized to do so, regardless if you are using LiveViews or not. For example, imagine a user can see all projects in a web application, but they may not have permission to delete any of them. At the UI level, you handle this accordingly by not showing the delete button in the projects listing, but a savvy user can directly talk to the server and request a deletion anyway. For this reason, **you must always verify permissions on the server**.
In LiveView, most actions are handled by the `handle_event` callback. Therefore, you typically authorize the user within those callbacks. In the scenario just described, one might implement this:
```
on_mount MyAppWeb.UserLiveAuth
def mount(_params, _session, socket) do
{:ok, load_projects(socket)}
end
def handle_event("delete_project", %{"project_id" => project_id}, socket) do
Project.delete!(socket.assigns.current_user, project_id)
{:noreply, update(socket, :projects, &Enum.reject(&1, fn p -> p.id == project_id end)}
end
defp load_projects(socket) do
projects = Project.all_projects(socket.assigns.current_user)
assign(socket, projects: projects)
end
```
First, we used `on_mount` to authenticate the user based on the data stored in the session. Then we load all projects based on the authenticated user. Now, whenever there is a request to delete a project, we still pass the current user as argument to the `Project` context, so it verifies if the user is allowed to delete it or not. In case it cannot delete, it is fine to just raise an exception. After all, users are not meant to trigger this code path anyway (unless they are fiddling with something they are not supposed to!).
Disconnecting all instances of a live user
-------------------------------------------
So far, the security model between LiveView and regular web applications have been remarkably similar. After all, we must always authenticate and authorize every user. The main difference between them happens on logout or when revoking access.
Because LiveView is a permanent connection between client and server, if a user is logged out, or removed from the system, this change won't reflect on the LiveView part unless the user reloads the page.
Luckily, it is possible to address this by setting a `live_socket_id` in the session. For example, when logging in a user, you could do:
```
conn
|> put_session(:current_user_id, user.id)
|> put_session(:live_socket_id, "users_socket:#{user.id}")
```
Now all LiveView sockets will be identified and listen to the given `live_socket_id`. You can then disconnect all live users identified by said ID by broadcasting on the topic:
```
MyAppWeb.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
```
> Note: If you use [`mix phx.gen.auth`](https://hexdocs.pm/phoenix/1.6.6/Mix.Tasks.Phx.Gen.Auth.html) to generate your authentication system, lines to that effect are already present in the generated code. The generated code uses a `user_token` instead of referring to the `user_id`.
>
>
Once a LiveView is disconnected, the client will attempt to reestablish the connection and re-execute the [`mount/3`](phoenix.liveview#c:mount/3) callback. In this case, if the user is no longer logged in or it no longer has access to the current resource, `mount/3` will fail and the user will be redirected.
This is the same mechanism provided by [`Phoenix.Channel`](https://hexdocs.pm/phoenix/1.6.6/Phoenix.Channel.html)s. Therefore, if your application uses both channels and LiveViews, you can use the same technique to disconnect any stateful connection.
`live_session` and `live_redirect`
-----------------------------------
LiveView supports live redirect, which allows users to navigate between pages over the LiveView connection. Whenever there is a `live_redirect`, a new LiveView will be mounted, skipping the regular HTTP requests and without going through the plug pipeline.
However, if you want to draw stronger boundaries between parts of your application, you can also use [`Phoenix.LiveView.Router.live_session/2`](phoenix.liveview.router#live_session/2) to group your live routes. This can be handy because you can only `live_redirect` between LiveViews in the same `live_session`.
For example, imagine you need to authenticate two distinct types of users. Your regular users login via email and password, and you have an admin dashboard that uses http auth. You can specify different `live_session`s for each authentication flow:
```
live_session :default do
scope "/" do
pipe_through [:authenticate_user]
get ...
live ...
end
end
live_session :admin do
scope "/admin" do
pipe_through [:http_auth_admin]
get ...
live ...
end
end
```
Now every time you try to navigate to an admin panel, and out of it, a regular page navigation will happen and a brand new live connection will be established.
Once again, it is worth remembering that LiveViews require their own security checks, so we use `pipe_through` above to protect the regular routes (get, post, etc.) and the LiveViews should run their own checks using `on_mount` hooks.
`live_session` can also be used to enforce each LiveView group has a different root layout, since layouts are not updated between live redirects:
```
live_session :default, root_layout: {LayoutView, "app.html"} do
...
end
live_session :admin, root_layout: {LayoutView, "admin.html"} do
...
end
```
Finally, you can even combine `live_session` with `on_mount`. Instead of declaring `on_mount` on every LiveView, you can declare it at the router level and it will enforce it on all LiveViews under it:
```
live_session :default, on_mount: MyAppWeb.UserLiveAuth do
scope "/" do
pipe_through [:authenticate_user]
live ...
end
end
live_session :admin, on_mount: MyAppWeb.AdminLiveAuth do
scope "/admin" do
pipe_through [:authenticate_admin]
live ...
end
end
```
Each live route under the `:default` `live_session` will invoke the `MyAppWeb.UserLiveAuth` hook on mount. This module was defined earlier in this guide. We will also pipe regular web requests through `:authenticate_user`, which must execute the same checks as `MyAppWeb.UserLiveAuth`, but tailored to plug.
Similarly, the `:admin` `live_session` has its own authentication flow, powered by `MyAppWeb.AdminLiveAuth`. It also defines a plug equivalent named `:authenticate_admin`, which will be used by any regular request. If there are no regular web requests defined under a live session, then the `pipe_through` checks are not necessary.
Declaring the `on_mount` on `live_session` is exactly the same as declaring it in each LiveView inside the `live_session`. It will be executed every time a LiveView is mounted, even after `live_redirect`s. The important concepts to keep in mind are:
* If you have both LiveViews and regular web requests, then you must always authorize and authenticate your LiveViews (using on mount hooks) and your web requests (using plugs)
* All actions (events) must also be explicitly authorized by checking permissions. Those permissions are often domain/business specific, and typically happen in your context modules
* `live_session` can be used to draw boundaries between groups of LiveViews. While you could use `live_session` to draw lines between different authorization rules, doing so would lead to frequent page reloads. For this reason, we typically use `live_session` to enforce different *authentication* requirements or whenever you need to change root layouts
[← Previous Page Live navigation](live-navigation) [Next Page → Telemetry](telemetry)
| programming_docs |
phoenix Live layouts Live layouts
=============
*NOTE:* Make sure you've read the [Assigns and HEEx templates](assigns-eex) guide before moving forward.
When working with LiveViews, there are usually three layouts to be considered:
* the root layout - this is a layout used by both LiveView and regular views. This layout typically contains the `<html>` definition alongside the head and body tags. Any content defined in the root layout will remain the same, even as you live navigate across LiveViews. All LiveViews defined at the router must have a root layout. The root layout is typically declared on the router with `put_root_layout` and defined as "root.html.heex" in your `MyAppWeb.LayoutView`. It may also be given via the `:root_layout` option to a `live_session` macro in the router.
* the app layout - this is the default application layout which is not included or used by LiveViews. It defaults to "app.html.heex" in your `MyAppWeb.LayoutView`.
* the live layout - this is the layout which wraps a LiveView and is rendered as part of the LiveView life-cycle. It must be opt-in by passing the `:layout` option on `use Phoenix.LiveView`. It is typically set to "live.html.heex"in your `MyAppWeb.LayoutView`.
Overall, those layouts are found in `templates/layout` with the following names:
```
* root.html.heex
* app.html.heex
* live.html.heex
```
> Note: if you are using earlier Phoenix versions, those layouts may use `.eex` and `.leex` extensions instead of `.heex`, but we have since then normalized on the latter.
>
>
All layouts must call `<%= @inner_content %>` to inject the content rendered by the layout.
The "root" layout is shared by both "app" and "live" layouts. It is rendered only on the initial request and therefore it has access to the `@conn` assign. The root layout must be defined in your router:
```
plug :put_root_layout, {MyAppWeb.LayoutView, :root}
```
The "app" and "live" layouts are often small and similar to each other, but the "app" layout uses the `@conn` and is used as part of the regular request life-cycle. The "live" layout is part of the LiveView and therefore has direct access to the `@socket`.
For example, you can define a new `live.html.heex` layout with dynamic content. You must use `@inner_content` where the output of the actual template will be placed at:
```
<p><%= live_flash(@flash, :notice) %></p>
<p><%= live_flash(@flash, :error) %></p>
<%= @inner_content %>
```
To use the live layout, update your LiveView to pass the `:layout` option to `use Phoenix.LiveView`:
```
use Phoenix.LiveView, layout: {MyAppWeb.LayoutView, "live.html"}
```
If you are using Phoenix v1.5, the layout is automatically set when generating apps with the `mix phx.new --live` flag.
The `:layout` option on `use` does not apply to LiveViews rendered within other LiveViews. If you want to render child live views or opt-in to a layout, use `:layout` as an option in mount:
```
def mount(_params, _session, socket) do
socket = assign(socket, new_message_count: 0)
{:ok, socket, layout: {MyAppWeb.LayoutView, "live.html"}}
end
```
*Note*: The live layout is always wrapped by the LiveView's `:container` tag.
Updating the HTML document title
---------------------------------
Because the root layout from the Plug pipeline is rendered outside of LiveView, the contents cannot be dynamically changed. The one exception is the `<title>` of the HTML document. Phoenix LiveView special cases the `@page_title` assign to allow dynamically updating the title of the page, which is useful when using live navigation, or annotating the browser tab with a notification. For example, to update the user's notification count in the browser's title bar, first set the `page_title` assign on mount:
```
def mount(_params, _session, socket) do
socket = assign(socket, page_title: "Latest Posts")
{:ok, socket}
end
```
Then access `@page_title` in the root layout:
```
<title><%= @page_title %></title>
```
You can also use [`Phoenix.LiveView.Helpers.live_title_tag/2`](phoenix.liveview.helpers#live_title_tag/2) to support adding automatic prefix and suffix to the page title when rendered and on subsequent updates:
```
<%= live_title_tag assigns[:page_title] || "Welcome", prefix: "MyApp – " %>
```
Although the root layout is not updated by LiveView, by simply assigning to `page_title`, LiveView knows you want the title to be updated:
```
def handle_info({:new_messages, count}, socket) do
{:noreply, assign(socket, page_title: "Latest Posts (#{count} new)")}
end
```
*Note*: If you find yourself needing to dynamically patch other parts of the base layout, such as injecting new scripts or styles into the `<head>` during live navigation, *then a regular, non-live, page navigation should be used instead*. Assigning the `@page_title` updates the `document.title` directly, and therefore cannot be used to update any other part of the base layout.
[← Previous Page Error and exception handling](error-handling) [Next Page → Live navigation](live-navigation)
phoenix Phoenix.LiveView.HTMLFormatter Phoenix.LiveView.HTMLFormatter
===============================
Format HEEx templates from `.heex` files or `~H` sigils.
This is a [`mix format`](https://hexdocs.pm/mix/Mix.Tasks.Format.html) [plugin](https://hexdocs.pm/mix/main/Mix.Tasks.Format.html#module-plugins).
> Note: The HEEx HTML Formatter requires Elixir v1.13.4 or later.
>
>
Setup
------
Add it as plugin to your `.formatter.exs` file and make sure to put the`heex` extension in the `inputs` option.
```
[
plugins: [Phoenix.LiveView.HTMLFormatter],
inputs: ["*.{heex,ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{heex,ex,exs}"],
# ...
]
```
>
> ### For umbrella projects
>
> In umbrella projects you must also change two files at the umbrella root, add `:phoenix_live_view` to your `deps` in the `mix.exs` file and add `plugins: [Phoenix.LiveView.HTMLFormatter]` in the `.formatter.exs` file. This is because the formatter does not attempt to load the dependencies of all children applications.
>
>
>
Options
--------
* `:line_length` - The Elixir formatter defaults to a maximum line length of 98 characters, which can be overwritten with the `:line_length` option in your `.formatter.exs` file.
* `:heex_line_length` - change the line length only for the HEEx formatter.
```
[
# ...omitted
heex_line_length: 300
]
```
Formatting
-----------
This formatter tries to be as consistent as possible with the Elixir formatter.
Given HTML like this:
```
<section><h1> <b><%= @user.name %></b></h1></section>
```
It will be formatted as:
```
<section>
<h1><b><%= @user.name %></b></h1>
</section>
```
A block element will go to the next line, while inline elements will be kept in the current line as long as they fit within the configured line length.
The following links list all block and inline elements.
* <https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements#elements>
* <https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements#list_of_inline_elements>
It will also keep inline elements in their own lines if you intentionally write them this way:
```
<section>
<h1>
<b><%= @user.name %></b>
</h1>
</section>
```
This formatter will place all attributes on their own lines when they do not all fit in the current line. Therefore this:
```
<section id="user-section-id" class="sm:focus:block flex w-full p-3" phx-click="send-event">
<p>Hi</p>
</section>
```
Will be formatted to:
```
<section
id="user-section-id"
class="sm:focus:block flex w-full p-3"
phx-click="send-event"
>
<p>Hi</p>
</section>
```
This formatter **does not** format Elixir expressions with `do...end`. The content within it will be formatted accordingly though. Therefore, the given input:
```
<%= live_redirect(
to: "/my/path",
class: "my class"
) do %>
My Link
<% end %>
```
Will be formatted to
```
<%= live_redirect(
to: "/my/path",
class: "my class"
) do %>
My Link
<% end %>
```
Note that only the text `My Link` has been formatted.
### Intentional new lines
The formatter will keep intentional new lines. However, the formatter will always keep a maximum of one line break in case you have multiple ones:
```
<p>
text
text
</p>
```
Will be formatted to:
```
<p>
text
text
</p>
```
### Inline elements
We don't format inline elements when there is a text without whitespace before or after the element. Otherwise it would compromise what is rendered adding an extra whitespace.
This is the list of inline elements:
<https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements#list_of_inline_elements>
### Special attributes
In case you don't want part of your HTML to be automatically formatted. you can use `phx-no-format` attr so that the formatter will skip the element block. Note that this attribute will not be rendered.
Therefore:
```
<.textarea phx-no-format>My content</.textarea>
```
Will be kept as is your code editor, but rendered as:
```
<textarea>My content</textarea>
```
### Inline comments <%# comment %>
Inline comments `<%# comment %>` are deprecated and the formatter will discard them silently from templates. You must change them to the multi-line comment `<%!-- comment --%>` on Elixir v1.14+ or the regular line comment `<%= # comment %>`.
phoenix Phoenix.LiveView.Rendered Phoenix.LiveView.Rendered
==========================
The struct returned by .heex templates.
See a description about its fields and use cases in [`Phoenix.LiveView.Engine`](phoenix.liveview.engine) docs.
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/engine.ex#L107)
```
@type t() :: %Phoenix.LiveView.Rendered{
dynamic:
(boolean() ->
[
nil
| iodata()
| t()
| Phoenix.LiveView.Comprehension.t()
| Phoenix.LiveView.Component.t()
]),
fingerprint: integer(),
root: nil | true | false,
static: [String.t()]
}
```
phoenix Phoenix.LiveView.UploadConfig Phoenix.LiveView.UploadConfig
==============================
The struct representing an upload.
Summary
========
Types
------
[t()](#t:t/0) Types
======
### t()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/upload_config.ex#L100)
```
@type t() :: %Phoenix.LiveView.UploadConfig{
accept: list() | :any,
acceptable_exts: MapSet.t(),
acceptable_types: MapSet.t(),
allowed?: boolean(),
auto_upload?: boolean(),
chunk_size: term(),
chunk_timeout: term(),
cid: :unregistered | nil | integer(),
client_key: String.t(),
entries: list(),
entry_refs_to_metas: %{required(String.t()) => map()},
entry_refs_to_pids: %{required(String.t()) => pid() | :unregistered | :done},
errors: list(),
external:
(Phoenix.LiveView.UploadEntry.t(), Phoenix.LiveView.Socket.t() ->
{:ok | :error, meta :: %{uploader: String.t()},
Phoenix.LiveView.Socket.t()})
| false,
max_entries: pos_integer(),
max_file_size: pos_integer(),
name: atom() | String.t(),
progress_event:
(name :: atom() | String.t(),
Phoenix.LiveView.UploadEntry.t(),
Phoenix.LiveView.Socket.t() ->
{:noreply, Phoenix.LiveView.Socket.t()})
| nil,
ref: String.t()
}
```
phoenix Phoenix.Component Phoenix.Component
==================
API for function components.
A function component is any function that receives an assigns map as argument and returns a rendered struct built with [the `~H` sigil](phoenix.liveview.helpers#sigil_H/2).
Here is an example:
```
defmodule MyComponent do
use Phoenix.Component
# Optionally also bring the HTML helpers
# use Phoenix.HTML
def greet(assigns) do
~H"""
<p>Hello, <%= assigns.name %></p>
"""
end
end
```
The component can be invoked as a regular function:
```
MyComponent.greet(%{name: "Jane"})
```
But it is typically invoked using the function component syntax from the `~H` sigil:
```
~H"""
<MyComponent.greet name="Jane" />
"""
```
If the `MyComponent` module is imported or if the function is defined locally, you can skip the module name:
```
~H"""
<.greet name="Jane" />
"""
```
Similar to any HTML tag inside the `~H` sigil, you can interpolate attributes values too:
```
~H"""
<.greet name={@user.name} />
"""
```
You can learn more about the `~H` sigil [in its documentation](phoenix.liveview.helpers#sigil_H/2).
`use Phoenix.Component`
------------------------
Modules that define function components should call `use Phoenix.Component` at the top. Doing so will import the functions from both [`Phoenix.LiveView`](phoenix.liveview) and [`Phoenix.LiveView.Helpers`](phoenix.liveview.helpers) modules. [`Phoenix.LiveView`](phoenix.liveview) and [`Phoenix.LiveComponent`](phoenix.livecomponent) automatically invoke `use Phoenix.Component` for you.
You must avoid defining a module for each component. Instead, we should use modules to group side-by-side related function components.
Assigns
--------
While inside a function component, you must use [`Phoenix.LiveView.assign/3`](phoenix.liveview#assign/3) and [`Phoenix.LiveView.assign_new/3`](phoenix.liveview#assign_new/3) to manipulate assigns, so that LiveView can track changes to the assigns values. For example, let's imagine a component that receives the first name and last name and must compute the name assign. One option would be:
```
def show_name(assigns) do
assigns = assign(assigns, :name, assigns.first_name <> assigns.last_name)
~H"""
<p>Your name is: <%= @name %></p>
"""
end
```
However, when possible, it may be cleaner to break the logic over function calls instead of precomputed assigns:
```
def show_name(assigns) do
~H"""
<p>Your name is: <%= full_name(@first_name, @last_name) %></p>
"""
end
defp full_name(first_name, last_name), do: first_name <> last_name
```
Another example is making an assign optional by providing a default value:
```
def field_label(assigns) do
assigns = assign_new(assigns, :help, fn -> nil end)
~H"""
<label>
<%= @text %>
<%= if @help do %>
<span class="help"><%= @help %></span>
<% end %>
</label>
"""
end
```
Slots
------
Slots is a mechanism to give HTML blocks to function components as in regular HTML tags.
### Default slots
Any content you pass inside a component is assigned to a default slot called `@inner_block`. For example, imagine you want to create a button component like this:
```
<.button>
This renders <strong>inside</strong> the button!
</.button>
```
It is quite simple to do so. Simply define your component and call `render_slot(@inner_block)` where you want to inject the content:
```
def button(assigns) do
~H"""
<button class="btn">
<%= render_slot(@inner_block) %>
</button>
"""
end
```
In a nutshell, the contents given to the component is assigned to the `@inner_block` assign and then we use [`Phoenix.LiveView.Helpers.render_slot/2`](phoenix.liveview.helpers#render_slot/2) to render it.
You can even have the component give a value back to the caller, by using `let`. Imagine this component:
```
def unordered_list(assigns) do
~H"""
<ul>
<%= for entry <- @entries do %>
<li><%= render_slot(@inner_block, entry) %></li>
<% end %>
</ul>
"""
end
```
And now you can invoke it as:
```
<.unordered_list let={entry} entries={~w(apple banana cherry)}>
I like <%= entry %>
</.unordered_list>
```
You can also pattern match the arguments provided to the render block. Let's make our `unordered_list` component fancier:
```
def unordered_list(assigns) do
~H"""
<ul>
<%= for entry <- @entries do %>
<li><%= render_slot(@inner_block, %{entry: entry, gif_url: random_gif()}) %></li>
<% end %>
</ul>
"""
end
```
And now we can invoke it like this:
```
<.unordered_list let={%{entry: entry, gif_url: url}}>
I like <%= entry %>. <img src={url} />
</.unordered_list>
```
### Named slots
Besides `@inner_block`, it is also possible to pass named slots to the component. For example, imagine that you want to create a modal component. The modal component has a header, a footer, and the body of the modal, which we would use like this:
```
<.modal>
<:header>
This is the top of the modal.
</:header>
This is the body - everything not in a
named slot goes to @inner_block.
<:footer>
<button>Save</button>
</:footer>
</.modal>
```
The component itself could be implemented like this:
```
def modal(assigns) do
~H"""
<div class="modal">
<div class="modal-header">
<%= render_slot(@header) %>
</div>
<div class="modal-body">
<%= render_slot(@inner_block) %>
</div>
<div class="modal-footer">
<%= render_slot(@footer) %>
</div>
</div>
"""
end
```
If you want to make the `@header` and `@footer` optional, you can assign them a default of an empty list at the top:
```
def modal(assigns) do
assigns =
assigns
|> assign_new(:header, fn -> [] end)
|> assign_new(:footer, fn -> [] end)
~H"""
<div class="modal">
...
end
```
### Named slots with attributes
It is also possible to pass the same named slot multiple times and also give attributes to each of them.
If multiple slot entries are defined for the same slot, `render_slot/2` will automatically render all entries, merging their contents. But sometimes we want more fine grained control over each individual slot, including access to their attributes. Let's see an example. Imagine we want to implement a table component
For example, imagine a table component:
```
<.table rows={@users}>
<:col let={user} label="Name">
<%= user.name %>
</:col>
<:col let={user} label="Address">
<%= user.address %>
</:col>
</.table>
```
At the top level, we pass the rows as an assign and we define a `:col` slot for each column we want in the table. Each column also has a `label`, which we are going to use in the table header.
Inside the component, you can render the table with headers, rows, and columns:
```
def table(assigns) do
~H"""
<table>
<tr>
<%= for col <- @col do %>
<th><%= col.label %></th>
<% end %>
</tr>
<%= for row <- @rows do %>
<tr>
<%= for col <- @col do %>
<td><%= render_slot(col, row) %></td>
<% end %>
</tr>
<% end %>
</table>
"""
end
```
Each named slot (including the `@inner_block`) is a list of maps, where the map contains all slot attributes, allowing us to access the label as `col.label`. This gives us complete control over how we render them.
phoenix Phoenix.LiveView.JS Phoenix.LiveView.JS
====================
Provides commands for executing JavaScript utility operations on the client.
JS commands support a variety of utility operations for common client-side needs, such as adding or removing CSS classes, setting or removing tag attributes, showing or hiding content, and transitioning in and out with animations. While these operations can be accomplished via client-side hooks, JS commands are DOM-patch aware, so operations applied by the JS APIs will stick to elements across patches from the server.
In addition to purely client-side utilities, the JS commands include a rich `push` API, for extending the default `phx-` binding pushes with options to customize targets, loading states, and additional payload values.
Client Utility Commands
------------------------
The following utilities are included:
* `add_class` - Add classes to elements, with optional transitions
* `remove_class` - Remove classes from elements, with optional transitions
* `set_attribute` - Set an attribute on elements
* `remove_attribute` - Remove an attribute from elements
* `show` - Show elements, with optional transitions
* `hide` - Hide elements, with optional transitions
* `toggle` - Shows or hides elements based on visibility, with optional transitions
* `transition` - Apply a temporary transition to elements for animations
* `dispatch` - Dispatch a DOM event to elements
For example, the following modal component can be shown or hidden on the client without a trip to the server:
```
alias Phoenix.LiveView.JS
def hide_modal(js \\ %JS{}) do
js
|> JS.hide(transition: "fade-out", to: "#modal")
|> JS.hide(transition: "fade-out-scale", to: "#modal-content")
end
def modal(assigns) do
~H"""
<div id="modal" class="phx-modal" phx-remove={hide_modal()}>
<div
id="modal-content"
class="phx-modal-content"
phx-click-away={hide_modal()}
phx-window-keydown={hide_modal()}
phx-key="escape"
>
<button class="phx-modal-close" phx-click={hide_modal()}>✖</button>
<p><%= @text %></p>
</div>
</div>
"""
end
```
Enhanced push events
---------------------
The [`push/1`](#push/1) command allows you to extend the built-in pushed event handling when a `phx-` event is pushed to the server. For example, you may wish to target a specific component, specify additional payload values to include with the event, apply loading states to external elements, etc. For example, given this basic `phx-click` event:
```
<div phx-click="inc">+</div>
```
Imagine you need to target your current component, and apply a loading state to the parent container while the client awaits the server acknowledgement:
```
alias Phoenix.LiveView.JS
<div phx-click={JS.push("inc", loading: ".thermo", target: @myself)}>+</div>
```
Push commands also compose with all other utilities. For example, to add a class when pushing:
```
<div phx-click={
JS.push("inc", loading: ".thermo", target: @myself)
|> JS.add_class(".warmer", to: ".thermo")
}>+</div>
```
Custom JS events with `JS.dispatch/1` and `window.addEventListener`
--------------------------------------------------------------------
[`dispatch/1`](#dispatch/1) can be used to dispatch custom JavaScript events to elements. For example, you can use `JS.dispatch("click", to: "#foo")`, to dispatch a click event to an element.
This also means you can augment your elements with custom events, by using JavaScript's `window.addEventListener` and invoking them with [`dispatch/1`](#dispatch/1). For example, imagine you want to provide a copy-to-clipboard functionality in your application. You can add a custom event for it:
```
window.addEventListener("my_app:clipcopy", (event) => {
if ("clipboard" in navigator) {
const text = event.target.textContent;
navigator.clipboard.writeText(text);
} else {
alert("Sorry, your browser does not support clipboard copy.");
}
});
```
Now you can have a button like this:
```
<button phx-click={JS.dispatch("my_app:clipcopy", to: "#element-with-text-to-copy")}>
Copy content
</button>
```
The combination of [`dispatch/1`](#dispatch/1) with `window.addEventListener` is a powerful mechanism to increase the amount of actions you can trigger client-side from your LiveView code.
Summary
========
Functions
----------
[add\_class(names)](#add_class/1) Adds classes to elements.
[add\_class(js, names)](#add_class/2) See [`add_class/1`](#add_class/1).
[add\_class(js, names, opts)](#add_class/3) See [`add_class/1`](#add_class/1).
[dispatch(js \\ %JS{}, event)](#dispatch/2) Dispatches an event to the DOM.
[dispatch(js, event, opts)](#dispatch/3) See [`dispatch/2`](#dispatch/2).
[hide(opts \\ [])](#hide/1) Hides elements.
[hide(js, opts)](#hide/2) See [`hide/1`](#hide/1).
[push(event)](#push/1) Pushes an event to the server.
[push(event, opts)](#push/2) See [`push/1`](#push/1).
[push(js, event, opts)](#push/3) See [`push/1`](#push/1).
[remove\_attribute(attr)](#remove_attribute/1) Removes an attribute from elements.
[remove\_attribute(attr, opts)](#remove_attribute/2) See [`remove_attribute/1`](#remove_attribute/1).
[remove\_attribute(js, attr, opts)](#remove_attribute/3) See [`remove_attribute/1`](#remove_attribute/1).
[remove\_class(names)](#remove_class/1) Removes classes from elements.
[remove\_class(js, names)](#remove_class/2) See [`remove_class/1`](#remove_class/1).
[remove\_class(js, names, opts)](#remove_class/3) See [`remove_class/1`](#remove_class/1).
[set\_attribute(arg)](#set_attribute/1) Sets an attribute on elements.
[set\_attribute(js, opts)](#set_attribute/2) See [`set_attribute/1`](#set_attribute/1).
[set\_attribute(js, arg, opts)](#set_attribute/3) See [`set_attribute/1`](#set_attribute/1).
[show(opts \\ [])](#show/1) Shows elements.
[show(js, opts)](#show/2) See [`show/1`](#show/1).
[toggle(opts \\ [])](#toggle/1) Toggles elements.
[toggle(js, opts)](#toggle/2) See [`toggle/1`](#toggle/1).
[transition(transition)](#transition/1) Transitions elements.
[transition(transition, opts)](#transition/2) See [`transition/1`](#transition/1).
[transition(js, transition, opts)](#transition/3) See [`transition/1`](#transition/1).
Functions
==========
### add\_class(names)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L418)
Adds classes to elements.
* `names` - The string of classes to add.
#### Options
* `:to` - The optional DOM selector to add classes to. Defaults to the interacted element.
* `:transition` - The string of classes to apply before adding classes or a 3-tuple containing the transition class, the class to apply to start the transition, and the ending transition class, such as: `{"ease-out duration-300", "opacity-0", "opacity-100"}`
* `:time` - The time to apply the transition from `:transition`. Defaults 200
#### Examples
```
<div id="item">My Item</div>
<button phx-click={JS.add_class("highlight underline", to: "#item")}>
highlight!
</button>
```
### add\_class(js, names)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L421)
See [`add_class/1`](#add_class/1).
### add\_class(js, names, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L430)
See [`add_class/1`](#add_class/1).
### dispatch(js \\ %JS{}, event)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L199)
Dispatches an event to the DOM.
* `event` - The string event name to dispatch.
*Note*: All events dispatched are of a type [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent), with the exception of `"click"`. For a `"click"`, a [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) is dispatched to properly simulate a UI click.
For emitted `CustomEvent`'s, the event detail will contain a `dispatcher`, which references the DOM node that dispatched the JS event to the target element.
#### Options
* `:to` - The optional DOM selector to dispatch the event to. Defaults to the interacted element.
* `:detail` - The optional detail map to dispatch along with the client event. The details will be available in the `event.detail` attribute for event listeners.
* `:bubbles` – The boolean flag to bubble the event or not. Default `true`.
#### Examples
```
window.addEventListener("click", e => console.log("clicked!", e.detail))
<button phx-click={JS.dispatch("click", to: ".nav")}>Click me!</button>
```
### dispatch(js, event, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L204)
See [`dispatch/2`](#dispatch/2).
### hide(opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L378)
Hides elements.
#### Options
* `:to` - The optional DOM selector to hide. Defaults to the interacted element.
* `:transition` - The string of classes to apply before hiding or a 3-tuple containing the transition class, the class to apply to start the transition, and the ending transition class, such as: `{"ease-out duration-300", "opacity-0", "opacity-100"}`
* `:time` - The time to apply the transition from `:transition`. Defaults 200
When the show is complete on the client, a `phx:hide-start` and `phx:hide-end` event will be dispatched to the hidden elements.
#### Examples
```
<div id="item">My Item</div>
<button phx-click={JS.hide(to: "#item")}>
hide!
</button>
<button phx-click={JS.hide(to: "#item", transition: "fade-out-scale")}>
hide fancy!
</button>
```
### hide(js, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L383)
See [`hide/1`](#hide/1).
### push(event)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L145)
Pushes an event to the server.
* `event` - The string event name to push.
#### Options
* `:target` - The selector or component ID to push to
* `:loading` - The selector to apply the phx loading classes to
* `:page_loading` - Boolean to trigger the phx:page-loading-start and phx:page-loading-stop events for this push. Defaults to `false`
* `:value` - The map of values to send to the server
#### Examples
```
<button phx-click={JS.push("clicked")}>click me!</button>
<button phx-click={JS.push("clicked", value: %{id: @id})}>click me!</button>
<button phx-click={JS.push("clicked", page_loading: true)}>click me!</button>
```
### push(event, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L150)
See [`push/1`](#push/1).
### push(js, event, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L159)
See [`push/1`](#push/1).
### remove\_attribute(attr)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L585)
Removes an attribute from elements.
* `attr` - The string attribute name to remove.
#### Options
* `:to` - The optional DOM selector to remove attributes from. Defaults to the interacted element.
#### Examples
```
<button phx-click={JS.remove_attribute("aria-expanded", to: "#dropdown")}>
hide
</button>
```
### remove\_attribute(attr, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L588)
See [`remove_attribute/1`](#remove_attribute/1).
### remove\_attribute(js, attr, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L594)
See [`remove_attribute/1`](#remove_attribute/1).
### remove\_class(names)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L465)
Removes classes from elements.
* `names` - The string of classes to remove.
#### Options
* `:to` - The optional DOM selector to remove classes from. Defaults to the interacted element.
* `:transition` - The string of classes to apply before removing classes or a 3-tuple containing the transition class, the class to apply to start the transition, and the ending transition class, such as: `{"ease-out duration-300", "opacity-0", "opacity-100"}`
* `:time` - The time to apply the transition from `:transition`. Defaults 200
#### Examples
```
<div id="item">My Item</div>
<button phx-click={JS.remove_class("highlight underline", to: "#item")}>
remove highlight!
</button>
```
### remove\_class(js, names)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L468)
See [`remove_class/1`](#remove_class/1).
### remove\_class(js, names, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L477)
See [`remove_class/1`](#remove_class/1).
### set\_attribute(arg)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L555)
Sets an attribute on elements.
Accepts a tuple containing the string attribute name/value pair.
#### Options
* `:to` - The optional DOM selector to add attributes to. Defaults to the interacted element.
#### Examples
```
<button phx-click={JS.set_attribute({"aria-expanded", "true"}, to: "#dropdown")}>
show
</button>
```
### set\_attribute(js, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L558)
See [`set_attribute/1`](#set_attribute/1).
### set\_attribute(js, arg, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L564)
See [`set_attribute/1`](#set_attribute/1).
### show(opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L331)
Shows elements.
#### Options
* `:to` - The optional DOM selector to show. Defaults to the interacted element.
* `:transition` - The string of classes to apply before showing or a 3-tuple containing the transition class, the class to apply to start the transition, and the ending transition class, such as: `{"ease-out duration-300", "opacity-0", "opacity-100"}`
* `:time` - The time to apply the transition from `:transition`. Defaults 200
* `:display` - The optional display value to set when showing. Defaults `"block"`.
When the show is complete on the client, a `phx:show-start` and `phx:show-end` event will be dispatched to the shown elements.
#### Examples
```
<div id="item">My Item</div>
<button phx-click={JS.show(to: "#item")}>
show!
</button>
<button phx-click={JS.show(to: "#item", transition: "fade-in-scale")}>
show fancy!
</button>
```
### show(js, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L336)
See [`show/1`](#show/1).
### toggle(opts \\ [])[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L281)
Toggles elements.
#### Options
* `:to` - The optional DOM selector to toggle. Defaults to the interacted element.
* `:in` - The string of classes to apply when toggling in, or a 3-tuple containing the transition class, the class to apply to start the transition, and the ending transition class, such as: `{"ease-out duration-300", "opacity-0", "opacity-100"}`
* `:out` - The string of classes to apply when toggling out, or a 3-tuple containing the transition class, the class to apply to start the transition, and the ending transition class, such as: `{"ease-out duration-300", "opacity-100", "opacity-0"}`
* `:time` - The time to apply the transition `:in` and `:out` classes. Defaults 200
* `:display` - The optional display value to set when toggling in. Defaults `"block"`.
When the toggle is complete on the client, a `phx:show-start` or `phx:hide-start`, and `phx:show-end` or `phx:hide-end` event will be dispatched to the toggled elements.
#### Examples
```
<div id="item">My Item</div>
<button phx-click={JS.toggle(to: "#item")}>
toggle item!
</button>
<button phx-click={JS.toggle(to: "#item", in: "fade-in-scale", out: "fade-out-scale")}>
toggle fancy!
</button>
```
### toggle(js, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L286)
See [`toggle/1`](#toggle/1).
### transition(transition)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L512)
Transitions elements.
* `transition` - The string of classes to apply before removing classes or a 3-tuple containing the transition class, the class to apply to start the transition, and the ending transition class, such as: `{"ease-out duration-300", "opacity-0", "opacity-100"}`
Transitions are useful for temporarily adding an animation class to element(s), such as for highlighting content changes.
#### Options
* `:to` - The optional DOM selector to apply transitions to. Defaults to the interacted element.
* `:time` - The time to apply the transition from `:transition`. Defaults 200
#### Examples
```
<div id="item">My Item</div>
<button phx-click={JS.transition("shake", to: "#item")}>Shake!</button>
```
### transition(transition, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L517)
See [`transition/1`](#transition/1).
### transition(js, transition, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/js.ex#L527)
See [`transition/1`](#transition/1).
| programming_docs |
phoenix Form bindings Form bindings
==============
A note about form helpers
--------------------------
LiveView works with the existing [`Phoenix.HTML`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.html) form helpers. If you want to use helpers such as [`text_input/2`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Form.html#text_input/2), etc. be sure to `use Phoenix.HTML` at the top of your LiveView. If your application was generated with Phoenix v1.6, then [`mix phx.new`](mix.tasks.phx.new) automatically uses [`Phoenix.HTML`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.html) when you `use MyAppWeb, :live_view` or `use MyAppWeb, :live_component` in your modules.
Using the generated `:live_view` and `:live_component` helpers will also `import MyAppWeb.ErrorHelpers`, a module generated as part of your application where `error_tag/2` resides (usually located at `lib/my_app_web/views/error_helpers.ex`). You are welcome to change the `ErrorHelpers` module as you prefer.
Form Events
------------
To handle form changes and submissions, use the `phx-change` and `phx-submit` events. In general, it is preferred to handle input changes at the form level, where all form fields are passed to the LiveView's callback given any single input change, but individual inputs may also track their own changes. For example, to handle real-time form validation and saving, your form would use both `phx-change` and `phx-submit` bindings:
```
<.form let={f} for={@changeset} phx-change="validate" phx-submit="save">
<%= label f, :username %>
<%= text_input f, :username %>
<%= error_tag f, :username %>
<%= label f, :email %>
<%= text_input f, :email %>
<%= error_tag f, :email %>
<%= submit "Save" %>
</.form>
```
Next, your LiveView picks up the events in `handle_event` callbacks:
```
def render(assigns) ...
def mount(_params, _session, socket) do
{:ok, assign(socket, %{changeset: Accounts.change_user(%User{})})}
end
def handle_event("validate", %{"user" => params}, socket) do
changeset =
%User{}
|> Accounts.change_user(params)
|> Map.put(:action, :insert)
{:noreply, assign(socket, changeset: changeset)}
end
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.create_user(user_params) do
{:ok, user} ->
{:noreply,
socket
|> put_flash(:info, "user created")
|> redirect(to: Routes.user_path(MyAppWeb.Endpoint, MyAppWeb.User.ShowView, user))}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
```
The validate callback simply updates the changeset based on all form input values, then assigns the new changeset to the socket. If the changeset changes, such as generating new errors, [`render/1`](phoenix.liveview#c:render/1) is invoked and the form is re-rendered.
Likewise for `phx-submit` bindings, the same callback is invoked and persistence is attempted. On success, a `:noreply` tuple is returned and the socket is annotated for redirect with [`Phoenix.LiveView.redirect/2`](phoenix.liveview#redirect/2) to the new user page, otherwise the socket assigns are updated with the errored changeset to be re-rendered for the client.
You may wish for an individual input to use its own change event or to target a different component. This can be accomplished by annotating the input itself with `phx-change`, for example:
```
<.form let={f} for={@changeset} phx-change="validate" phx-submit="save">
...
<%= label f, :county %>
<%= text_input f, :email, phx_change: "email_changed", phx_target: @myself %>
</.form>
```
Then your LiveView or LiveComponent would handle the event:
```
def handle_event("email_changed", %{"user" => %{"email" => email}}, socket) do
...
end
```
*Note*: only the individual input is sent as params for an input marked with `phx-change`.
`phx-feedback-for`
-------------------
For proper form error tag updates, the error tag must specify which input it belongs to. This is accomplished with the `phx-feedback-for` attribute, which specifies the name (or id, for backwards compatibility) of the input it belongs to. Failing to add the `phx-feedback-for` attribute will result in displaying error messages for form fields that the user has not changed yet (e.g. required fields further down on the page).
For example, your `MyAppWeb.ErrorHelpers` may use this function:
```
def error_tag(form, field) do
form.errors
|> Keyword.get_values(field)
|> Enum.map(fn error ->
content_tag(:span, translate_error(error),
class: "invalid-feedback",
phx_feedback_for: input_name(form, field)
)
end)
end
```
Now, any DOM container with the `phx-feedback-for` attribute will receive a `phx-no-feedback` class in cases where the form fields has yet to receive user input/focus. The following css rules are generated in new projects to hide the errors:
```
.phx-no-feedback.invalid-feedback, .phx-no-feedback .invalid-feedback {
display: none;
}
```
Number inputs
--------------
Number inputs are a special case in LiveView forms. On programmatic updates, some browsers will clear invalid inputs. So LiveView will not send change events from the client when an input is invalid, instead allowing the browser's native validation UI to drive user interaction. Once the input becomes valid, change and submit events will be sent normally.
```
<input type="number">
```
This is known to have a plethora of problems including accessibility, large numbers are converted to exponential notation, and scrolling can accidentally increase or decrease the number.
One alternative is the `inputmode` attribute, which may serve your application's needs and users much better. According to [Can I Use?](https://caniuse.com/#search=inputmode), the following is supported by 86% of the global market (as of Sep 2021):
```
<input type="text" inputmode="numeric" pattern="[0-9]*">
```
Password inputs
----------------
Password inputs are also special cased in [`Phoenix.HTML`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.html). For security reasons, password field values are not reused when rendering a password input tag. This requires explicitly setting the `:value` in your markup, for example:
```
<%= password_input f, :password, value: input_value(f, :password) %>
<%= password_input f, :password_confirmation, value: input_value(f, :password_confirmation) %>
<%= error_tag f, :password %>
<%= error_tag f, :password_confirmation %>
```
File inputs
------------
LiveView forms support [reactive file inputs](uploads), including drag and drop support via the `phx-drop-target` attribute:
```
<div class="container" phx-drop-target={@uploads.avatar.ref}>
...
<%= live_file_input @uploads.avatar %>
</div>
```
See [`Phoenix.LiveView.Helpers.live_file_input/2`](phoenix.liveview.helpers#live_file_input/2) for more.
Submitting the form action over HTTP
-------------------------------------
The `phx-trigger-action` attribute can be added to a form to trigger a standard form submit on DOM patch to the URL specified in the form's standard `action` attribute. This is useful to perform pre-final validation of a LiveView form submit before posting to a controller route for operations that require Plug session mutation. For example, in your LiveView template you can annotate the `phx-trigger-action` with a boolean assign:
```
<.form let={f} for={@changeset}
action={Routes.reset_password_path(@socket, :create)}
phx-submit="save",
phx-trigger-action={@trigger_submit}>
```
Then in your LiveView, you can toggle the assign to trigger the form with the current fields on next render:
```
def handle_event("save", params, socket) do
case validate_change_password(socket.assigns.user, params) do
{:ok, changeset} ->
{:noreply, assign(socket, changeset: changeset, trigger_submit: true)}
{:error, changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
```
Once `phx-trigger-action` is true, LiveView disconnects and then submits the form.
Recovery following crashes or disconnects
------------------------------------------
By default, all forms marked with `phx-change` will recover input values automatically after the user has reconnected or the LiveView has remounted after a crash. This is achieved by the client triggering the same `phx-change` to the server as soon as the mount has been completed.
**Note:** if you want to see form recovery working in development, please make sure to disable live reloading in development by commenting out the LiveReload plug in your `endpoint.ex` file or by setting `code_reloader: false` in your `config/dev.exs`. Otherwise live reloading may cause the current page to be reloaded whenever you restart the server, which will discard all form state.
For most use cases, this is all you need and form recovery will happen without consideration. In some cases, where forms are built step-by-step in a stateful fashion, it may require extra recovery handling on the server outside of your existing `phx-change` callback code. To enable specialized recovery, provide a `phx-auto-recover` binding on the form to specify a different event to trigger for recovery, which will receive the form params as usual. For example, imagine a LiveView wizard form where the form is stateful and built based on what step the user is on and by prior selections:
```
<form phx-change="validate_wizard_step" phx-auto-recover="recover_wizard">
```
On the server, the `"validate_wizard_step"` event is only concerned with the current client form data, but the server maintains the entire state of the wizard. To recover in this scenario, you can specify a recovery event, such as `"recover_wizard"` above, which would wire up to the following server callbacks in your LiveView:
```
def handle_event("validate_wizard_step", params, socket) do
# regular validations for current step
{:noreply, socket}
end
def handle_event("recover_wizard", params, socket) do
# rebuild state based on client input data up to the current step
{:noreply, socket}
end
```
To forgo automatic form recovery, set `phx-auto-recover="ignore"`.
JavaScript client specifics
----------------------------
The JavaScript client is always the source of truth for current input values. For any given input with focus, LiveView will never overwrite the input's current value, even if it deviates from the server's rendered updates. This works well for updates where major side effects are not expected, such as form validation errors, or additive UX around the user's input values as they fill out a form.
For these use cases, the `phx-change` input does not concern itself with disabling input editing while an event to the server is in flight. When a `phx-change` event is sent to the server, the input tag and parent form tag receive the `phx-change-loading` css class, then the payload is pushed to the server with a `"_target"` param in the root payload containing the keyspace of the input name which triggered the change event.
For example, if the following input triggered a change event:
```
<input name="user[username]"/>
```
The server's `handle_event/3` would receive a payload:
```
%{"_target" => ["user", "username"], "user" => %{"username" => "Name"}}
```
The `phx-submit` event is used for form submissions where major side effects typically happen, such as rendering new containers, calling an external service, or redirecting to a new page.
On submission of a form bound with a `phx-submit` event:
1. The form's inputs are set to `readonly`
2. Any submit button on the form is disabled
3. The form receives the `"phx-submit-loading"` class
On completion of server processing of the `phx-submit` event:
1. The submitted form is reactivated and loses the `"phx-submit-loading"` class
2. The last input with focus is restored (unless another input has received focus)
3. Updates are patched to the DOM as usual
To handle latent events, the `<button>` tag of a form can be annotated with `phx-disable-with`, which swaps the element's `innerText` with the provided value during event submission. For example, the following code would change the "Save" button to "Saving...", and restore it to "Save" on acknowledgment:
```
<button type="submit" phx-disable-with="Saving...">Save</button>
```
You may also take advantage of LiveView's CSS loading state classes to swap out your form content while the form is submitting. For example, with the following rules in your `app.css`:
```
.while-submitting { display: none; }
.inputs { display: block; }
.phx-submit-loading .while-submitting { display: block; }
.phx-submit-loading .inputs { display: none; }
```
You can show and hide content with the following markup:
```
<form phx-change="update">
<div class="while-submitting">Please wait while we save our content...</div>
<div class="inputs">
<input type="text" name="text" value={@text}>
</div>
</form>
```
Additionally, we strongly recommend including a unique HTML "id" attribute on the form. When DOM siblings change, elements without an ID will be replaced rather than moved, which can cause issues such as form fields losing focus.
[← Previous Page Bindings](bindings) [Next Page → DOM patching & temporary assigns](dom-patching)
phoenix Phoenix.LiveView behaviour Phoenix.LiveView behaviour
===========================
LiveView provides rich, real-time user experiences with server-rendered HTML.
The LiveView programming model is declarative: instead of saying "once event X happens, change Y on the page", events in LiveView are regular messages which may cause changes to its state. Once the state changes, LiveView will re-render the relevant parts of its HTML template and push it to the browser, which updates itself in the most efficient manner. This means developers write LiveView templates as any other server-rendered HTML and LiveView does the hard work of tracking changes and sending the relevant diffs to the browser.
At the end of the day, a LiveView is nothing more than a process that receives events as messages and updates its state. The state itself is nothing more than functional and immutable Elixir data structures. The events are either internal application messages (usually emitted by [`Phoenix.PubSub`](https://hexdocs.pm/phoenix_pubsub/2.0.0/Phoenix.PubSub.html)) or sent by the client/browser.
LiveView is first rendered statically as part of regular HTTP requests, which provides quick times for "First Meaningful Paint", in addition to helping search and indexing engines. Then a persistent connection is established between client and server. This allows LiveView applications to react faster to user events as there is less work to be done and less data to be sent compared to stateless requests that have to authenticate, decode, load, and encode data on every request. The flipside is that LiveView uses more memory on the server compared to stateless requests.
Life-cycle
-----------
A LiveView begins as a regular HTTP request and HTML response, and then upgrades to a stateful view on client connect, guaranteeing a regular HTML page even if JavaScript is disabled. Any time a stateful view changes or updates its socket assigns, it is automatically re-rendered and the updates are pushed to the client.
You begin by rendering a LiveView typically from your router. When LiveView is first rendered, the [`mount/3`](#c:mount/3) callback is invoked with the current params, the current session and the LiveView socket. As in a regular request, `params` contains public data that can be modified by the user. The `session` always contains private data set by the application itself. The [`mount/3`](#c:mount/3) callback wires up socket assigns necessary for rendering the view. After mounting, [`handle_params/3`](#c:handle_params/3) is invoked so uri and query params are handled. Finally, [`render/1`](#c:render/1) is invoked and the HTML is sent as a regular HTML response to the client.
After rendering the static page, LiveView connects from the client to the server where stateful views are spawned to push rendered updates to the browser, and receive client events via `phx-` bindings. Just like the first rendering, [`mount/3`](#c:mount/3), is invoked with params, session, and socket state, However in the connected client case, a LiveView process is spawned on the server, runs [`handle_params/3`](#c:handle_params/3) again and then pushes the result of [`render/1`](#c:render/1) to the client and continues on for the duration of the connection. If at any point during the stateful life-cycle a crash is encountered, or the client connection drops, the client gracefully reconnects to the server, calling [`mount/3`](#c:mount/3) and [`handle_params/3`](#c:handle_params/3) again.
LiveView also allows attaching hooks to specific life-cycle stages with [`attach_hook/4`](#attach_hook/4).
Example
--------
Before writing your first example, make sure that Phoenix LiveView is properly installed. If you are just getting started, this can be easily done by running `mix phx.new my_app --live`. The `phx.new` command with the `--live` flag will create a new project with LiveView installed and configured. Otherwise, please follow the steps in the [installation guide](installation) before continuing.
A LiveView is a simple module that requires two callbacks: [`mount/3`](#c:mount/3) and [`render/1`](#c:render/1):
```
defmodule MyAppWeb.ThermostatLive do
# In Phoenix v1.6+ apps, the line below should be: use MyAppWeb, :live_view
use Phoenix.LiveView
def render(assigns) do
~H"""
Current temperature: <%= @temperature %>
"""
end
def mount(_params, %{"current_user_id" => user_id}, socket) do
temperature = Thermostat.get_user_reading(user_id)
{:ok, assign(socket, :temperature, temperature)}
end
end
```
The [`render/1`](#c:render/1) callback receives the `socket.assigns` and is responsible for returning rendered content. We use the `~H` sigil to define a HEEx template, which stands for HTML+EEx. They are an extension of Elixir's builtin EEx templates, with support for HTML validation, syntax-based components, smart change tracking, and more. You can learn more about the template syntax in [`Phoenix.LiveView.Helpers.sigil_H/2`](phoenix.liveview.helpers#sigil_H/2).
Next, decide where you want to use your LiveView.
You can serve the LiveView directly from your router (recommended):
```
defmodule MyAppWeb.Router do
use Phoenix.Router
import Phoenix.LiveView.Router
scope "/", MyAppWeb do
live "/thermostat", ThermostatLive
end
end
```
*Note:* the above assumes there is `plug :put_root_layout` call in your router that configures the LiveView layout. This call is automatically included in Phoenix v1.6 apps and described in the installation guide.
Alternatively, you can `live_render` from any template. In your view:
```
import Phoenix.LiveView.Helpers
```
Then in your template:
```
<h1>Temperature Control</h1>
<%= live_render(@conn, MyAppWeb.ThermostatLive) %>
```
Once the LiveView is rendered, a regular HTML response is sent. In your app.js file, you should find the following:
```
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
liveSocket.connect()
```
After the client connects, [`mount/3`](#c:mount/3) will be invoked inside a spawned LiveView process. At this point, you can use [`connected?/1`](#connected?/1) to conditionally perform stateful work, such as subscribing to pubsub topics, sending messages, etc. For example, you can periodically update a LiveView with a timer:
```
defmodule DemoWeb.ThermostatLive do
use Phoenix.LiveView
...
def mount(_params, %{"current_user_id" => user_id}, socket) do
if connected?(socket), do: Process.send_after(self(), :update, 30000)
case Thermostat.get_user_reading(user_id) do
{:ok, temperature} ->
{:ok, assign(socket, temperature: temperature, user_id: user_id)}
{:error, _reason} ->
{:ok, redirect(socket, to: "/error")}
end
end
def handle_info(:update, socket) do
Process.send_after(self(), :update, 30000)
{:ok, temperature} = Thermostat.get_reading(socket.assigns.user_id)
{:noreply, assign(socket, :temperature, temperature)}
end
end
```
We used `connected?(socket)` on mount to send our view a message every 30s if the socket is in a connected state. We receive the `:update` message in the [`handle_info/2`](#c:handle_info/2) callback, just like in an Elixir [`GenServer`](https://hexdocs.pm/elixir/GenServer.html), and update our socket assigns. Whenever a socket's assigns change, [`render/1`](#c:render/1) is automatically invoked, and the updates are sent to the client.
Colocating templates
---------------------
In the examples above, we have placed the template directly inside the LiveView:
```
defmodule MyAppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
~H"""
Current temperature: <%= @temperature %>
"""
end
```
For larger templates, you can place them in a file in the same directory and same name as the LiveView. For example, if the file above is placed at `lib/my_app_web/live/thermostat_live.ex`, you can also remove the [`render/1`](#c:render/1) definition above and instead put the template code at `lib/my_app_web/live/thermostat_live.html.heex`.
Alternatively, you can keep the [`render/1`](#c:render/1) callback but delegate to an existing [`Phoenix.View`](https://hexdocs.pm/phoenix_view/1.1.2/Phoenix.View.html) module in your application. For example:
```
defmodule MyAppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
Phoenix.View.render(MyAppWeb.PageView, "page.html", assigns)
end
end
```
In all cases, each assign in the template will be accessible as `@assign`. You can learn more about [assigns and HEEx templates in their own guide](assigns-eex).
Bindings
---------
Phoenix supports DOM element bindings for client-server interaction. For example, to react to a click on a button, you would render the element:
```
<button phx-click="inc_temperature">+</button>
```
Then on the server, all LiveView bindings are handled with the [`handle_event/3`](#c:handle_event/3) callback, for example:
```
def handle_event("inc_temperature", _value, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
```
To update UI state, for example, to open and close dropdowns, switch tabs, etc, LiveView also supports JS commands ([`Phoenix.LiveView.JS`](phoenix.liveview.js)), which execute directly on the client without reaching the server. To learn more, see [our bindings page](bindings) for a complete list of all LiveView bindings as well as our [JavaScript interoperability guide](https://hexdocs.pm/phoenix_live_view/js-interop.html).
Compartmentalize state, markup, and events in LiveView
-------------------------------------------------------
LiveView supports two extension mechanisms: function components, provided by `HEEx` templates, and stateful components.
Function components are any function that receives an assigns map, similar to `render(assigns)` in our LiveView, and returns a `~H` template. For example:
```
def weather_greeting(assigns) do
~H"""
<div title="My div" class={@class}>
<p>Hello <%= @name %></p>
<MyApp.Weather.city name="Kraków"/>
</div>
"""
end
```
You can learn more about function components in the [`Phoenix.Component`](phoenix.component) module. At the end of the day, they are useful mechanism to reuse markup in your LiveViews.
However, sometimes you need to compartmentalize or reuse more than markup. Perhaps you want to move part of the state or part of the events in your LiveView to a separate module. For these cases, LiveView provides [`Phoenix.LiveComponent`](phoenix.livecomponent), which are rendered using [`live_component/1`](phoenix.liveview.helpers#live_component/1):
```
<.live_component module={UserComponent} id={user.id} user={user} />
```
Components have their own [`mount/3`](#c:mount/3) and [`handle_event/3`](#c:handle_event/3) callbacks, as well as their own state with change tracking support. Components are also lightweight as they "run" in the same process as the parent `LiveView`. However, this means an error in a component would cause the whole view to fail to render. See [`Phoenix.LiveComponent`](phoenix.livecomponent) for a complete rundown on components.
Finally, if you want complete isolation between parts of a LiveView, you can always render a LiveView inside another LiveView by calling [`live_render/3`](phoenix.liveview.helpers#live_render/3). This child LiveView runs in a separate process than the parent, with its own callbacks. If a child LiveView crashes, it won't affect the parent. If the parent crashes, all children are terminated.
When rendering a child LiveView, the `:id` option is required to uniquely identify the child. A child LiveView will only ever be rendered and mounted a single time, provided its ID remains unchanged.
Given that a LiveView runs on its own process, it is an excellent tool for creating completely isolated UI elements, but it is a slightly expensive abstraction if all you want is to compartmentalize markup or events (or both).
To sum it up:
* use [`Phoenix.Component`](phoenix.component) to compartmentalize/reuse markup
* use [`Phoenix.LiveComponent`](phoenix.livecomponent) to compartmentalize state, markup, and events
* use nested [`Phoenix.LiveView`](phoenix.liveview#content) to compartmentalize state, markup, events, and error isolation
Endpoint configuration
-----------------------
LiveView accepts the following configuration in your endpoint under the `:live_view` key:
* `:signing_salt` (required) - the salt used to sign data sent to the client
* `:hibernate_after` (optional) - the idle time in milliseconds allowed in the LiveView before compressing its own memory and state. Defaults to 15000ms (15 seconds)
Guides
-------
LiveView has many guides to help you on your journey.
### Server-side
These guides focus on server-side functionality:
* [Assigns and HEEx templates](assigns-eex)
* [Error and exception handling](error-handling)
* [Live Layouts](live-layouts)
* [Live Navigation](live-navigation)
* [Security considerations of the LiveView model](security-model)
* [Telemetry](telemetry)
* [Uploads](uploads)
* [Using Gettext for internationalization](using-gettext)
### Client-side
These guides focus on LiveView bindings and client-side integration:
* [Bindings](bindings)
* [Form bindings](form-bindings)
* [DOM patching and temporary assigns](dom-patching)
* [JavaScript interoperability](https://hexdocs.pm/phoenix_live_view/js-interop.html)
* [Uploads (External)](uploads-external)
Summary
========
Types
------
[unsigned\_params()](#t:unsigned_params/0) Callbacks
----------
[handle\_call(msg, {}, socket)](#c:handle_call/3) Invoked to handle calls from other Elixir processes.
[handle\_cast(msg, socket)](#c:handle_cast/2) Invoked to handle casts from other Elixir processes.
[handle\_event(event, unsigned\_params, socket)](#c:handle_event/3) Invoked to handle events sent by the client.
[handle\_info(msg, socket)](#c:handle_info/2) Invoked to handle messages from other Elixir processes.
[handle\_params(unsigned\_params, uri, socket)](#c:handle_params/3) Invoked after mount and whenever there is a live patch event.
[mount( params, session, socket )](#c:mount/3) The LiveView entry-point.
[render(assigns)](#c:render/1) Renders a template.
[terminate(reason, socket)](#c:terminate/2) Invoked when the LiveView is terminating.
Functions
----------
[\_\_using\_\_(opts)](#__using__/1) Uses LiveView in the current module to mark it a LiveView.
[allow\_upload(socket, name, options)](#allow_upload/3) Allows an upload for the provided name.
[assign(socket\_or\_assigns, keyword\_or\_map)](#assign/2) Adds key-value pairs to assigns.
[assign(socket\_or\_assigns, key, value)](#assign/3) Adds a `key`-`value` pair to `socket_or_assigns`.
[assign\_new(socket\_or\_assigns, key, fun)](#assign_new/3) Assigns the given `key` with value from `fun` into `socket_or_assigns` if one does not yet exist.
[attach\_hook(socket, name, stage, fun)](#attach_hook/4) Attaches the given `fun` by `name` for the lifecycle `stage` into `socket`.
[cancel\_upload(socket, name, entry\_ref)](#cancel_upload/3) Cancels an upload for the given entry.
[changed?(socket\_or\_assigns, key)](#changed?/2) Checks if the given key changed in `socket_or_assigns`.
[clear\_flash(socket)](#clear_flash/1) Clears the flash.
[clear\_flash(socket, key)](#clear_flash/2) Clears a key from the flash.
[connected?(socket)](#connected?/1) Returns true if the socket is connected.
[consume\_uploaded\_entries(socket, name, func)](#consume_uploaded_entries/3) Consumes the uploaded entries.
[consume\_uploaded\_entry(socket, entry, func)](#consume_uploaded_entry/3) Consumes an individual uploaded entry.
[detach\_hook(socket, name, stage)](#detach_hook/3) Detaches a hook with the given `name` from the lifecycle `stage`.
[disallow\_upload(socket, name)](#disallow_upload/2) Revokes a previously allowed upload from [`allow_upload/3`](#allow_upload/3).
[get\_connect\_info(socket)](#get_connect_info/1) deprecated [get\_connect\_info(socket, key)](#get_connect_info/2) Accesses a given connect info key from the socket.
[get\_connect\_params(socket)](#get_connect_params/1) Accesses the connect params sent by the client for use on connected mount.
[on\_mount(mod\_or\_mod\_arg)](#on_mount/1) Declares a module callback to be invoked on the LiveView's mount.
[push\_event(socket, event, payload)](#push_event/3) Pushes an event to the client.
[push\_patch(socket, opts)](#push_patch/2) Annotates the socket for navigation within the current LiveView.
[push\_redirect(socket, opts)](#push_redirect/2) Annotates the socket for navigation to another LiveView.
[put\_flash(socket, kind, msg)](#put_flash/3) Adds a flash message to the socket to be displayed.
[redirect(socket, arg2)](#redirect/2) Annotates the socket for redirect to a destination path.
[send\_update(pid \\ self(), module, assigns)](#send_update/3) Asynchronously updates a [`Phoenix.LiveComponent`](phoenix.livecomponent) with new assigns.
[send\_update\_after(pid \\ self(), module, assigns, time\_in\_milliseconds)](#send_update_after/4) Similar to [`send_update/3`](#send_update/3) but the update will be delayed according to the given `time_in_milliseconds`.
[static\_changed?(socket)](#static_changed?/1) Returns true if the socket is connected and the tracked static assets have changed.
[transport\_pid(socket)](#transport_pid/1) Returns the transport pid of the socket.
[update(socket\_or\_assigns, key, fun)](#update/3) Updates an existing `key` with `fun` in the given `socket_or_assigns`.
[uploaded\_entries(socket, name)](#uploaded_entries/2) Returns the completed and in progress entries for the upload.
Types
======
### unsigned\_params()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L327)
```
@type unsigned_params() :: map()
```
Callbacks
==========
### handle\_call(msg, {}, socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L422)
```
@callback handle_call(
msg :: term(),
{pid(), reference()},
socket :: Phoenix.LiveView.Socket.t()
) ::
{:noreply, Phoenix.LiveView.Socket.t()}
| {:reply, term(), Phoenix.LiveView.Socket.t()}
```
Invoked to handle calls from other Elixir processes.
See [`GenServer.call/3`](https://hexdocs.pm/elixir/GenServer.html#call/3) and [`GenServer.handle_call/3`](https://hexdocs.pm/elixir/GenServer.html#c:handle_call/3) for more information.
### handle\_cast(msg, socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L433)
```
@callback handle_cast(msg :: term(), socket :: Phoenix.LiveView.Socket.t()) ::
{:noreply, Phoenix.LiveView.Socket.t()}
```
Invoked to handle casts from other Elixir processes.
See [`GenServer.cast/2`](https://hexdocs.pm/elixir/GenServer.html#cast/2) and [`GenServer.handle_cast/2`](https://hexdocs.pm/elixir/GenServer.html#c:handle_cast/2) for more information. It must always return `{:noreply, socket}`, where `:noreply` means no additional information is sent to the process which cast the message.
### handle\_event(event, unsigned\_params, socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L413)
```
@callback handle_event(
event :: binary(),
unsigned_params(),
socket :: Phoenix.LiveView.Socket.t()
) ::
{:noreply, Phoenix.LiveView.Socket.t()}
| {:reply, map(), Phoenix.LiveView.Socket.t()}
```
Invoked to handle events sent by the client.
It receives the `event` name, the event payload as a map, and the socket.
It must return `{:noreply, socket}`, where `:noreply` means no additional information is sent to the client, or `{:reply, map(), socket}`, where the given `map()` is encoded and sent as a reply to the client.
### handle\_info(msg, socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L444)
```
@callback handle_info(msg :: term(), socket :: Phoenix.LiveView.Socket.t()) ::
{:noreply, Phoenix.LiveView.Socket.t()}
```
Invoked to handle messages from other Elixir processes.
See [`Kernel.send/2`](https://hexdocs.pm/elixir/Kernel.html#send/2) and [`GenServer.handle_info/2`](https://hexdocs.pm/elixir/GenServer.html#c:handle_info/2) for more information. It must always return `{:noreply, socket}`, where `:noreply` means no additional information is sent to the process which sent the message.
### handle\_params(unsigned\_params, uri, socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L399)
```
@callback handle_params(
unsigned_params(),
uri :: String.t(),
socket :: Phoenix.LiveView.Socket.t()
) ::
{:noreply, Phoenix.LiveView.Socket.t()}
```
Invoked after mount and whenever there is a live patch event.
It receives the current `params`, including parameters from the router, the current `uri` from the client and the `socket`. It is invoked after mount or whenever there is a live navigation event caused by [`push_patch/2`](#push_patch/2) or [`Phoenix.LiveView.Helpers.live_patch/2`](phoenix.liveview.helpers#live_patch/2).
It must always return `{:noreply, socket}`, where `:noreply` means no additional information is sent to the client.
### mount( params, session, socket )[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L359)
```
@callback mount(
params :: unsigned_params() | :not_mounted_at_router,
session :: map(),
socket :: Phoenix.LiveView.Socket.t()
) ::
{:ok, Phoenix.LiveView.Socket.t()}
| {:ok, Phoenix.LiveView.Socket.t(), keyword()}
```
The LiveView entry-point.
For each LiveView in the root of a template, [`mount/3`](#c:mount/3) is invoked twice: once to do the initial page load and again to establish the live socket.
It expects three arguments:
* `params` - a map of string keys which contain public information that can be set by the user. The map contains the query params as well as any router path parameter. If the LiveView was not mounted at the router, this argument is the atom `:not_mounted_at_router`
* `session` - the connection session
* `socket` - the LiveView socket
It must return either `{:ok, socket}` or `{:ok, socket, options}`, where `options` is one of:
* `:temporary_assigns` - a keyword list of assigns that are temporary and must be reset to their value after every render. Note that once the value is reset, it won't be re-rendered again until it is explicitly assigned
* `:layout` - the optional layout to be used by the LiveView
### render(assigns)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L377)
```
@callback render(assigns :: Phoenix.LiveView.Socket.assigns()) ::
Phoenix.LiveView.Rendered.t()
```
Renders a template.
This callback is invoked whenever LiveView detects new content must be rendered and sent to the client.
If you define this function, it must return a template defined via the [`Phoenix.LiveView.Helpers.sigil_H/2`](phoenix.liveview.helpers#sigil_H/2).
If you don't define this function, LiveView will attempt to render a template in the same directory as your LiveView. For example, if you have a LiveView named `MyApp.MyCustomView` inside `lib/my_app/live_views/my_custom_view.ex`, Phoenix will look for a template at `lib/my_app/live_views/my_custom_view.html.heex`.
### terminate(reason, socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L385)
```
@callback terminate(reason, socket :: Phoenix.LiveView.Socket.t()) :: term()
when reason: :normal | :shutdown | {:shutdown, :left | :closed | term()}
```
Invoked when the LiveView is terminating.
In case of errors, this callback is only invoked if the LiveView is trapping exits. See [`GenServer.terminate/2`](https://hexdocs.pm/elixir/GenServer.html#c:terminate/2) for more info.
Functions
==========
### \_\_using\_\_(opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L470)
Uses LiveView in the current module to mark it a LiveView.
```
use Phoenix.LiveView,
namespace: MyAppWeb,
container: {:tr, class: "colorized"},
layout: {MyAppWeb.LayoutView, "live.html"}
```
#### Options
* `:namespace` - configures the namespace the `LiveView` is in
* `:container` - configures the container the `LiveView` will be wrapped in
* `:layout` - configures the layout the `LiveView` will be rendered in
### allow\_upload(socket, name, options)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1120)
Allows an upload for the provided name.
#### Options
* `:accept` - Required. A list of unique file type specifiers or the atom :any to allow any kind of file. For example, `[".jpeg"]`, `:any`, etc.
* `:max_entries` - The maximum number of selected files to allow per file input. Defaults to 1.
* `:max_file_size` - The maximum file size in bytes to allow to be uploaded. Defaults 8MB. For example, `12_000_000`.
* `:chunk_size` - The chunk size in bytes to send when uploading. Defaults `64_000`.
* `:chunk_timeout` - The time in milliseconds to wait before closing the upload channel when a new chunk has not been received. Defaults `10_000`.
* `:external` - The 2-arity function for generating metadata for external client uploaders. See the Uploads section for example usage.
* `:progress` - The optional 3-arity function for receiving progress events
* `:auto_upload` - Instructs the client to upload the file automatically on file selection instead of waiting for form submits. Default false.
Raises when a previously allowed upload under the same name is still active.
#### Examples
```
allow_upload(socket, :avatar, accept: ~w(.jpg .jpeg), max_entries: 2)
allow_upload(socket, :avatar, accept: :any)
```
For consuming files automatically as they are uploaded, you can pair `auto_upload: true` with a custom progress function to consume the entries as they are completed. For example:
```
allow_upload(socket, :avatar, accept: :any, progress: &handle_progress/3, auto_upload: true)
defp handle_progress(:avatar, entry, socket) do
if entry.done? do
uploaded_file =
consume_uploaded_entry(socket, entry, fn %{} = meta ->
{:ok, ...}
end)
{:noreply, put_flash(socket, :info, "file #{uploaded_file.name} uploaded")}
else
{:noreply, socket}
end
end
```
### assign(socket\_or\_assigns, keyword\_or\_map)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L894)
Adds key-value pairs to assigns.
The first argument is either a LiveView `socket` or an `assigns` map from function components.
A keyword list or a map of assigns must be given as argument to be merged into existing assigns.
#### Examples
```
iex> assign(socket, name: "Elixir", logo: "💧")
iex> assign(socket, %{name: "Elixir"})
```
### assign(socket\_or\_assigns, key, value)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L858)
Adds a `key`-`value` pair to `socket_or_assigns`.
The first argument is either a LiveView `socket` or an `assigns` map from function components.
#### Examples
```
iex> assign(socket, :name, "Elixir")
```
### assign\_new(socket\_or\_assigns, key, fun)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L751)
Assigns the given `key` with value from `fun` into `socket_or_assigns` if one does not yet exist.
The first argument is either a LiveView `socket` or an `assigns` map from function components.
This function is useful for lazily assigning values and referencing parent assigns. We will cover both use cases next.
#### Lazy assigns
Imagine you have a function component that accepts a color:
```
<.my_component color="red" />
```
The color is also optional, so you can skip it:
```
<.my_component />
```
In such cases, the implementation can use `assign_new` to lazily assign a color if none is given. Let's make it so it picks a random one when none is given:
```
def my_component(assigns) do
assigns = assign_new(assigns, :color, fn -> Enum.random(~w(red green blue)) end)
~H"""
<div class={"bg-#{@color}"}>
Example
</div>
"""
end
```
#### Referencing parent assigns
When a user first accesses an application using LiveView, the LiveView is first rendered in its disconnected state, as part of a regular HTML response. In some cases, there may be data that is shared by your Plug pipelines and your LiveView, such as the `:current_user` assign.
By using `assign_new` in the mount callback of your LiveView, you can instruct LiveView to re-use any assigns set in your Plug pipelines as part of [`Plug.Conn`](https://hexdocs.pm/plug/1.13.3/Plug.Conn.html), avoiding sending additional queries to the database. Imagine you have a Plug that does:
```
# A plug
def authenticate(conn, _opts) do
if user_id = get_session(conn, :user_id) do
assign(conn, :current_user, Accounts.get_user!(user_id))
else
send_resp(conn, :forbidden)
end
end
```
You can re-use the `:current_user` assign in your LiveView during the initial render:
```
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)}
end
```
In such case `conn.assigns.current_user` will be used if present. If there is no such `:current_user` assign or the LiveView was mounted as part of the live navigation, where no Plug pipelines are invoked, then the anonymous function is invoked to execute the query instead.
LiveView is also able to share assigns via `assign_new` within nested LiveView. If the parent LiveView defines a `:current_user` assign and the child LiveView also uses [`assign_new/3`](#assign_new/3) to fetch the `:current_user` in its `mount/3` callback, as above, the assign will be fetched from the parent LiveView, once again avoiding additional database queries.
Note that `fun` also provides access to the previously assigned values:
```
assigns =
assigns
|> assign_new(:foo, fn -> "foo" end)
|> assign_new(:bar, fn %{foo: foo} -> foo <> "bar" end)
```
### attach\_hook(socket, name, stage, fun)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1715)
Attaches the given `fun` by `name` for the lifecycle `stage` into `socket`.
> Note: This function is for server-side lifecycle callbacks. For client-side hooks, see the [JS Interop guide](https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks).
>
>
Hooks provide a mechanism to tap into key stages of the LiveView lifecycle in order to bind/update assigns, intercept events, patches, and regular messages when necessary, and to inject common functionality. Hooks may be attached to any of the following lifecycle stages: `:mount` (via [`on_mount/1`](#on_mount/1)), `:handle_params`, `:handle_event`, and `:handle_info`.
#### Return Values
Lifecycle hooks take place immediately before a given lifecycle callback is invoked on the LiveView. A hook may return `{:halt, socket}` to halt the reduction, otherwise it must return `{:cont, socket}` so the operation may continue until all hooks have been invoked for the current stage.
#### Halting the lifecycle
Note that halting from a hook *will halt the entire lifecycle stage*. This means that when a hook returns `{:halt, socket}` then the LiveView callback will **not** be invoked. This has some implications.
### Implications for plugin authors
When defining a plugin that matches on specific callbacks, you **must** define a catch-all clause, as your hook will be invoked even for events you may not be interested on.
### Implications for end-users
Allowing a hook to halt the invocation of the callback means that you can attach hooks to intercept specific events before detaching themselves, while allowing other events to continue normally.
#### Examples
```
def mount(_params, _session, socket) do
socket =
attach_hook(socket, :my_hook, :handle_event, fn
"very-special-event", _params, socket ->
# Handle the very special event and then detach the hook
{:halt, detach_hook(socket, :my_hook, :handle_event)}
_event, _params, socket ->
{:cont, socket}
end)
{:ok, socket}
end
```
### cancel\_upload(socket, name, entry\_ref)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1145)
Cancels an upload for the given entry.
#### Examples
```
<%= for entry <- @uploads.avatar.entries do %>
...
<button phx-click="cancel-upload" phx-value-ref="<%= entry.ref %>">cancel</button>
<% end %>
def handle_event("cancel-upload", %{"ref" => ref}, socket) do
{:noreply, cancel_upload(socket, :avatar, ref)}
end
```
### changed?(socket\_or\_assigns, key)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L967)
Checks if the given key changed in `socket_or_assigns`.
The first argument is either a LiveView `socket` or an `assigns` map from function components.
#### Examples
```
iex> changed?(socket, :count)
```
### clear\_flash(socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1014)
Clears the flash.
#### Examples
```
iex> clear_flash(socket)
```
### clear\_flash(socket, key)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1023)
Clears a key from the flash.
#### Examples
```
iex> clear_flash(socket, :info)
```
### connected?(socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L669)
Returns true if the socket is connected.
Useful for checking the connectivity status when mounting the view. For example, on initial page render, the view is mounted statically, rendered, and the HTML is sent to the client. Once the client connects to the server, a LiveView is then spawned and mounted statefully within a process. Use [`connected?/1`](#connected?/1) to conditionally perform stateful work, such as subscribing to pubsub topics, sending messages, etc.
#### Examples
```
defmodule DemoWeb.ClockLive do
use Phoenix.LiveView
...
def mount(_params, _session, socket) do
if connected?(socket), do: :timer.send_interval(1000, self(), :tick)
{:ok, assign(socket, date: :calendar.local_time())}
end
def handle_info(:tick, socket) do
{:noreply, assign(socket, date: :calendar.local_time())}
end
end
```
### consume\_uploaded\_entries(socket, name, func)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1188)
Consumes the uploaded entries.
Raises when there are still entries in progress. Typically called when submitting a form to handle the uploaded entries alongside the form data. For form submissions, it is guaranteed that all entries have completed before the submit event is invoked. Once entries are consumed, they are removed from the upload.
The function passed to consume may return a tagged tuple of the form `{:ok, my_result}` to collect results about the consumed entries, or `{:postpone, my_result}` to collect results, but postpone the file consumption to be performed later.
#### Examples
```
def handle_event("save", _params, socket) do
uploaded_files =
consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
dest = Path.join("priv/static/uploads", Path.basename(path))
File.cp!(path, dest)
{:ok, Routes.static_path(socket, "/uploads/#{Path.basename(dest)}")}
end)
{:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))}
end
```
### consume\_uploaded\_entry(socket, entry, func)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1225)
Consumes an individual uploaded entry.
Raises when the entry is still in progress. Typically called when submitting a form to handle the uploaded entries alongside the form data. Once entries are consumed, they are removed from the upload.
This is a lower-level feature than [`consume_uploaded_entries/3`](#consume_uploaded_entries/3) and useful for scenarios where you want to consume entries as they are individually completed.
Like [`consume_uploaded_entries/3`](#consume_uploaded_entries/3), the function passed to consume may return a tagged tuple of the form `{:ok, my_result}` to collect results about the consumed entries, or `{:postpone, my_result}` to collect results, but postpone the file consumption to be performed later.
#### Examples
```
def handle_event("save", _params, socket) do
case uploaded_entries(socket, :avatar) do
{[_|_] = entries, []} ->
uploaded_files = for entry <- entries do
consume_uploaded_entry(socket, entry, fn %{path: path} ->
dest = Path.join("priv/static/uploads", Path.basename(path))
File.cp!(path, dest)
{:ok, Routes.static_path(socket, "/uploads/#{Path.basename(dest)}")}
end)
end
{:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))}
_ ->
{:noreply, socket}
end
end
```
### detach\_hook(socket, name, stage)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1732)
Detaches a hook with the given `name` from the lifecycle `stage`.
> Note: This function is for server-side lifecycle callbacks. For client-side hooks, see the [JS Interop guide](https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks).
>
>
If no hook is found, this function is a no-op.
#### Examples
```
def handle_event(_, socket) do
{:noreply, detach_hook(socket, :hook_that_was_attached, :handle_event)}
end
```
### disallow\_upload(socket, name)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1129)
Revokes a previously allowed upload from [`allow_upload/3`](#allow_upload/3).
#### Examples
```
disallow_upload(socket, :avatar)
```
### get\_connect\_info(socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1377)
This function is deprecated. use get\_connect\_info/2 instead. ### get\_connect\_info(socket, key)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1416)
Accesses a given connect info key from the socket.
The following keys are supported: `:peer_data`, `:trace_context_headers`, `:x_headers`, `:uri`, and `:user_agent`.
The connect information is available only during mount. During disconnected render, all keys are available. On connected render, only the keys explicitly declared in your socket are available. See [`Phoenix.Endpoint.socket/3`](https://hexdocs.pm/phoenix/1.6.6/Phoenix.Endpoint.html#socket/3) for a complete description of the keys.
#### Examples
The first step is to declare the `connect_info` you want to receive. Typically, it includes at least the session, but you must include all other keys you want to access on connected mount, such as `:peer_data`:
```
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [:peer_data, session: @session_options]]
```
Those values can now be accessed on the connected mount as [`get_connect_info/2`](#get_connect_info/2):
```
def mount(_params, _session, socket) do
peer_data = get_connect_info(socket, :peer_data)
{:ok, assign(socket, ip: peer_data.address)}
end
```
If the key is not available, usually because it was not specified in `connect_info`, it returns nil.
### get\_connect\_params(socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1368)
Accesses the connect params sent by the client for use on connected mount.
Connect params are only sent when the client connects to the server and only remain available during mount. `nil` is returned when called in a disconnected state and a [`RuntimeError`](https://hexdocs.pm/elixir/RuntimeError.html) is raised if called after mount.
#### Reserved params
The following params have special meaning in LiveView:
* `"_csrf_token"` - the CSRF Token which must be explicitly set by the user when connecting
* `"_mounts"` - the number of times the current LiveView is mounted. It is 0 on first mount, then increases on each reconnect. It resets when navigating away from the current LiveView or on errors
* `"_track_static"` - set automatically with a list of all href/src from tags with the `phx-track-static` annotation in them. If there are no such tags, nothing is sent
#### Examples
```
def mount(_params, _session, socket) do
{:ok, assign(socket, width: get_connect_params(socket)["width"] || @width)}
end
```
### on\_mount(mod\_or\_mod\_arg)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L620)
Declares a module callback to be invoked on the LiveView's mount.
The function within the given module, which must be named `on_mount`, will be invoked before both disconnected and connected mounts. The hook has the option to either halt or continue the mounting process as usual. If you wish to redirect the LiveView, you **must** halt, otherwise an error will be raised.
Tip: if you need to define multiple `on_mount` callbacks, avoid defining multiple modules. Instead, pass a tuple and use pattern matching to handle different cases:
```
def on_mount(:admin, _params, _session, socket) do
{:cont, socket}
end
def on_mount(:user, _params, _session, socket) do
{:cont, socket}
end
```
And then invoke it as:
```
on_mount {MyAppWeb.SomeHook, :admin}
on_mount {MyAppWeb.SomeHook, :user}
```
Registering `on_mount` hooks can be useful to perform authentication as well as add custom behaviour to other callbacks via [`attach_hook/4`](#attach_hook/4).
#### Examples
The following is an example of attaching a hook via [`Phoenix.LiveView.Router.live_session/3`](phoenix.liveview.router#live_session/3):
```
# lib/my_app_web/live/init_assigns.ex
defmodule MyAppWeb.InitAssigns do
@moduledoc """
Ensures common `assigns` are applied to all LiveViews attaching this hook.
"""
import Phoenix.LiveView
def on_mount(:default, _params, _session, socket) do
{:cont, assign(socket, :page_title, "DemoWeb")}
end
def on_mount(:user, params, session, socket) do
# code
end
def on_mount(:admin, params, session, socket) do
# code
end
end
# lib/my_app_web/router.ex
defmodule MyAppWeb.Router do
use MyAppWeb, :router
# pipelines, plugs, etc.
live_session :default, on_mount: MyAppWeb.InitAssigns do
scope "/", MyAppWeb do
pipe_through :browser
live "/", PageLive, :index
end
end
live_session :authenticated, on_mount: {MyAppWeb.InitAssigns, :user} do
scope "/", MyAppWeb do
pipe_through [:browser, :require_user]
live "/profile", UserLive.Profile, :index
end
end
live_session :admins, on_mount: {MyAppWeb.InitAssigns, :admin} do
scope "/admin", MyAppWeb.Admin do
pipe_through [:browser, :require_user, :require_admin]
live "/", AdminLive.Index, :index
end
end
end
```
### push\_event(socket, event, payload)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1065)
Pushes an event to the client.
Events can be handled in two ways:
1. They can be handled on `window` via `addEventListener`. A "phx:" prefix will be added to the event name.
2. They can be handled inside a hook via `handleEvent`.
Note that events are dispatched to all active hooks on the client who are handling the given `event`. If you need to scope events, then this must be done by namespacing them.
#### Hook example
If you push a "scores" event from your LiveView:
```
{:noreply, push_event(socket, "scores", %{points: 100, user: "josé"})}
```
A hook declared via `phx-hook` can handle it via `handleEvent`:
```
this.handleEvent("scores", data => ...)
```
#### `window` example
All events are also dispatched on the `window`. This means you can handle them by adding listeners. For example, if you want to remove an element from the page, you can do this:
```
{:noreply, push_event(socket, "remove-el", %{id: "foo-bar"})}
```
And now in your app.js you can register and handle it:
```
window.addEventListener(
"phx:remove-el",
e => document.getElementById(e.detail.id).remove()
)
```
### push\_patch(socket, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1274)
Annotates the socket for navigation within the current LiveView.
When navigating to the current LiveView, [`handle_params/3`](#c:handle_params/3) is immediately invoked to handle the change of params and URL state. Then the new state is pushed to the client, without reloading the whole page while also maintaining the current scroll position. For live redirects to another LiveView, use [`push_redirect/2`](#push_redirect/2).
#### Options
* `:to` - the required path to link to. It must always be a local path
* `:replace` - the flag to replace the current history or push a new state. Defaults `false`.
#### Examples
```
{:noreply, push_patch(socket, to: "/")}
{:noreply, push_patch(socket, to: "/", replace: true)}
```
### push\_redirect(socket, opts)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1300)
Annotates the socket for navigation to another LiveView.
The current LiveView will be shutdown and a new one will be mounted in its place, without reloading the whole page. This can also be used to remount the same LiveView, in case you want to start fresh. If you want to navigate to the same LiveView without remounting it, use [`push_patch/2`](#push_patch/2) instead.
#### Options
* `:to` - the required path to link to. It must always be a local path
* `:replace` - the flag to replace the current history or push a new state. Defaults `false`.
#### Examples
```
{:noreply, push_redirect(socket, to: "/")}
{:noreply, push_redirect(socket, to: "/", replace: true)}
```
### put\_flash(socket, kind, msg)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1005)
Adds a flash message to the socket to be displayed.
*Note*: While you can use [`put_flash/3`](#put_flash/3) inside a [`Phoenix.LiveComponent`](phoenix.livecomponent), components have their own `@flash` assigns. The `@flash` assign in a component is only copied to its parent LiveView if the component calls [`push_redirect/2`](#push_redirect/2) or [`push_patch/2`](#push_patch/2).
*Note*: You must also place the [`Phoenix.LiveView.Router.fetch_live_flash/2`](phoenix.liveview.router#fetch_live_flash/2) plug in your browser's pipeline in place of `fetch_flash` for LiveView flash messages be supported, for example:
```
import Phoenix.LiveView.Router
pipeline :browser do
...
plug :fetch_live_flash
end
```
#### Examples
```
iex> put_flash(socket, :info, "It worked!")
iex> put_flash(socket, :error, "You can't access that page")
```
### redirect(socket, arg2)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1240)
Annotates the socket for redirect to a destination path.
*Note*: LiveView redirects rely on instructing client to perform a `window.location` update on the provided redirect location. The whole page will be reloaded and all state will be discarded.
#### Options
* `:to` - the path to redirect to. It must always be a local path
* `:external` - an external path to redirect to
### send\_update(pid \\ self(), module, assigns)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1595)
Asynchronously updates a [`Phoenix.LiveComponent`](phoenix.livecomponent) with new assigns.
The `:id` that identifies the component must be passed as part of the assigns and it will be used to identify the live components to be updated.
The `pid` argument is optional and it defaults to the current process, which means the update instruction will be sent to a component running on the same LiveView. If the current process is not a LiveView or you want to send updates to a live component running on another LiveView, you should explicitly pass the LiveView's pid instead.
When the component receives the update, first the optional [`preload/1`](phoenix.livecomponent#c:preload/1) then [`update/2`](phoenix.livecomponent#c:update/2) is invoked with the new assigns. If [`update/2`](phoenix.livecomponent#c:update/2) is not defined all assigns are simply merged into the socket.
While a component may always be updated from the parent by updating some parent assigns which will re-render the child, thus invoking [`update/2`](phoenix.livecomponent#c:update/2) on the child component, [`send_update/3`](#send_update/3) is useful for updating a component that entirely manages its own state, as well as messaging between components mounted in the same LiveView.
#### Examples
```
def handle_event("cancel-order", _, socket) do
...
send_update(Cart, id: "cart", status: "cancelled")
{:noreply, socket}
end
def handle_event("cancel-order-asynchronously", _, socket) do
...
pid = self()
Task.async(fn ->
# Do something asynchronously
send_update(pid, Cart, id: "cart", status: "cancelled")
end)
{:noreply, socket}
end
```
### send\_update\_after(pid \\ self(), module, assigns, time\_in\_milliseconds)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1628)
Similar to [`send_update/3`](#send_update/3) but the update will be delayed according to the given `time_in_milliseconds`.
#### Examples
```
def handle_event("cancel-order", _, socket) do
...
send_update_after(Cart, [id: "cart", status: "cancelled"], 3000)
{:noreply, socket}
end
def handle_event("cancel-order-asynchronously", _, socket) do
...
pid = self()
Task.async(fn ->
# Do something asynchronously
send_update_after(pid, Cart, [id: "cart", status: "cancelled"], 3000)
end)
{:noreply, socket}
end
```
### static\_changed?(socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1507)
Returns true if the socket is connected and the tracked static assets have changed.
This function is useful to detect if the client is running on an outdated version of the marked static files. It works by comparing the static paths sent by the client with the one on the server.
**Note:** this functionality requires Phoenix v1.5.2 or later.
To use this functionality, the first step is to annotate which static files you want to be tracked by LiveView, with the `phx-track-static`. For example:
```
<link phx-track-static rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/>
<script defer phx-track-static type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
```
Now, whenever LiveView connects to the server, it will send a copy `src` or `href` attributes of all tracked statics and compare those values with the latest entries computed by [`mix phx.digest`](https://hexdocs.pm/phoenix/1.6.6/Mix.Tasks.Phx.Digest.html) in the server.
The tracked statics on the client will match the ones on the server the huge majority of times. However, if there is a new deployment, those values may differ. You can use this function to detect those cases and show a banner to the user, asking them to reload the page. To do so, first set the assign on mount:
```
def mount(params, session, socket) do
{:ok, assign(socket, static_changed?: static_changed?(socket))}
end
```
And then in your views:
```
<%= if @static_changed? do %>
<div id="reload-static">
The app has been updated. Click here to <a href="#" onclick="window.location.reload()">reload</a>.
</div>
<% end %>
```
If you prefer, you can also send a JavaScript script that immediately reloads the page.
**Note:** only set `phx-track-static` on your own assets. For example, do not set it in external JavaScript files:
```
<script defer phx-track-static type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
```
Because you don't actually serve the file above, LiveView will interpret the static above as missing, and this function will return true.
### transport\_pid(socket)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1649)
Returns the transport pid of the socket.
Raises [`ArgumentError`](https://hexdocs.pm/elixir/ArgumentError.html) if the socket is not connected.
#### Examples
```
iex> transport_pid(socket)
#PID<0.107.0>
```
### update(socket\_or\_assigns, key, fun)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L928)
Updates an existing `key` with `fun` in the given `socket_or_assigns`.
The first argument is either a LiveView `socket` or an `assigns` map from function components.
The update function receives the current key's value and returns the updated value. Raises if the key does not exist.
The update function may also be of arity 2, in which case it receives the current key's value as the first argument and the current assigns as the second argument. Raises if the key does not exist.
#### Examples
```
iex> update(socket, :count, fn count -> count + 1 end)
iex> update(socket, :count, &(&1 + 1))
iex> update(socket, :max_users_this_session, fn current_max, %{users: users} -> max(current_max, length(users)) end)
```
### uploaded\_entries(socket, name)[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view.ex#L1160)
Returns the completed and in progress entries for the upload.
#### Examples
```
case uploaded_entries(socket, :photos) do
{[_ | _] = completed, []} ->
# all entries are completed
{[], [_ | _] = in_progress} ->
# all entries are still in progress
end
```
| programming_docs |
phoenix DOM patching & temporary assigns DOM patching & temporary assigns
=================================
A container can be marked with `phx-update`, allowing the DOM patch operations to avoid updating or removing portions of the LiveView, or to append or prepend the updates rather than replacing the existing contents. This is useful for client-side interop with existing libraries that do their own DOM operations. The following `phx-update` values are supported:
* `replace` - the default operation. Replaces the element with the contents
* `ignore` - ignores updates to the DOM regardless of new content changes
* `append` - append the new DOM contents instead of replacing
* `prepend` - prepend the new DOM contents instead of replacing
When using `phx-update`, a unique DOM ID must always be set in the container. If using "append" or "prepend", a DOM ID must also be set for each child. When appending or prepending elements containing an ID already present in the container, LiveView will replace the existing element with the new content instead appending or prepending a new element.
The "ignore" behaviour is frequently used when you need to integrate with another JS library. Note only the element contents are ignored, its attributes can still be updated.
The "append" and "prepend" feature is often used with "Temporary assigns" to work with large amounts of data. Let's learn more.
To react to elements being removed from the DOM, the `phx-remove` binding may be specified, which can contain a [`Phoenix.LiveView.JS`](phoenix.liveview.js) command to execute.
*Note*: The `phx-remove` command is only executed for the removed parent element. It does not cascade to children.
Temporary assigns
------------------
By default, all LiveView assigns are stateful, which enables change tracking and stateful interactions. In some cases, it's useful to mark assigns as temporary, meaning they will be reset to a default value after each update. This allows otherwise large but infrequently updated values to be discarded after the client has been patched.
Imagine you want to implement a chat application with LiveView. You could render each message like this:
```
<%= for message <- @messages do %>
<p><span><%= message.username %>:</span> <%= message.text %></p>
<% end %>
```
Every time there is a new message, you would append it to the `@messages` assign and re-render all messages.
As you may suspect, keeping the whole chat conversation in memory and resending it on every update would be too expensive, even with LiveView smart change tracking. By using temporary assigns and phx-update, we don't need to keep any messages in memory, and send messages to be appended to the UI only when there are new ones.
To do so, the first step is to mark which assigns are temporary and what values they should be reset to on mount:
```
def mount(_params, _session, socket) do
socket = assign(socket, :messages, load_last_20_messages())
{:ok, socket, temporary_assigns: [messages: []]}
end
```
On mount we also load the initial number of messages we want to send. After the initial render, the initial batch of messages will be reset back to an empty list.
Now, whenever there are one or more new messages, we will assign only the new messages to `@messages`:
```
socket = assign(socket, :messages, new_messages)
```
In the template, we want to wrap all of the messages in a container and tag this content with `phx-update`. Remember, we must add an ID to the container as well as to each child:
```
<div id="chat-messages" phx-update="append">
<%= for message <- @messages do %>
<p id={message.id}>
<span><%= message.username %>:</span> <%= message.text %>
</p>
<% end %>
</div>
```
When the client receives new messages, it now knows to append to the old content rather than replace it.
You can also update the direction of messages. Suppose there is an edit to a message that is being sent to your LiveView like this:
```
def handle_info({:update_message, message}, socket) do
{:noreply, update(socket, :messages, fn messages -> [message | messages] end)}
end
```
You can add it to the list like you do with new messages. LiveView is aware that this message was rendered on the client, even though the message itself is discarded on the server after it is rendered.
LiveView uses DOM ids to check if a message is rendered before or not. If an id is rendered before, the DOM element is updated rather than appending or prepending a new node. Also, the order of elements is not changed. You can use it to show edited messages, show likes, or anything that would require an update to a rendered message.
[← Previous Page Form bindings](form-bindings) [Next Page → JavaScript interoperability](https://hexdocs.pm/phoenix_live_view/js-interop.html)
phoenix Phoenix.LiveView.Socket Phoenix.LiveView.Socket
========================
The LiveView socket for Phoenix Endpoints.
This is typically mounted directly in your endpoint.
```
socket "/live", Phoenix.LiveView.Socket
```
Summary
========
Types
------
[assigns()](#t:assigns/0) The data in a LiveView as stored in the socket.
[assigns\_not\_in\_socket()](#t:assigns_not_in_socket/0) Struct returned when `assigns` is not in the socket.
[fingerprints()](#t:fingerprints/0) [t()](#t:t/0) Types
======
### assigns()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/socket.ex#L58)
```
@type assigns() :: map() | assigns_not_in_socket()
```
The data in a LiveView as stored in the socket.
### assigns\_not\_in\_socket()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/socket.ex#L55)
```
@opaque assigns_not_in_socket()
```
Struct returned when `assigns` is not in the socket.
### fingerprints()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/socket.ex#L60)
```
@type fingerprints() :: {nil, map()} | {binary(), map()}
```
### t()[Source](https://github.com/phoenixframework/phoenix_live_view/blob/v0.17.11/lib/phoenix_live_view/socket.ex#L62)
```
@type t() :: %Phoenix.LiveView.Socket{
assigns: assigns(),
endpoint: module(),
fingerprints: fingerprints(),
host_uri: URI.t() | :not_mounted_at_router,
id: binary(),
parent_pid: nil | pid(),
private: map(),
redirected: nil | tuple(),
root_pid: pid(),
router: module(),
transport_pid: pid() | nil,
view: module()
}
```
phoenix Phoenix.LiveViewTest.View Phoenix.LiveViewTest.View
==========================
The struct for testing LiveViews.
The following public fields represent the LiveView:
* `id` - The DOM id of the LiveView
* `module` - The module of the running LiveView
* `pid` - The Pid of the running LiveView
* `endpoint` - The endpoint for the LiveView
* `target` - The target to scope events to
See the [`Phoenix.LiveViewTest`](phoenix.liveviewtest) documentation for usage.
phoenix Installation Installation
=============
New projects
-------------
Phoenix v1.5+ comes with built-in support for LiveView apps. Just create your application with `mix phx.new my_app --live`. The `--live` flag has become the default on Phoenix v1.6.
Once you've created a LiveView project, refer to [LiveView documentation](phoenix.liveview) for further information on how to use it.
Existing projects
------------------
If you are using a Phoenix version earlier than v1.5 or your app already exists, continue with the following steps.
The instructions below will serve if you are installing the latest stable version from Hex. To start using LiveView, add one of the following dependencies to your `mix.exs` and run [`mix deps.get`](https://hexdocs.pm/mix/Mix.Tasks.Deps.Get.html).
If installing from Hex, use the latest version from there:
```
def deps do
[
{:phoenix_live_view, "~> 0.17.11"},
{:floki, ">= 0.30.0", only: :test}
]
end
```
If you want the latest features, install from GitHub:
```
def deps do
[
{:phoenix_live_view, github: "phoenixframework/phoenix_live_view"},
{:floki, ">= 0.30.0", only: :test}
]
```
Once installed, update your endpoint's configuration to include a signing salt. You can generate a signing salt by running `mix phx.gen.secret 32`:
```
# config/config.exs
config :my_app, MyAppWeb.Endpoint,
live_view: [signing_salt: "SECRET_SALT"]
```
Next, add the following imports to your web file in `lib/my_app_web.ex`:
```
# lib/my_app_web.ex
def view do
quote do
...
import Phoenix.LiveView.Helpers
end
end
def router do
quote do
...
import Phoenix.LiveView.Router
end
end
```
Then add the [`Phoenix.LiveView.Router.fetch_live_flash/2`](phoenix.liveview.router#fetch_live_flash/2) plug to your browser pipeline, in place of `:fetch_flash`:
```
# lib/my_app_web/router.ex
pipeline :browser do
...
plug :fetch_session
- plug :fetch_flash
+ plug :fetch_live_flash
end
```
Next, expose a new socket for LiveView updates in your app's endpoint module.
```
# lib/my_app_web/endpoint.ex
defmodule MyAppWeb.Endpoint do
use Phoenix.Endpoint
# ...
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]]
# ...
end
```
Where `@session_options` are the options given to `plug Plug.Session` by using a module attribute. If you don't have a `@session_options` in your endpoint yet, here is how to create one:
1. Find plug Plug.Session in your endpoint.ex
```
plug Plug.Session
store: :cookie,
key: "_my_app_key",
signing_salt: "somesigningsalt"
```
2. Move the options to a module attribute at the top of your file:
```
@session_options [
store: :cookie,
key: "_my_app_key",
signing_salt: "somesigningsalt"
]
```
3. Change the plug Plug.Session to use that attribute:
```
plug Plug.Session, @session_options
```
Finally, ensure you have placed a CSRF meta tag inside the `<head>` tag in your layout (`lib/my_app_web/templates/layout/app.html.*`) before `app.js` is included, like so:
```
<%= csrf_meta_tag() %>
<script defer type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
```
and enable connecting to a LiveView socket in your `app.js` file.
```
// assets/js/app.js
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
// Connect if there are any LiveViews on the page
liveSocket.connect()
// Expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000)
// The latency simulator is enabled for the duration of the browser session.
// Call disableLatencySim() to disable:
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket
```
The JavaScript above expects `phoenix_live_view` to be available as a JavaScript dependency. Let's do that.
npm dependencies
-----------------
If using `npm`, you need to add LiveView to your `assets/package.json`. For a regular project, do:
```
{
"dependencies": {
"phoenix": "file:../deps/phoenix",
"phoenix_html": "file:../deps/phoenix_html",
"phoenix_live_view": "file:../deps/phoenix_live_view"
}
}
```
However, if you're adding `phoenix_live_view` to an umbrella project, the dependency paths should be modified appropriately:
```
{
"dependencies": {
"phoenix": "file:../../../deps/phoenix",
"phoenix_html": "file:../../../deps/phoenix_html",
"phoenix_live_view": "file:../../../deps/phoenix_live_view"
}
}
```
Now run the next commands from your web app root:
```
npm install --prefix assets
```
If you had previously installed `phoenix_live_view` and want to get the latest javascript, then force an install with:
```
npm install --force phoenix_live_view --prefix assets
```
Layouts
--------
LiveView does not use the default app layout. Instead, you typically call `put_root_layout` in your router to specify a layout that is used by both "regular" views and live views. In your router, do:
```
pipeline :browser do
...
plug :put_root_layout, {MyAppWeb.LayoutView, :root}
...
end
```
The layout given to `put_root_layout` is typically very barebones, with mostly `<head>` and `<body>` tags. For example:
```
<!DOCTYPE html>
<html lang="en">
<head>
<%= csrf_meta_tag() %>
<%= live_title_tag assigns[:page_title] || "MyApp" %>
<link rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/>
<script defer type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
</head>
<body>
<%= @inner_content %>
</body>
</html>
```
Once you have specified a root layout, "app.html.heex" will be rendered within your root layout for all non-LiveViews. You may also optionally define a "live.html.heex" layout to be used across all LiveViews, as we will describe in the next section.
Optionally, you can add a [`phx-track-static`](phoenix.liveview#static_changed?/1) to all `script` and `link` elements in your layout that use `src` and `href`. This way you can detect when new assets have been deployed by calling `static_changed?`.
```
<link phx-track-static rel="stylesheet" href={Routes.static_path(@conn, "/css/app.css")} />
<script phx-track-static defer type="text/javascript" src={Routes.static_path(@conn, "/js/app.js")}></script>
```
phx.gen.live support
---------------------
While the above instructions are enough to install LiveView in a Phoenix app, if you want to use the `phx.gen.live` generators that come as part of Phoenix v1.5, you need to do one more change, as those generators assume your application was created with `mix phx.new --live`.
The change is to define the `live_view` and `live_component` functions in your `my_app_web.ex` file, while refactoring the `view` function. At the end, they will look like this:
```
def view do
quote do
use Phoenix.View,
root: "lib/<%= lib_web_name %>/templates",
namespace: MyAppWeb
# Import convenience functions from controllers
import Phoenix.Controller,
only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1]
# Include shared imports and aliases for views
unquote(view_helpers())
end
end
def live_view do
quote do
use Phoenix.LiveView,
layout: {MyAppWeb.LayoutView, "live.html"}
unquote(view_helpers())
end
end
def live_component do
quote do
use Phoenix.LiveComponent
unquote(view_helpers())
end
end
defp view_helpers do
quote do
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
# Import LiveView helpers (live_render, live_component, live_patch, etc)
import Phoenix.LiveView.Helpers
# Import basic rendering functionality (render, render_layout, etc)
import Phoenix.View
import MyAppWeb.ErrorHelpers
import MyAppWeb.Gettext
alias MyAppWeb.Router.Helpers, as: Routes
end
end
```
Note that LiveViews are automatically configured to use a "live.html.heex" layout in this line:
```
use Phoenix.LiveView,
layout: {MyAppWeb.LayoutView, "live.html"}
```
"layouts/root.html.heex" is shared by regular and live views, "app.html.heex" is rendered inside the root layout for regular views, and "live.html.heex" is rendered inside the root layout for LiveViews. "live.html.heex" typically starts out as a copy of "app.html.heex", but using the `@socket` assign instead of `@conn`. Check the [Live Layouts](live-layouts) guide for more information.
Progress animation
-------------------
If you want to show a progress bar as users perform live actions, we recommend using [`topbar`](https://github.com/buunguyen/topbar).
You can either add a copy of `topbar` to `assets/vendor/topbar.js` or add it as a npm dependency by calling:
```
$ npm install --prefix assets --save topbar
```
Then customize LiveView to use it in your `assets/js/app.js`, right before the `liveSocket.connect()` call:
```
// Show progress bar on live navigation and form submits
import topbar from "topbar"
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", info => topbar.show())
window.addEventListener("phx:page-loading-stop", info => topbar.hide())
```
Alternatively, you can also delay showing the `topbar` and wait if the results do not appear within 200ms:
```
// Show progress bar on live navigation and form submits
import topbar from "topbar"
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
let topBarScheduled = undefined
window.addEventListener("phx:page-loading-start", () => {
if(!topBarScheduled) {
topBarScheduled = setTimeout(() => topbar.show(), 200)
}
})
window.addEventListener("phx:page-loading-stop", () => {
clearTimeout(topBarScheduled)
topBarScheduled = undefined
topbar.hide()
})
```
Location for LiveView modules
------------------------------
By convention your LiveView modules and `heex` templates should be placed in `lib/my_app_web/live/` directory.
[← Previous Page Changelog](changelog) [Next Page → Assigns and HEEx templates](assigns-eex)
phoenix Bindings Bindings
=========
Phoenix supports DOM element bindings for client-server interaction. For example, to react to a click on a button, you would render the element:
```
<button phx-click="inc_temperature">+</button>
```
Then on the server, all LiveView bindings are handled with the `handle_event` callback, for example:
```
def handle_event("inc_temperature", _value, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
```
| Binding | Attributes |
| --- | --- |
| [Params](#click-events) | `phx-value-*` |
| [Click Events](#click-events) | `phx-click`, `phx-click-away` |
| [Form Events](form-bindings) | `phx-change`, `phx-submit`, `phx-feedback-for`, `phx-disable-with`, `phx-trigger-action`, `phx-auto-recover` |
| [Focus Events](#focus-and-blur-events) | `phx-blur`, `phx-focus`, `phx-window-blur`, `phx-window-focus` |
| [Key Events](#key-events) | `phx-keydown`, `phx-keyup`, `phx-window-keydown`, `phx-window-keyup`, `phx-key` |
| [DOM Patching](dom-patching) | `phx-update`, `phx-remove` |
| [JS Interop](https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks) | `phx-hook` |
| [Rate Limiting](#rate-limiting-events-with-debounce-and-throttle) | `phx-debounce`, `phx-throttle` |
| [Static tracking](phoenix.liveview#static_changed?/1) | `phx-track-static` |
Click Events
-------------
The `phx-click` binding is used to send click events to the server. When any client event, such as a `phx-click` click is pushed, the value sent to the server will be chosen with the following priority:
* The `:value` specified in [`Phoenix.LiveView.JS.push/3`](phoenix.liveview.js#push/3), such as:
```
<div phx-click={JS.push("inc", value: %{myvar1: @val1})}>
```
* Any number of optional `phx-value-` prefixed attributes, such as:
```
<div phx-click="inc" phx-value-myvar1="val1" phx-value-myvar2="val2">
```
will send the following map of params to the server:
```
def handle_event("inc", %{"myvar1" => "val1", "myvar2" => "val2"}, socket) do
```
If the `phx-value-` prefix is used, the server payload will also contain a `"value"` if the element's value attribute exists.
* The payload will also include any additional user defined metadata of the client event. For example, the following `LiveSocket` client option would send the coordinates and `altKey` information for all clicks:
```
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
metadata: {
click: (e, el) => {
return {
altKey: e.altKey,
clientX: e.clientX,
clientY: e.clientY
}
}
}
})
```
The `phx-click-away` event is fired when a click event happens outside of the element. This is useful for hiding toggled containers like drop-downs.
Focus and Blur Events
----------------------
Focus and blur events may be bound to DOM elements that emit such events, using the `phx-blur`, and `phx-focus` bindings, for example:
```
<input name="email" phx-focus="myfocus" phx-blur="myblur"/>
```
To detect when the page itself has received focus or blur, `phx-window-focus` and `phx-window-blur` may be specified. These window level events may also be necessary if the element in consideration (most often a `div` with no tabindex) cannot receive focus. Like other bindings, `phx-value-*` can be provided on the bound element, and those values will be sent as part of the payload. For example:
```
<div class="container"
phx-window-focus="page-active"
phx-window-blur="page-inactive"
phx-value-page="123">
...
</div>
```
Key Events
-----------
The `onkeydown`, and `onkeyup` events are supported via the `phx-keydown`, and `phx-keyup` bindings. Each binding supports a `phx-key` attribute, which triggers the event for the specific key press. If no `phx-key` is provided, the event is triggered for any key press. When pushed, the value sent to the server will contain the `"key"` that was pressed, plus any user-defined metadata. For example, pressing the Escape key looks like this:
```
%{"key" => "Escape"}
```
To capture additional user-defined metadata, the `metadata` option for keydown events may be provided to the `LiveSocket` constructor. For example:
```
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
metadata: {
keydown: (e, el) => {
return {
key: e.key,
metaKey: e.metaKey,
repeat: e.repeat
}
}
}
})
```
To determine which key has been pressed you should use `key` value. The available options can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) or via the [Key Event Viewer](https://w3c.github.io/uievents/tools/key-event-viewer.html).
*Note*: it is possible for certain browser features like autofill to trigger key events with no `"key"` field present in the value map sent to the server. For this reason, we recommend always having a fallback catch-all event handler for LiveView key bindings. By default, the bound element will be the event listener, but a window-level binding may be provided via `phx-window-keydown` or `phx-window-keyup`, for example:
```
def render(assigns) do
~H"""
<div id="thermostat" phx-window-keyup="update_temp">
Current temperature: <%= @temperature %>
</div>
"""
end
def handle_event("update_temp", %{"key" => "ArrowUp"}, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", %{"key" => "ArrowDown"}, socket) do
{:ok, new_temp} = Thermostat.dec_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", _, socket) do
{:noreply, socket}
end
```
Rate limiting events with Debounce and Throttle
------------------------------------------------
All events can be rate-limited on the client by using the `phx-debounce` and `phx-throttle` bindings, with the exception of the `phx-blur` binding, which is fired immediately.
Rate limited and debounced events have the following behavior:
* `phx-debounce` - Accepts either an integer timeout value (in milliseconds), or `"blur"`. When an integer is provided, emitting the event is delayed by the specified milliseconds. When `"blur"` is provided, emitting the event is delayed until the field is blurred by the user. Debouncing is typically used for input elements.
* `phx-throttle` - Accepts an integer timeout value to throttle the event in milliseconds. Unlike debounce, throttle will immediately emit the event, then rate limit it at once per provided timeout. Throttling is typically used to rate limit clicks, mouse and keyboard actions.
For example, to avoid validating an email until the field is blurred, while validating the username at most every 2 seconds after a user changes the field:
```
<form phx-change="validate" phx-submit="save">
<input type="text" name="user[email]" phx-debounce="blur"/>
<input type="text" name="user[username]" phx-debounce="2000"/>
</form>
```
And to rate limit a volume up click to once every second:
```
<button phx-click="volume_up" phx-throttle="1000">+</button>
```
Likewise, you may throttle held-down keydown:
```
<div phx-window-keydown="keydown" phx-throttle="500">
...
</div>
```
Unless held-down keys are required, a better approach is generally to use `phx-keyup` bindings which only trigger on key up, thereby being self-limiting. However, `phx-keydown` is useful for games and other use cases where a constant press on a key is desired. In such cases, throttle should always be used.
### Debounce and Throttle special behavior
The following specialized behavior is performed for forms and keydown bindings:
* When a `phx-submit`, or a `phx-change` for a different input is triggered, any current debounce or throttle timers are reset for existing inputs.
* A `phx-keydown` binding is only throttled for key repeats. Unique keypresses back-to-back will dispatch the pressed key events.
JS Commands
------------
LiveView bindings support a JavaScript command interface via the [`Phoenix.LiveView.JS`](phoenix.liveview.js) module, which allows you to specify utility operations that execute on the client when firing `phx-` binding events, such as `phx-click`, `phx-change`, etc. Commands compose together to allow you to push events, add classes to elements, transition elements in and out, and more. See the [`Phoenix.LiveView.JS`](phoenix.liveview.js) documentation for full usage.
For a small example of what's possible, imagine you want to show and hide a modal on the page without needing to make the round trip to the server to render the content:
```
<div id="modal" class="modal">
My Modal
</div>
<button phx-click={JS.show(to: "#modal", transition: "fade-in")}>
show modal
</button>
<button phx-click={JS.hide(to: "#modal", transition: "fade-out")}>
hide modal
</button>
<button phx-click={JS.toggle(to: "#modal", in: "fade-in", out: "fade-out")}>
toggle modal
</button>
```
Or if your UI library relies on classes to perform the showing or hiding:
```
<div id="modal" class="modal">
My Modal
</div>
<button phx-click={JS.add_class("show", to: "#modal", transition: "fade-in")}>
show modal
</button>
<button phx-click={JS.remove_class("show", to: "#modal", transition: "fade-out")}>
hide modal
</button>
```
Commands compose together. For example, you can push an event to the server and immediately hide the modal on the client:
```
<div id="modal" class="modal">
My Modal
</div>
<button phx-click={JS.push("modal-closed") |> JS.remove_class("show", to: "#modal", transition: "fade-out")}>
hide modal
</button>
```
It is also useful to extract commands into their own functions:
```
alias Phoenix.LiveView.JS
def hide_modal(js \\ %JS{}, selector) do
js
|> JS.push("modal-closed")
|> JS.remove_class("show", to: selector, transition: "fade-out")
end
```
```
<button phx-click={hide_modal("#modal")}>hide modal</button>
```
The [`Phoenix.LiveView.JS.push/3`](phoenix.liveview.js#push/3) command is particularly powerful in allowing you to customize the event being pushed to the server. For example, imagine you start with a familiar `phx-click` which pushes a message to the server when clicked:
```
<button phx-click="clicked">click</button>
```
Now imagine you want to customize what happens when the `"clicked"` event is pushed, such as which component should be targeted, which element should receive css loading state classes, etc. This can be accomplished with options on the JS push command. For example:
```
<button phx-click={JS.push("clicked", target: @myself, loading: ".container")}>click</button>
```
See [`Phoenix.LiveView.JS.push/3`](phoenix.liveview.js#push/3) for all supported options.
LiveView Specific Events
-------------------------
The `lv:` event prefix supports LiveView specific features that are handled by LiveView without calling the user's `handle_event/3` callbacks. Today, the following events are supported:
* `lv:clear-flash` – clears the flash when sent to the server. If a `phx-value-key` is provided, the specific key will be removed from the flash.
For example:
```
<p class="alert" phx-click="lv:clear-flash" phx-value-key="info">
<%= live_flash(@flash, :info) %>
</p>
```
Loading states and errors
--------------------------
All `phx-` event bindings apply their own css classes when pushed. For example the following markup:
```
<button phx-click="clicked" phx-window-keydown="key">...</button>
```
On click, would receive the `phx-click-loading` class, and on keydown would receive the `phx-keydown-loading` class. The css loading classes are maintained until an acknowledgement is received on the client for the pushed event.
In the case of forms, when a `phx-change` is sent to the server, the input element which emitted the change receives the `phx-change-loading` class, along with the parent form tag. The following events receive css loading classes:
* `phx-click` - `phx-click-loading`
* `phx-change` - `phx-change-loading`
* `phx-submit` - `phx-submit-loading`
* `phx-focus` - `phx-focus-loading`
* `phx-blur` - `phx-blur-loading`
* `phx-window-keydown` - `phx-keydown-loading`
* `phx-window-keyup` - `phx-keyup-loading`
Additionally, the following classes are applied to the LiveView's parent container:
* `"phx-connected"` - applied when the view has connected to the server
* `"phx-loading"` - applied when the view is not connected to the server
* `"phx-error"` - applied when an error occurs on the server. Note, this class will be applied in conjunction with `"phx-loading"` if connection to the server is lost.
[← Previous Page Using Gettext for internationalization](using-gettext) [Next Page → Form bindings](form-bindings)
| programming_docs |
phoenix Phoenix.LiveView.Engine Phoenix.LiveView.Engine
========================
An [`EEx`](https://hexdocs.pm/eex/EEx.html) template engine that tracks changes.
This is often used by [`Phoenix.LiveView.HTMLEngine`](phoenix.liveview.htmlengine) which also adds HTML validation. In the documentation below, we will explain how it works internally. For user-facing documentation, see [`Phoenix.LiveView`](phoenix.liveview).
Phoenix.LiveView.Rendered
--------------------------
Whenever you render a live template, it returns a [`Phoenix.LiveView.Rendered`](phoenix.liveview.rendered) structure. This structure has three fields: `:static`, `:dynamic` and `:fingerprint`.
The `:static` field is a list of literal strings. This allows the Elixir compiler to optimize this list and avoid allocating its strings on every render.
The `:dynamic` field contains a function that takes a boolean argument (see "Tracking changes" below), and returns a list of dynamic content. Each element in the list is either one of:
1. iodata - which is the dynamic content
2. nil - the dynamic content did not change
3. another [`Phoenix.LiveView.Rendered`](phoenix.liveview.rendered) struct, see "Nesting and fingerprinting" below
4. a [`Phoenix.LiveView.Comprehension`](phoenix.liveview.comprehension) struct, see "Comprehensions" below
5. a [`Phoenix.LiveView.Component`](phoenix.liveview.component) struct, see "Component" below
When you render a live template, you can convert the rendered structure to iodata by alternating the static and dynamic fields, always starting with a static entry followed by a dynamic entry. The last entry will always be static too. So the following structure:
```
%Phoenix.LiveView.Rendered{
static: ["foo", "bar", "baz"],
dynamic: fn track_changes? -> ["left", "right"] end
}
```
Results in the following content to be sent over the wire as iodata:
```
["foo", "left", "bar", "right", "baz"]
```
This is also what calling [`Phoenix.HTML.Safe.to_iodata/1`](https://hexdocs.pm/phoenix_html/3.2.0/Phoenix.HTML.Safe.html#to_iodata/1) with a [`Phoenix.LiveView.Rendered`](phoenix.liveview.rendered) structure returns.
Of course, the benefit of live templates is exactly that you do not need to send both static and dynamic segments every time. So let's talk about tracking changes.
Tracking changes
-----------------
By default, a live template does not track changes. Change tracking can be enabled by including a changed map in the assigns with the key `__changed__` and passing `true` to the dynamic parts. The map should contain the name of any changed field as key and the boolean true as value. If a field is not listed in `__changed__`, then it is always considered unchanged.
If a field is unchanged and live believes a dynamic expression no longer needs to be computed, its value in the `dynamic` list will be `nil`. This information can be leveraged to avoid sending data to the client.
Nesting and fingerprinting
---------------------------
[`Phoenix.LiveView`](phoenix.liveview) also tracks changes across live templates. Therefore, if your view has this:
```
<%= render "form.html", assigns %>
```
Phoenix will be able to track what is static and dynamic across templates, as well as what changed. A rendered nested `live` template will appear in the `dynamic` list as another [`Phoenix.LiveView.Rendered`](phoenix.liveview.rendered) structure, which must be handled recursively.
However, because the rendering of live templates can be dynamic in itself, it is important to distinguish which live template was rendered. For example, imagine this code:
```
<%= if something?, do: render("one.html", assigns), else: render("other.html", assigns) %>
```
To solve this, all [`Phoenix.LiveView.Rendered`](phoenix.liveview.rendered) structs also contain a fingerprint field that uniquely identifies it. If the fingerprints are equal, you have the same template, and therefore it is possible to only transmit its changes.
Comprehensions
---------------
Another optimization done by live templates is to track comprehensions. If your code has this:
```
<%= for point <- @points do %>
x: <%= point.x %>
y: <%= point.y %>
<% end %>
```
Instead of rendering all points with both static and dynamic parts, it returns a [`Phoenix.LiveView.Comprehension`](phoenix.liveview.comprehension) struct with the static parts, that are shared across all points, and a list of dynamics to be interpolated inside the static parts. If `@points` is a list with `%{x: 1, y: 2}` and `%{x: 3, y: 4}`, the above expression would return:
```
%Phoenix.LiveView.Comprehension{
static: ["\n x: ", "\n y: ", "\n"],
dynamics: [
["1", "2"],
["3", "4"]
]
}
```
This allows live templates to drastically optimize the data sent by comprehensions, as the static parts are emitted only once, regardless of the number of items.
The list of dynamics is always a list of iodatas or components, as we don't perform change tracking inside the comprehensions themselves. Similarly, comprehensions do not have fingerprints because they are only optimized at the root, so conditional evaluation, as the one seen in rendering, is not possible. The only possible outcome for a dynamic field that returns a comprehension is `nil`.
Components
-----------
Live also supports stateful components defined with [`Phoenix.LiveComponent`](phoenix.livecomponent). Since they are stateful, they are always handled lazily by the diff algorithm.
phoenix Phoenix.LiveView.HTMLEngine Phoenix.LiveView.HTMLEngine
============================
The HTMLEngine that powers `.heex` templates and the `~H` sigil.
It works by adding a HTML parsing and validation layer on top of EEx engine. By default it uses [`Phoenix.LiveView.Engine`](phoenix.liveview.engine) as its "subengine".
html HTML attribute reference HTML attribute reference
========================
Elements in HTML have **attributes**; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want.
Attribute list
--------------
| Attribute Name | Elements | Description |
| --- | --- | --- |
| `[accept](attributes/accept)` | [`<form>`](element/form), [`<input>`](element/input) | List of types the server accepts, typically a file type. |
| `[accept-charset](element/form#attr-accept-charset)` | [`<form>`](element/form) | List of supported charsets. |
| `[accesskey](global_attributes/accesskey)` | [Global attribute](global_attributes) | Keyboard shortcut to activate or add focus to the element. |
| `[action](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/action)` | [`<form>`](element/form) | The URI of a program that processes the information submitted via the form. |
| `[align](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/align)` | [`<applet>`](element/applet), [`<caption>`](element/caption), [`<col>`](element/col), [`<colgroup>`](element/colgroup), [`<hr>`](element/hr), [`<iframe>`](element/iframe), [`<img>`](element/img), [`<table>`](element/table), [`<tbody>`](element/tbody), [`<td>`](element/td), [`<tfoot>`](element/tfoot), [`<th>`](element/th), [`<thead>`](element/thead), [`<tr>`](element/tr) | Specifies the horizontal alignment of the element. |
| `[allow](element/iframe#attr-allow)` | [`<iframe>`](element/iframe) | Specifies a feature-policy for the iframe. |
| `[alt](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/alt)` | [`<applet>`](element/applet), [`<area>`](element/area), [`<img>`](element/img), [`<input>`](element/input) | Alternative text in case an image can't be displayed. |
| `[async](element/script#attr-async)` | [`<script>`](element/script) | Executes the script asynchronously. |
| `[autocapitalize](global_attributes/autocapitalize)` | [Global attribute](global_attributes) | Sets whether input is automatically capitalized when entered by user |
| `[autocomplete](attributes/autocomplete)` | [`<form>`](element/form), [`<input>`](element/input), [`<select>`](element/select), [`<textarea>`](element/textarea) | Indicates whether controls in this form can by default have their values automatically completed by the browser. |
| `[autofocus](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autofocus)` | [`<button>`](element/button), [`<input>`](element/input), [`<keygen>`](element/keygen), [`<select>`](element/select), [`<textarea>`](element/textarea) | The element should be automatically focused after the page loaded. |
| `[autoplay](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autoplay)` | [`<audio>`](element/audio), [`<video>`](element/video) | The audio or video should play as soon as possible. |
| `background` | [`<body>`](element/body), [`<table>`](element/table), [`<td>`](element/td), [`<th>`](element/th) | Specifies the URL of an image file. **Note:** Although browsers and email clients may still support this attribute, it is obsolete. Use CSS [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image) instead. |
| `bgcolor` | [`<body>`](element/body), [`<col>`](element/col), [`<colgroup>`](element/colgroup), [`<marquee>`](element/marquee), [`<table>`](element/table), [`<tbody>`](element/tbody), [`<tfoot>`](element/tfoot), [`<td>`](element/td), [`<th>`](element/th), [`<tr>`](element/tr) | Background color of the element. **Note:** This is a legacy attribute. Please use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property instead. |
| `border` | [`<img>`](element/img), [`<object>`](element/object), [`<table>`](element/table) | The border width. **Note:** This is a legacy attribute. Please use the CSS [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) property instead. |
| `[buffered](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/buffered)` | [`<audio>`](element/audio), [`<video>`](element/video) | Contains the time range of already buffered media. |
| `[capture](attributes/capture)` | [`<input>`](element/input) | From the [Media Capture specification](https://w3c.github.io/html-media-capture/#the-capture-attribute), specifies a new file can be captured. |
| `[challenge](element/keygen#attr-challenge)` | [`<keygen>`](element/keygen) | A challenge string that is submitted along with the public key. |
| `[charset](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/charset)` | [`<meta>`](element/meta), [`<script>`](element/script) | Declares the character encoding of the page or script. |
| `[checked](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/checked)` | `<command>`, [`<input>`](element/input) | Indicates whether the element should be checked on page load. |
| `[cite](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/cite)` | [`<blockquote>`](element/blockquote), [`<del>`](element/del), [`<ins>`](element/ins), [`<q>`](element/q) | Contains a URI which points to the source of the quote or change. |
| `[class](global_attributes/class)` | [Global attribute](global_attributes) | Often used with CSS to style elements with common properties. |
| `[code](element/applet#attr-code)` | [`<applet>`](element/applet) | Specifies the URL of the applet's class file to be loaded and executed. |
| `[codebase](element/applet#attr-codebase)` | [`<applet>`](element/applet) | This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored. |
| `color` | [`<font>`](element/font), [`<hr>`](element/hr) | This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. **Note:** This is a legacy attribute. Please use the CSS [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) property instead. |
| `[cols](element/textarea#attr-cols)` | [`<textarea>`](element/textarea) | Defines the number of columns in a textarea. |
| `[colspan](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/colspan)` | [`<td>`](element/td), [`<th>`](element/th) | The colspan attribute defines the number of columns a cell should span. |
| `[content](element/meta#attr-content)` | [`<meta>`](element/meta) | A value associated with `http-equiv` or `name` depending on the context. |
| `[contenteditable](global_attributes/contenteditable)` | [Global attribute](global_attributes) | Indicates whether the element's content is editable. |
| `[contextmenu](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/contextmenu)` | [Global attribute](global_attributes) | Defines the ID of a [`<menu>`](element/menu) element which will serve as the element's context menu. |
| `[controls](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/controls)` | [`<audio>`](element/audio), [`<video>`](element/video) | Indicates whether the browser should show playback controls to the user. |
| `[coords](element/area#attr-coords)` | [`<area>`](element/area) | A set of values specifying the coordinates of the hot-spot region. |
| `[crossorigin](attributes/crossorigin)` | [`<audio>`](element/audio), [`<img>`](element/img), [`<link>`](element/link), [`<script>`](element/script), [`<video>`](element/video) | How the element handles cross-origin requests |
| `[csp](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/csp)` Experimental | [`<iframe>`](element/iframe) | Specifies the Content Security Policy that an embedded document must agree to enforce upon itself. |
| `[data](element/object#attr-data)` | [`<object>`](element/object) | Specifies the URL of the resource. |
| `[data-\*](global_attributes/data-*)` | [Global attribute](global_attributes) | Lets you attach custom attributes to an HTML element. |
| `[datetime](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/datetime)` | [`<del>`](element/del), [`<ins>`](element/ins), [`<time>`](element/time) | Indicates the date and time associated with the element. |
| `[decoding](element/img#attr-decoding)` | [`<img>`](element/img) | Indicates the preferred method to decode the image. |
| `[default](element/track#attr-default)` | [`<track>`](element/track) | Indicates that the track should be enabled unless the user's preferences indicate something different. |
| `[defer](element/script#attr-defer)` | [`<script>`](element/script) | Indicates that the script should be executed after the page has been parsed. |
| `[dir](global_attributes/dir)` | [Global attribute](global_attributes) | Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left) |
| `[dirname](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/dirname)` | [`<input>`](element/input), [`<textarea>`](element/textarea) | |
| `[disabled](attributes/disabled)` | [`<button>`](element/button), `<command>`, [`<fieldset>`](element/fieldset), [`<input>`](element/input), [`<keygen>`](element/keygen), [`<optgroup>`](element/optgroup), [`<option>`](element/option), [`<select>`](element/select), [`<textarea>`](element/textarea) | Indicates whether the user can interact with the element. |
| `[download](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/download)` | [`<a>`](element/a), [`<area>`](element/area) | Indicates that the hyperlink is to be used for downloading a resource. |
| `[draggable](global_attributes/draggable)` | [Global attribute](global_attributes) | Defines whether the element can be dragged. |
| `[enctype](element/form#attr-enctype)` | [`<form>`](element/form) | Defines the content type of the form data when the `method` is POST. |
| `[enterkeyhint](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/enterkeyhint)` Experimental | [`<textarea>`](element/textarea), [`contenteditable`](global_attributes/contenteditable) | The [`enterkeyhint`](https://html.spec.whatwg.org/dev/interaction.html#input-modalities:-the-enterkeyhint-attribute) specifies what action label (or icon) to present for the enter key on virtual keyboards. The attribute can be used with form controls (such as the value of `textarea` elements), or in elements in an editing host (e.g., using `contenteditable` attribute). |
| `[for](attributes/for)` | [`<label>`](element/label), [`<output>`](element/output) | Describes elements which belongs to this one. |
| `[form](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/form)` | [`<button>`](element/button), [`<fieldset>`](element/fieldset), [`<input>`](element/input), [`<keygen>`](element/keygen), [`<label>`](element/label), [`<meter>`](element/meter), [`<object>`](element/object), [`<output>`](element/output), [`<progress>`](element/progress), [`<select>`](element/select), [`<textarea>`](element/textarea) | Indicates the form that is the owner of the element. |
| `[formaction](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/formaction)` | [`<input>`](element/input), [`<button>`](element/button) | Indicates the action of the element, overriding the action defined in the [`<form>`](element/form). |
| `[formenctype](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/formenctype)` | [`<button>`](element/button), [`<input>`](element/input) | If the button/input is a submit button (`type="submit"`), this attribute sets the encoding type to use during form submission. If this attribute is specified, it overrides the `enctype` attribute of the button's [form](element/form) owner. |
| `[formmethod](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/formmethod)` | [`<button>`](element/button), [`<input>`](element/input) | If the button/input is a submit button (`type="submit"`), this attribute sets the submission method to use during form submission (`GET`, `POST`, etc.). If this attribute is specified, it overrides the `method` attribute of the button's [form](element/form) owner. |
| `[formnovalidate](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/formnovalidate)` | [`<button>`](element/button), [`<input>`](element/input) | If the button/input is a submit button (`type="submit"`), this boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the `novalidate` attribute of the button's [form](element/form) owner. |
| `[formtarget](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/formtarget)` | [`<button>`](element/button), [`<input>`](element/input) | If the button/input is a submit button (`type="submit"`), this attribute specifies the browsing context (for example, tab, window, or inline frame) in which to display the response that is received after submitting the form. If this attribute is specified, it overrides the `target` attribute of the button's [form](element/form) owner. |
| `[headers](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/headers)` | [`<td>`](element/td), [`<th>`](element/th) | IDs of the `<th>` elements which applies to this element. |
| `height` | [`<canvas>`](element/canvas), [`<embed>`](element/embed), [`<iframe>`](element/iframe), [`<img>`](element/img), [`<input>`](element/input), [`<object>`](element/object), [`<video>`](element/video) | Specifies the height of elements listed here. For all other elements, use the CSS [`height`](https://developer.mozilla.org/en-US/docs/Web/CSS/height) property. **Note:** In some instances, such as [`<div>`](element/div), this is a legacy attribute, in which case the CSS [`height`](https://developer.mozilla.org/en-US/docs/Web/CSS/height) property should be used instead. |
| `[hidden](global_attributes/hidden)` | [Global attribute](global_attributes) | Prevents rendering of given element, while keeping child elements, e.g. script elements, active. |
| `[high](element/meter#attr-high)` | [`<meter>`](element/meter) | Indicates the lower bound of the upper range. |
| `[href](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/href)` | [`<a>`](element/a), [`<area>`](element/area), [`<base>`](element/base), [`<link>`](element/link) | The URL of a linked resource. |
| `[hreflang](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/hreflang)` | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | Specifies the language of the linked resource. |
| `[http-equiv](element/meta#attr-http-equiv)` | [`<meta>`](element/meta) | Defines a pragma directive. |
| `[icon](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/command#attr-icon)` | `<command>` | Specifies a picture which represents the command. |
| `[id](global_attributes/id)` | [Global attribute](global_attributes) | Often used with CSS to style a specific element. The value of this attribute must be unique. |
| `[importance](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/importance)` Experimental | [`<iframe>`](element/iframe), [`<img>`](element/img), [`<link>`](element/link), [`<script>`](element/script) | Indicates the relative fetch priority for the resource. |
| `[integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)` | [`<link>`](element/link), [`<script>`](element/script) | Specifies a [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) value that allows browsers to verify what they fetch. |
| [`intrinsicsize`](element/img#attr-intrinsicsize) Deprecated | [`<img>`](element/img) | This attribute tells the browser to ignore the actual intrinsic size of the image and pretend it's the size specified in the attribute. |
| [`inputmode`](global_attributes/inputmode) | [`<textarea>`](element/textarea), [`contenteditable`](global_attributes/contenteditable) | Provides a hint as to the type of data that might be entered by the user while editing the element or its contents. The attribute can be used with form controls (such as the value of `textarea` elements), or in elements in an editing host (e.g., using `contenteditable` attribute). |
| `[ismap](element/img#attr-ismap)` | [`<img>`](element/img) | Indicates that the image is part of a server-side image map. |
| `[itemprop](global_attributes/itemprop)` | [Global attribute](global_attributes) | |
| `[keytype](element/keygen#attr-keytype)` | [`<keygen>`](element/keygen) | Specifies the type of key generated. |
| `[kind](element/track#attr-kind)` | [`<track>`](element/track) | Specifies the kind of text track. |
| `[label](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/label)` | [`<optgroup>`](element/optgroup), [`<option>`](element/option), [`<track>`](element/track) | Specifies a user-readable title of the element. |
| `[lang](global_attributes/lang)` | [Global attribute](global_attributes) | Defines the language used in the element. |
| `[language](element/script#attr-language)` Deprecated | [`<script>`](element/script) | Defines the script language used in the element. |
| `loading` Experimental | [`<img>`](element/img), [`<iframe>`](element/iframe) | Indicates if the element should be loaded lazily (`loading="lazy"`) or loaded immediately (`loading="eager"`). |
| `[list](element/input#list)` | [`<input>`](element/input) | Identifies a list of pre-defined options to suggest to the user. |
| `[loop](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/loop)` | [`<audio>`](element/audio), [`<bgsound>`](element/bgsound), [`<marquee>`](element/marquee), [`<video>`](element/video) | Indicates whether the media should start playing from the start when it's finished. |
| `[low](element/meter#attr-low)` | [`<meter>`](element/meter) | Indicates the upper bound of the lower range. |
| `[manifest](element/html#attr-manifest)` Deprecated | [`<html>`](element/html) | Specifies the URL of the document's cache manifest. **Note:** This attribute is obsolete, use [`<link rel="manifest">`](https://developer.mozilla.org/en-US/docs/Web/Manifest) instead. |
| `[max](attributes/max)` | [`<input>`](element/input), [`<meter>`](element/meter), [`<progress>`](element/progress) | Indicates the maximum value allowed. |
| `[maxlength](attributes/maxlength)` | [`<input>`](element/input), [`<textarea>`](element/textarea) | Defines the maximum number of characters allowed in the element. |
| `[minlength](attributes/minlength)` | [`<input>`](element/input), [`<textarea>`](element/textarea) | Defines the minimum number of characters allowed in the element. |
| `[media](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/media)` | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link), [`<source>`](element/source), [`<style>`](element/style) | Specifies a hint of the media for which the linked resource was designed. |
| `[method](element/form#attr-method)` | [`<form>`](element/form) | Defines which [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) method to use when submitting the form. Can be `GET` (default) or `POST`. |
| `[min](attributes/min)` | [`<input>`](element/input), [`<meter>`](element/meter) | Indicates the minimum value allowed. |
| `[multiple](attributes/multiple)` | [`<input>`](element/input), [`<select>`](element/select) | Indicates whether multiple values can be entered in an input of the type `email` or `file`. |
| `[muted](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/muted)` | [`<audio>`](element/audio), [`<video>`](element/video) | Indicates whether the audio will be initially silenced on page load. |
| `[name](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/name)` | [`<button>`](element/button), [`<form>`](element/form), [`<fieldset>`](element/fieldset), [`<iframe>`](element/iframe), [`<input>`](element/input), [`<keygen>`](element/keygen), [`<object>`](element/object), [`<output>`](element/output), [`<select>`](element/select), [`<textarea>`](element/textarea), [`<map>`](element/map), [`<meta>`](element/meta), [`<param>`](element/param) | Name of the element. For example used by the server to identify the fields in form submits. |
| `[novalidate](element/form#attr-novalidate)` | [`<form>`](element/form) | This attribute indicates that the form shouldn't be validated when submitted. |
| `[open](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/open)` | [`<details>`](element/details), [`<dialog>`](element/dialog) | Indicates whether the contents are currently visible (in the case of a `<details>` element) or whether the dialog is active and can be interacted with (in the case of a `<dialog>` element). |
| `[optimum](element/meter#attr-optimum)` | [`<meter>`](element/meter) | Indicates the optimal numeric value. |
| `[pattern](attributes/pattern)` | [`<input>`](element/input) | Defines a regular expression which the element's value will be validated against. |
| `[ping](element/a#attr-ping)` | [`<a>`](element/a), [`<area>`](element/area) | The `ping` attribute specifies a space-separated list of URLs to be notified if a user follows the hyperlink. |
| `[placeholder](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/placeholder)` | [`<input>`](element/input), [`<textarea>`](element/textarea) | Provides a hint to the user of what can be entered in the field. |
| `[playsinline](element/video#attr-playsinline)` | [`<video>`](element/video) | A Boolean attribute indicating that the video is to be played "inline"; that is, within the element's playback area. Note that the absence of this attribute does not imply that the video will always be played in fullscreen. |
| `[poster](element/video#attr-poster)` | [`<video>`](element/video) | A URL indicating a poster frame to show until the user plays or seeks. |
| `[preload](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/preload)` | [`<audio>`](element/audio), [`<video>`](element/video) | Indicates whether the whole resource, parts of it or nothing should be preloaded. |
| `[radiogroup](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/command#attr-radiogroup)` | `<command>` | |
| `[readonly](attributes/readonly)` | [`<input>`](element/input), [`<textarea>`](element/textarea) | Indicates whether the element can be edited. |
| `[referrerpolicy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/referralpolicy)` | [`<a>`](element/a), [`<area>`](element/area), [`<iframe>`](element/iframe), [`<img>`](element/img), [`<link>`](element/link), [`<script>`](element/script) | Specifies which referrer is sent when fetching the resource. |
| `[rel](attributes/rel)` | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | Specifies the relationship of the target object to the link object. |
| `[required](attributes/required)` | [`<input>`](element/input), [`<select>`](element/select), [`<textarea>`](element/textarea) | Indicates whether this element is required to fill out or not. |
| `[reversed](element/ol#attr-reversed)` | [`<ol>`](element/ol) | Indicates whether the list should be displayed in a descending order instead of an ascending order. |
| `[role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles)` | [Global attribute](global_attributes) | Defines an explicit role for an element for use by assistive technologies. |
| `[rows](element/textarea#attr-rows)` | [`<textarea>`](element/textarea) | Defines the number of rows in a text area. |
| `[rowspan](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rowspan)` | [`<td>`](element/td), [`<th>`](element/th) | Defines the number of rows a table cell should span over. |
| `[sandbox](element/iframe#attr-sandbox)` | [`<iframe>`](element/iframe) | Stops a document loaded in an iframe from using certain features (such as submitting forms or opening new windows). |
| `[scope](element/th#attr-scope)` | [`<th>`](element/th) | Defines the cells that the header test (defined in the `th` element) relates to. |
| `[scoped](element/style#attr-scoped)` Non-standard Deprecated | [`<style>`](element/style) | |
| `[selected](element/option#attr-selected)` | [`<option>`](element/option) | Defines a value which will be selected on page load. |
| `[shape](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/shape)` | [`<a>`](element/a), [`<area>`](element/area) | |
| `[size](attributes/size)` | [`<input>`](element/input), [`<select>`](element/select) | Defines the width of the element (in pixels). If the element's `type` attribute is `text` or `password` then it's the number of characters. |
| `[sizes](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/sizes)` | [`<link>`](element/link), [`<img>`](element/img), [`<source>`](element/source) | |
| `[slot](global_attributes/slot)` | [Global attribute](global_attributes) | Assigns a slot in a shadow DOM shadow tree to an element. |
| `[span](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/span)` | [`<col>`](element/col), [`<colgroup>`](element/colgroup) | |
| `[spellcheck](global_attributes/spellcheck)` | [Global attribute](global_attributes) | Indicates whether spell checking is allowed for the element. |
| `[src](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/src)` | [`<audio>`](element/audio), [`<embed>`](element/embed), [`<iframe>`](element/iframe), [`<img>`](element/img), [`<input>`](element/input), [`<script>`](element/script), [`<source>`](element/source), [`<track>`](element/track), [`<video>`](element/video) | The URL of the embeddable content. |
| `[srcdoc](element/iframe#attr-srcdoc)` | [`<iframe>`](element/iframe) | |
| `[srclang](element/track#attr-srclang)` | [`<track>`](element/track) | |
| `[srcset](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/srcset)` | [`<img>`](element/img), [`<source>`](element/source) | One or more responsive image candidates. |
| `[start](element/ol#attr-start)` | [`<ol>`](element/ol) | Defines the first number if other than 1. |
| `[step](attributes/step)` | [`<input>`](element/input) | |
| `[style](global_attributes/style)` | [Global attribute](global_attributes) | Defines CSS styles which will override styles previously set. |
| `[summary](element/table#attr-summary)` Deprecated | [`<table>`](element/table) | |
| `[tabindex](global_attributes/tabindex)` | [Global attribute](global_attributes) | Overrides the browser's default tab order and follows the one specified instead. |
| `[target](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/target)` | [`<a>`](element/a), [`<area>`](element/area), [`<base>`](element/base), [`<form>`](element/form) | Specifies where to open the linked document (in the case of an `<a>` element) or where to display the response received (in the case of a `<form>` element) |
| `[title](global_attributes/title)` | [Global attribute](global_attributes) | Text to be displayed in a tooltip when hovering over the element. |
| `[translate](global_attributes/translate)` | [Global attribute](global_attributes) | Specify whether an element's attribute values and the values of its `[Text](https://dom.spec.whatwg.org/#text)` node children are to be translated when the page is localized, or whether to leave them unchanged. |
| `[type](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/type)` | [`<button>`](element/button), [`<input>`](element/input), `<command>`, [`<embed>`](element/embed), [`<object>`](element/object), [`<ol>`](element/ol), [`<script>`](element/script), [`<source>`](element/source), [`<style>`](element/style), [`<menu>`](element/menu), [`<link>`](element/link) | Defines the type of the element. |
| `[usemap](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/usemap)` | [`<img>`](element/img), [`<input>`](element/input), [`<object>`](element/object) | |
| `[value](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/value)` | [`<button>`](element/button), [`<data>`](element/data), [`<input>`](element/input), [`<li>`](element/li), [`<meter>`](element/meter), [`<option>`](element/option), [`<progress>`](element/progress), [`<param>`](element/param) | Defines a default value which will be displayed in the element on page load. |
| `[width](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/width)` | [`<canvas>`](element/canvas), [`<embed>`](element/embed), [`<iframe>`](element/iframe), [`<img>`](element/img), [`<input>`](element/input), [`<object>`](element/object), [`<video>`](element/video) | For the elements listed here, this establishes the element's width. **Note:** For all other instances, such as [`<div>`](element/div), this is a legacy attribute, in which case the CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property should be used instead. |
| `[wrap](element/textarea#attr-wrap)` | [`<textarea>`](element/textarea) | Indicates whether the text should be wrapped. |
Content versus IDL attributes
-----------------------------
In HTML, most attributes have two faces: the **content attribute** and the **IDL (Interface Definition Language) attribute**.
The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via [`element.setAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute) or [`element.getAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute). The content attribute is always a string even when the expected value should be an integer. For example, to set an [`<input>`](element/input) element's `maxlength` to 42 using the content attribute, you have to call `setAttribute("maxlength", "42")` on that element.
The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like `element.foo`. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.
Most of the time, IDL attributes will return their values as they are really used. For example, the default `type` for [`<input>`](element/input) elements is "text", so if you set `input.type="foobar"`, the `<input>` element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the `type` IDL attribute will return the string "text".
IDL attributes are not always strings; for example, `input.maxlength` is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so `input.maxlength` is always going to return a number and when you set `input.maxlength`, it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.
IDL attributes can [reflect other types](https://html.spec.whatwg.org/multipage/urls-and-fetching.html) such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow [the rules laid out in the specification](https://html.spec.whatwg.org/multipage/urls-and-fetching.html), but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (`select.size`, for example) and you should read the specifications to understand how exactly they behave.
Boolean Attributes
------------------
Some content attributes (e.g. `required`, `readonly`, `disabled`) are called [boolean attributes](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes). If a boolean attribute is present, its value is **true**, and if it's absent, its value is **false**.
HTML defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace. The following examples are valid ways to mark up a boolean attribute:
```
<div itemscope>This is valid HTML but invalid XML.</div>
<div itemscope=itemscope>This is also valid HTML but invalid XML.</div>
<div itemscope="">This is valid HTML and also valid XML.</div>
<div itemscope="itemscope">
This is also valid HTML and XML, but perhaps a bit verbose.
</div>
```
To be clear, the values "`true`" and "`false`" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether. This restriction clears up some common misunderstandings: With `checked="false"` for example, the element's `checked` attribute would be interpreted as **true** because the attribute is present.
Event handler attributes
------------------------
**Warning:** The use of event handler content attributes is discouraged. The mix of HTML and JavaScript often produces unmaintainable code, and the execution of event handler attributes may also be blocked by content security policies.
In addition to the attributes listed in the table above, global [event handlers](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers#using_onevent_properties) — such as [`onclick`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) — can also be specified as [content attributes](#content_versus_idl_attributes) on all elements.
All event handler attributes accept a string. The string will be used to synthesize a [JavaScript function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions) like `function name(/*args*/) {body}`, where `name` is the attribute's name, and `body` is the attribute's value. The handler receives the same parameters as its JavaScript event handler counterpart — most handlers receive only one `event` parameter, while `onerror` receives five: `event`, `source`, `lineno`, `colno`, `error`. This means you can, in general, use the `event` variable within the attribute.
```
<div onclick="console.log(event)">Click me!</div>
<!-- The synthesized handler has a name; you can reference itself -->
<div onclick="console.log(onclick)">Click me!</div>
```
See also
--------
* [HTML elements](element)
| programming_docs |
html HTML elements reference HTML elements reference
=======================
This page lists all the [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) [elements](https://developer.mozilla.org/en-US/docs/Glossary/Element), which are created using [tags](https://developer.mozilla.org/en-US/docs/Glossary/Tag).
They are grouped by function to help you find what you have in mind easily. An alphabetical list of all elements is provided in the sidebar on every element's page as well as this one.
**Note:** For more information about the basics of HTML elements and attributes, see [the section on elements in the Introduction to HTML article](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML#elements_%e2%80%94_the_basic_building_blocks).
Main root
---------
| Element | Description |
| --- | --- |
| [`<html>`](element/html) | The `<html>` [HTML](index) element represents the root (top-level element) of an HTML document, so it is also referred to as the *root element*. All other elements must be descendants of this element. |
Document metadata
-----------------
Metadata contains information about the page. This includes information about styles, scripts and data to help software ([search engines](https://developer.mozilla.org/en-US/docs/Glossary/Search_engine), [browsers](https://developer.mozilla.org/en-US/docs/Glossary/Browser), etc.) use and render the page. Metadata for styles and scripts may be defined in the page or link to another file that has the information.
| Element | Description |
| --- | --- |
| [`<base>`](element/base) | The `<base>` [HTML](index) element specifies the base URL to use for all *relative* URLs in a document. There can be only one `<base>` element in a document. |
| [`<head>`](element/head) | The `<head>` [HTML](index) element contains machine-readable information (metadata) about the document, like its [title](element/title), [scripts](element/script), and [style sheets](element/style). |
| [`<link>`](element/link) | The `<link>` [HTML](index) element specifies relationships between the current document and an external resource. This element is most commonly used to link to CSS, but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things. |
| [`<meta>`](element/meta) | The `<meta>` [HTML](index) element represents Metadata that cannot be represented by other HTML meta-related elements, like `base`, `link`, `script`, `style` or `title`. |
| [`<style>`](element/style) | The `<style>` [HTML](index) element contains style information for a document, or part of a document. It contains CSS, which is applied to the contents of the document containing the `<style>` element. |
| [`<title>`](element/title) | The `<title>` [HTML](index) element defines the document's title that is shown in a Browser's title bar or a page's tab. It only contains text; tags within the element are ignored. |
Sectioning root
---------------
| Element | Description |
| --- | --- |
| [`<body>`](element/body) | The `<body>` [HTML](index) element represents the content of an HTML document. There can be only one `<body>` element in a document. |
Content sectioning
------------------
Content sectioning elements allow you to organize the document content into logical pieces. Use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content.
| Element | Description |
| --- | --- |
| [`<address>`](element/address) | The `<address>` [HTML](index) element indicates that the enclosed HTML provides contact information for a person or people, or for an organization. |
| [`<article>`](element/article) | The `<article>` [HTML](index) element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include: a forum post, a magazine or newspaper article, or a blog entry, a product card, a user-submitted comment, an interactive widget or gadget, or any other independent item of content. |
| [`<aside>`](element/aside) | The `<aside>` [HTML](index) element represents a portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes. |
| [`<footer>`](element/footer) | The `<footer>` [HTML](index) element represents a footer for its nearest ancestor [sectioning content](content_categories#sectioning_content) or [sectioning root](element/heading_elements#sectioning_root) element. A `<footer>` typically contains information about the author of the section, copyright data or links to related documents. |
| [`<header>`](element/header) | The `<header>` [HTML](index) element represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also a logo, a search form, an author name, and other elements. |
| [`<h1>`](element/heading_elements), [`<h2>`](element/heading_elements), [`<h3>`](element/heading_elements), [`<h4>`](element/heading_elements), [`<h5>`](element/heading_elements), [`<h6>`](element/heading_elements) | The `<h1>` to `<h6>` [HTML](index) elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. |
| [`<main>`](element/main) | The `<main>` [HTML](index) element represents the dominant content of the `body` of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. |
| [`<nav>`](element/nav) | The `<nav>` [HTML](index) element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes. |
| [`<section>`](element/section) | The `<section>` [HTML](index) element represents a generic standalone section of a document, which doesn't have a more specific semantic element to represent it. Sections should always have a heading, with very few exceptions. |
Text content
------------
Use HTML text content elements to organize blocks or sections of content placed between the opening [`<body>`](element/body) and closing `</body>` tags. Important for [accessibility](https://developer.mozilla.org/en-US/docs/Glossary/Accessibility) and [SEO](https://developer.mozilla.org/en-US/docs/Glossary/SEO), these elements identify the purpose or structure of that content.
| Element | Description |
| --- | --- |
| [`<blockquote>`](element/blockquote) | The `<blockquote>` [HTML](index) element indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see [Notes](#usage_notes) for how to change it). A URL for the source of the quotation may be given using the `cite` attribute, while a text representation of the source can be given using the `cite` element. |
| [`<dd>`](element/dd) | The `<dd>` [HTML](index) element provides the description, definition, or value for the preceding term (`dt`) in a description list (`dl`). |
| [`<div>`](element/div) | The `<div>` [HTML](index) element is the generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g. styling is directly applied to it, or some kind of layout model like [Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout) is applied to its parent element). |
| [`<dl>`](element/dl) | The `<dl>` [HTML](index) element represents a description list. The element encloses a list of groups of terms (specified using the `dt` element) and descriptions (provided by `dd` elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs). |
| [`<dt>`](element/dt) | The `<dt>` [HTML](index) element specifies a term in a description or definition list, and as such must be used inside a `dl` element. It is usually followed by a `dd` element; however, multiple `<dt>` elements in a row indicate several terms that are all defined by the immediate next `dd` element. |
| [`<figcaption>`](element/figcaption) | The `<figcaption>` [HTML](index) element represents a caption or legend describing the rest of the contents of its parent `figure` element. |
| [`<figure>`](element/figure) | The `<figure>` [HTML](index) element represents self-contained content, potentially with an optional caption, which is specified using the `figcaption` element. The figure, its caption, and its contents are referenced as a single unit. |
| [`<hr>`](element/hr) | The `<hr>` [HTML](index) element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section. |
| [`<li>`](element/li) | The `<li>` [HTML](index) element is used to represent an item in a list. It must be contained in a parent element: an ordered list (`ol`), an unordered list (`ul`), or a menu (`menu`). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter. |
| [`<menu>`](element/menu) | The `<menu>` [HTML](index) element is described in the HTML specification as a semantic alternative to `ul`, but treated by browsers (and exposed through the accessibility tree) as no different than `ul`. It represents an unordered list of items (which are represented by `li` elements). |
| [`<ol>`](element/ol) | The `<ol>` [HTML](index) element represents an ordered list of items — typically rendered as a numbered list. |
| [`<p>`](element/p) | The `<p>` [HTML](index) element represents a paragraph. Paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but HTML paragraphs can be any structural grouping of related content, such as images or form fields. |
| [`<pre>`](element/pre) | The `<pre>` [HTML](index) element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional, or [monospaced](https://en.wikipedia.org/wiki/Monospaced_font), font. Whitespace inside this element is displayed as written. |
| [`<ul>`](element/ul) | The `<ul>` [HTML](index) element represents an unordered list of items, typically rendered as a bulleted list. |
Inline text semantics
---------------------
Use the HTML inline text semantic to define the meaning, structure, or style of a word, line, or any arbitrary piece of text.
| Element | Description |
| --- | --- |
| [`<a>`](element/a) | The `<a>` [HTML](index) element (or *anchor* element), with [its `href` attribute](#attr-href), creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address. |
| [`<abbr>`](element/abbr) | The `<abbr>` [HTML](index) element represents an abbreviation or acronym. |
| [`<b>`](element/b) | The `<b>` [HTML](index) element is used to draw the reader's attention to the element's contents, which are not otherwise granted special importance. This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use `<b>` for styling text; instead, you should use the CSS `font-weight` property to create boldface text, or the `strong` element to indicate that text is of special importance. |
| [`<bdi>`](element/bdi) | The `<bdi>` [HTML](index) element tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. It's particularly useful when a website dynamically inserts some text and doesn't know the directionality of the text being inserted. |
| [`<bdo>`](element/bdo) | The `<bdo>` [HTML](index) element overrides the current directionality of text, so that the text within is rendered in a different direction. |
| [`<br>`](element/br) | The `<br>` [HTML](index) element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant. |
| [`<cite>`](element/cite) | The `<cite>` [HTML](index) element is used to describe a reference to a cited creative work, and must include the title of that work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata. |
| [`<code>`](element/code) | The `<code>` [HTML](index) element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the user agent default monospace font. |
| [`<data>`](element/data) | The `<data>` [HTML](index) element links a given piece of content with a machine-readable translation. If the content is time- or date-related, the `time` element must be used. |
| [`<dfn>`](element/dfn) | The `<dfn>` [HTML](index) element is used to indicate the term being defined within the context of a definition phrase or sentence. The ancestor `p` element, the `dt`/`dd` pairing, or the nearest `section` ancestor of the `<dfn>` element, is considered to be the definition of the term. |
| [`<em>`](element/em) | The `<em>` [HTML](index) element marks text that has stress emphasis. The `<em>` element can be nested, with each level of nesting indicating a greater degree of emphasis. |
| [`<i>`](element/i) | The `<i>` [HTML](index) element represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. Historically, these have been presented using italicized type, which is the original source of the `<i>` naming of this element. |
| [`<kbd>`](element/kbd) | The `<kbd>` [HTML](index) element represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the user agent defaults to rendering the contents of a `<kbd>` element using its default monospace font, although this is not mandated by the HTML standard. |
| [`<mark>`](element/mark) | The `<mark>` [HTML](index) element represents text which is **marked** or **highlighted** for reference or notation purposes due to the marked passage's relevance in the enclosing context. |
| [`<q>`](element/q) | The `<q>` [HTML](index) element indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the `blockquote` element. |
| [`<rp>`](element/rp) | The `<rp>` [HTML](index) element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the `ruby` element. One `<rp>` element should enclose each of the opening and closing parentheses that wrap the `rt` element that contains the annotation's text. |
| [`<rt>`](element/rt) | The `<rt>` [HTML](index) element specifies the ruby text component of a ruby annotation, which is used to provide pronunciation, translation, or transliteration information for East Asian typography. The `<rt>` element must always be contained within a `ruby` element. |
| [`<ruby>`](element/ruby) | The `<ruby>` [HTML](index) element represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common. |
| [`<s>`](element/s) | The `<s>` [HTML](index) element renders text with a strikethrough, or a line through it. Use the `<s>` element to represent things that are no longer relevant or no longer accurate. However, `<s>` is not appropriate when indicating document edits; for that, use the `del` and `ins` elements, as appropriate. |
| [`<samp>`](element/samp) | The `<samp>` [HTML](index) element is used to enclose inline text which represents sample (or quoted) output from a computer program. Its contents are typically rendered using the browser's default monospaced font (such as [Courier](https://en.wikipedia.org/wiki/Courier_(typeface)) or Lucida Console). |
| [`<small>`](element/small) | The `<small>` [HTML](index) element represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font-size smaller, such as from `small` to `x-small`. |
| [`<span>`](element/span) | The `<span>` [HTML](index) element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the `class` or `id` attributes), or because they share attribute values, such as `lang`. It should be used only when no other semantic element is appropriate. `<span>` is very much like a `div` element, but `div` is a [block-level element](block-level_elements) whereas a `<span>` is an [inline element](inline_elements). |
| [`<strong>`](element/strong) | The `<strong>` [HTML](index) element indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type. |
| [`<sub>`](element/sub) | The `<sub>` [HTML](index) element specifies inline text which should be displayed as subscript for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text. |
| [`<sup>`](element/sup) | The `<sup>` [HTML](index) element specifies inline text which is to be displayed as superscript for solely typographical reasons. Superscripts are usually rendered with a raised baseline using smaller text. |
| [`<time>`](element/time) | The `<time>` [HTML](index) element represents a specific period in time. It may include the `datetime` attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders. |
| [`<u>`](element/u) | The `<u>` [HTML](index) element represents a span of inline text which should be rendered in a way that indicates that it has a non-textual annotation. This is rendered by default as a simple solid underline, but may be altered using CSS. |
| [`<var>`](element/var) | The `<var>` [HTML](index) element represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent. |
| [`<wbr>`](element/wbr) | The `<wbr>` [HTML](index) element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location. |
Image and multimedia
--------------------
HTML supports various multimedia resources such as images, audio, and video.
| Element | Description |
| --- | --- |
| [`<area>`](element/area) | The `<area>` [HTML](index) element defines an area inside an image map that has predefined clickable areas. An *image map* allows geometric areas on an image to be associated with Hyperlink. |
| [`<audio>`](element/audio) | The `<audio>` [HTML](index) element is used to embed sound content in documents. It may contain one or more audio sources, represented using the `src` attribute or the `source` element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a `MediaStream`. |
| [`<img>`](element/img) | The `<img>` [HTML](index) element embeds an image into the document. |
| [`<map>`](element/map) | The `<map>` [HTML](index) element is used with `area` elements to define an image map (a clickable link area). |
| [`<track>`](element/track) | The `<track>` [HTML](index) element is used as a child of the media elements, `audio` and `video`. It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in [WebVTT format](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API) (`.vtt` files) — Web Video Text Tracks. |
| [`<video>`](element/video) | The `<video>` [HTML](index) element embeds a media player which supports video playback into the document. You can use `<video>` for audio content as well, but the `audio` element may provide a more appropriate user experience. |
Embedded content
----------------
In addition to regular multimedia content, HTML can include a variety of other content, even if it's not always easy to interact with.
| Element | Description |
| --- | --- |
| [`<embed>`](element/embed) | The `<embed>` [HTML](index) element embeds external content at the specified point in the document. This content is provided by an external application or other source of interactive content such as a browser plug-in. |
| [`<iframe>`](element/iframe) | The `<iframe>` [HTML](index) element represents a nested browsing context, embedding another HTML page into the current one. |
| [`<object>`](element/object) | The `<object>` [HTML](index) element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin. |
| [`<picture>`](element/picture) | The `<picture>` [HTML](index) element contains zero or more `source` elements and one `img` element to offer alternative versions of an image for different display/device scenarios. |
| [`<portal>`](element/portal) | The `<portal>` [HTML](index) element enables the embedding of another HTML page into the current one for the purposes of allowing smoother navigation into new pages. |
| [`<source>`](element/source) | The `<source>` [HTML](index) element specifies multiple media resources for the `picture`, the `audio` element, or the `video` element. It is a void element, meaning that it has no content and does not have a closing tag. It is commonly used to offer the same media content in multiple file formats in order to provide compatibility with a broad range of browsers given their differing support for [image file formats](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types) and [media file formats](https://developer.mozilla.org/en-US/docs/Web/Media/Formats). |
SVG and MathML
--------------
You can embed [SVG](https://developer.mozilla.org/en-US/docs/Web/SVG) and [MathML](https://developer.mozilla.org/en-US/docs/Web/MathML) content directly into HTML documents, using the [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg) and `[<math>](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math)` elements.
| Element | Description |
| --- | --- |
| [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg) | The `svg` element is a container that defines a new coordinate system and [viewport](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox). It is used as the outermost element of SVG documents, but it can also be used to embed an SVG fragment inside an SVG or HTML document. |
| `[<math>](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math)` | The top-level element in MathML is `<math>`. Every valid MathML instance must be wrapped in `<math>` tags. In addition you must not nest a second `<math>` element in another, but you can have an arbitrary number of other child elements in it. |
Scripting
---------
In order to create dynamic content and Web applications, HTML supports the use of scripting languages, most prominently JavaScript. Certain elements support this capability.
| Element | Description |
| --- | --- |
| [`<canvas>`](element/canvas) | Use the `<canvas>` with either the [canvas scripting API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) or the [WebGL API](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) to draw graphics and animations. |
| [`<noscript>`](element/noscript) | The `<noscript>` [HTML](index) element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. |
| [`<script>`](element/script) | The `<script>` [HTML](index) element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The `<script>` element can also be used with other languages, such as [WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API)'s GLSL shader programming language and [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON). |
Demarcating edits
-----------------
These elements let you provide indications that specific parts of the text have been altered.
| Element | Description |
| --- | --- |
| [`<del>`](element/del) | The `<del>` [HTML](index) element represents a range of text that has been deleted from a document. This can be used when rendering "track changes" or source code diff information, for example. The `ins` element can be used for the opposite purpose: to indicate text that has been added to the document. |
| [`<ins>`](element/ins) | The `<ins>` [HTML](index) element represents a range of text that has been added to a document. You can use the `del` element to similarly represent a range of text that has been deleted from the document. |
Table content
-------------
The elements here are used to create and handle tabular data.
| Element | Description |
| --- | --- |
| [`<caption>`](element/caption) | The `<caption>` [HTML](index) element specifies the caption (or title) of a table. |
| [`<col>`](element/col) | The `<col>` [HTML](index) element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a `colgroup` element. |
| [`<colgroup>`](element/colgroup) | The `<colgroup>` [HTML](index) element defines a group of columns within a table. |
| [`<table>`](element/table) | The `<table>` [HTML](index) element represents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. |
| [`<tbody>`](element/tbody) | The `<tbody>` [HTML](index) element encapsulates a set of table rows (`tr` elements), indicating that they comprise the body of the table (`table`). |
| [`<td>`](element/td) | The `<td>` [HTML](index) element defines a cell of a table that contains data. It participates in the *table model*. |
| [`<tfoot>`](element/tfoot) | The `<tfoot>` [HTML](index) element defines a set of rows summarizing the columns of the table. |
| [`<th>`](element/th) | The `<th>` [HTML](index) element defines a cell as header of a group of table cells. The exact nature of this group is defined by the `scope` and `headers` attributes. |
| [`<thead>`](element/thead) | The `<thead>` [HTML](index) element defines a set of rows defining the head of the columns of the table. |
| [`<tr>`](element/tr) | The `<tr>` [HTML](index) element defines a row of cells in a table. The row's cells can then be established using a mix of `td` (data cell) and `th` (header cell) elements. |
Forms
-----
HTML provides a number of elements which can be used together to create forms which the user can fill out and submit to the website or application. There's a great deal of further information about this available in the [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms).
| Element | Description |
| --- | --- |
| [`<button>`](element/button) | The `<button>` [HTML](index) element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs an action, such as submitting a [form](https://developer.mozilla.org/en-US/docs/Learn/Forms) or opening a dialog. |
| [`<datalist>`](element/datalist) | The `<datalist>` [HTML](index) element contains a set of `option` elements that represent the permissible or recommended options available to choose from within other controls. |
| [`<fieldset>`](element/fieldset) | The `<fieldset>` [HTML](index) element is used to group several controls as well as labels (`label`) within a web form. |
| [`<form>`](element/form) | The `<form>` [HTML](index) element represents a document section containing interactive controls for submitting information. |
| [`<input>`](element/input) | The `<input>` [HTML](index) element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. The `<input>` element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes. |
| [`<label>`](element/label) | The `<label>` [HTML](index) element represents a caption for an item in a user interface. |
| [`<legend>`](element/legend) | The `<legend>` [HTML](index) element represents a caption for the content of its parent `fieldset`. |
| [`<meter>`](element/meter) | The `<meter>` [HTML](index) element represents either a scalar value within a known range or a fractional value. |
| [`<optgroup>`](element/optgroup) | The `<optgroup>` [HTML](index) element creates a grouping of options within a `select` element. |
| [`<option>`](element/option) | The `<option>` [HTML](index) element is used to define an item contained in a `select`, an `optgroup`, or a `datalist` element. As such, `<option>` can represent menu items in popups and other lists of items in an HTML document. |
| [`<output>`](element/output) | The `<output>` [HTML](index) element is a container element into which a site or app can inject the results of a calculation or the outcome of a user action. |
| [`<progress>`](element/progress) | The `<progress>` [HTML](index) element displays an indicator showing the completion progress of a task, typically displayed as a progress bar. |
| [`<select>`](element/select) | The `<select>` [HTML](index) element represents a control that provides a menu of options. |
| [`<textarea>`](element/textarea) | The `<textarea>` [HTML](index) element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form. |
Interactive elements
--------------------
HTML offers a selection of elements which help to create interactive user interface objects.
| Element | Description |
| --- | --- |
| [`<details>`](element/details) | The `<details>` [HTML](index) element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the `summary` element. |
| [`<dialog>`](element/dialog) | The `<dialog>` [HTML](index) element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow. |
| [`<summary>`](element/summary) | The `<summary>` [HTML](index) element specifies a summary, caption, or legend for a `details` element's disclosure box. Clicking the `<summary>` element toggles the state of the parent `<details>` element open and closed. |
Web Components
--------------
Web Components is an HTML-related technology which makes it possible to, essentially, create and use custom elements as if it were regular HTML. In addition, you can create custom versions of standard HTML elements.
| Element | Description |
| --- | --- |
| [`<slot>`](element/slot) | The `<slot>` [HTML](index) element—part of the [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. |
| [`<template>`](element/template) | The `<template>` [HTML](index) element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript. |
Obsolete and deprecated elements
--------------------------------
**Warning:** These are old HTML elements which are deprecated and should not be used. **You should never use them in new projects, and you should replace them in old projects as soon as you can.** They are listed here for completeness only.
| Element | Description |
| --- | --- |
| [`<acronym>`](element/acronym) | The `<acronym>` [HTML](index) element allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word. |
| [`<applet>`](element/applet) | The obsolete **HTML Applet Element** (`<applet>`) embeds a Java applet into the document; this element has been deprecated in favor of `object`. |
| [`<bgsound>`](element/bgsound) | The `<bgsound>` [HTML](index) element is deprecated. It sets up a sound file to play in the background while the page is used; use `audio` instead. |
| [`<big>`](element/big) | The `<big>` [HTML](index) deprecated element renders the enclosed text at a font size one level larger than the surrounding text (`medium` becomes `large`, for example). The size is capped at the browser's maximum permitted font size. |
| [`<blink>`](element/blink) | The `<blink>` [HTML](index) element is a non-standard element which causes the enclosed text to flash slowly. |
| [`<center>`](element/center) | The `<center>` [HTML](index) element is a [block-level element](block-level_elements) that displays its block-level or inline contents centered horizontally within its containing element. The container is usually, but isn't required to be, `body`. |
| [`<content>`](element/content) | The `<content>` [HTML](index) element—an obsolete part of the [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) suite of technologies—was used inside of [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) as an insertion point, and wasn't meant to be used in ordinary HTML. It has now been replaced by the `slot` element, which creates a point in the DOM at which a shadow DOM can be inserted. |
| [`<dir>`](element/dir) | The `<dir>` [HTML](index) element is used as a container for a directory of files and/or folders, potentially with styles and icons applied by the user agent. Do not use this obsolete element; instead, you should use the `ul` element for lists, including lists of files. |
| [`<font>`](element/font) | The `<font>` [HTML](index) element defines the font size, color and face for its content. |
| [`<frame>`](element/frame) | The `<frame>` [HTML](index) element defines a particular area in which another HTML document can be displayed. A frame should be used within a `frameset`. |
| [`<frameset>`](element/frameset) | The `<frameset>` [HTML](index) element is used to contain `frame` elements. |
| [`<image>`](element/image) | The `<image>` [HTML](index) element is an ancient and poorly supported precursor to the `img` element. **It should not be used**. |
| [`<keygen>`](element/keygen) | The `<keygen>` [HTML](index) element exists to facilitate generation of key material, and submission of the public key as part of an [HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms). This mechanism is designed for use with Web-based certificate management systems. It is expected that the `<keygen>` element will be used in an HTML form along with other information needed to construct a certificate request, and that the result of the process will be a signed certificate. |
| [`<marquee>`](element/marquee) | The `<marquee>` [HTML](index) element is used to insert a scrolling area of text. You can control what happens when the text reaches the edges of its content area using its attributes. |
| [`<menuitem>`](element/menuitem) | The `<menuitem>` [HTML](index) element represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button. |
| [`<nobr>`](element/nobr) | The `<nobr>` [HTML](index) element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text. |
| [`<noembed>`](element/noembed) | The `<noembed>` [HTML](index) element is an obsolete, non-standard way to provide alternative, or "fallback", content for browsers that do not support the `embed` element or do not support the type of [embedded content](content_categories#embedded_content) an author wishes to use. This element was deprecated in HTML 4.01 and above in favor of placing fallback content between the opening and closing tags of an `object` element. |
| [`<noframes>`](element/noframes) | The `<noframes>` [HTML](index) element provides content to be presented in browsers that don't support (or have disabled support for) the `frame` element. Although most commonly-used browsers support frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers. |
| [`<param>`](element/param) | The `<param>` [HTML](index) element defines parameters for an `object` element. |
| [`<plaintext>`](element/plaintext) | The `<plaintext>` [HTML](index) element renders everything following the start tag as raw text, ignoring any following HTML. There is no closing tag, since everything after it is considered raw text. |
| [`<rb>`](element/rb) | The `<rb>` [HTML](index) element is used to delimit the base text component of a `ruby` annotation, i.e. the text that is being annotated. One `<rb>` element should wrap each separate atomic segment of the base text. |
| [`<rtc>`](element/rtc) | The `<rtc>` [HTML](index) element embraces semantic annotations of characters presented in a ruby of `rb` elements used inside of `ruby` element. `rb` elements can have both pronunciation (`rt`) and semantic (`rtc`) annotations. |
| [`<shadow>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/shadow) | The `<shadow>` [HTML](index) element—an obsolete part of the [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) technology suite—was intended to be used as a shadow DOM insertion point. You might have used it if you have created multiple shadow roots under a shadow host. It is not useful in ordinary HTML. |
| [`<spacer>`](element/spacer) | The `<spacer>` [HTML](index) element is an obsolete HTML element which allowed insertion of empty spaces on pages. It was devised by Netscape to accomplish the same effect as a single-pixel layout image, which was something web designers used to use to add white spaces to web pages without actually using an image. However, `<spacer>` is no longer supported by any major browser and the same effects can now be achieved using simple CSS. |
| [`<strike>`](element/strike) | The `<strike>` [HTML](index) element places a strikethrough (horizontal line) over text. |
| [`<tt>`](element/tt) | The `<tt>` [HTML](index) element creates inline text which is presented using the user agent default monospace font face. This element was created for the purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer. |
| [`<xmp>`](element/xmp) | The `<xmp>` [HTML](index) element renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line. |
| programming_docs |
html HTML: HyperText Markup Language HTML: HyperText Markup Language
===============================
**HTML** (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page's appearance/presentation ([CSS](https://developer.mozilla.org/en-US/docs/Web/CSS)) or functionality/behavior ([JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)).
"Hypertext" refers to links that connect web pages to one another, either within a single website or between websites. Links are a fundamental aspect of the Web. By uploading content to the Internet and linking it to pages created by other people, you become an active participant in the World Wide Web.
HTML uses "markup" to annotate text, images, and other content for display in a Web browser. HTML markup includes special "elements" such as [`<head>`](element/head), [`<title>`](element/title), [`<body>`](element/body), [`<header>`](element/header), [`<footer>`](element/footer), [`<article>`](element/article), [`<section>`](element/section), [`<p>`](element/p), [`<div>`](element/div), [`<span>`](element/span), [`<img>`](element/img), [`<aside>`](element/aside), [`<audio>`](element/audio), [`<canvas>`](element/canvas), [`<datalist>`](element/datalist), [`<details>`](element/details), [`<embed>`](element/embed), [`<nav>`](element/nav), [`<output>`](element/output), [`<progress>`](element/progress), [`<video>`](element/video), [`<ul>`](element/ul), [`<ol>`](element/ol), [`<li>`](element/li) and many others.
An HTML element is set off from other text in a document by "tags", which consist of the element name surrounded by "`<`" and "`>`". The name of an element inside a tag is case insensitive. That is, it can be written in uppercase, lowercase, or a mixture. For example, the `<title>` tag can be written as `<Title>`, `<TITLE>`, or in any other way. However, the convention and recommended practice is to write tags in lowercase.
The articles below can help you learn more about HTML.
Key resources
-------------
HTML Introduction If you're new to web development, be sure to read our [HTML Basics](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics) article to learn what HTML is and how to use it.
HTML Tutorials For articles about how to use HTML, as well as tutorials and complete examples, check out our [HTML Learning Area](https://developer.mozilla.org/en-US/docs/Learn/HTML).
HTML Reference In our extensive [HTML reference](reference) section, you'll find the details about every element and attribute in HTML.
#### Looking to become a front-end web developer?
We have put together a course that includes all the essential information you need to work towards your goal.
[**Get started**](https://developer.mozilla.org/en-US/docs/Learn/Front-end_web_developer)
Beginner's tutorials
--------------------
Our [HTML Learning Area](https://developer.mozilla.org/en-US/docs/Learn/HTML) features multiple modules that teach HTML from the ground up — no previous knowledge required.
[Introduction to HTML](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML) This module sets the stage, getting you used to important concepts and syntax such as looking at applying HTML to text, how to create hyperlinks, and how to use HTML to structure a web page.
[Multimedia and embedding](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding) This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.
[HTML tables](https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables) Representing tabular data on a webpage in an understandable, accessible way can be a challenge. This module covers basic table markup, along with more complex features such as implementing captions and summaries.
[HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) Forms are a very important part of the Web — these provide much of the functionality you need for interacting with websites, e.g. registering and logging in, sending feedback, buying products, and more. This module gets you started with creating the client-side/front-end parts of forms.
[Use HTML to solve common problems](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto) Provides links to sections of content explaining how to use HTML to solve very common problems when creating a web page: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc.
Advanced topics
---------------
[CORS enabled image](cors_enabled_image) The [`crossorigin`](element/img#attr-crossorigin) attribute, in combination with an appropriate [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) header, allows images defined by the [`<img>`](element/img) element to be loaded from foreign origins and used in a [`<canvas>`](element/canvas) element as if they were being loaded from the current origin.
[CORS settings attributes](attributes/crossorigin) Some HTML elements that provide support for [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), such as [`<img>`](element/img) or [`<video>`](element/video), have a `crossorigin` attribute (`crossOrigin` property), which lets you configure the CORS requests for the element's fetched data.
[Preloading content with rel="preload"](link_types/preload) The `preload` value of the [`<link>`](element/link) element's [`rel`](element/link#attr-rel) attribute allows you to write declarative fetch requests in your HTML [`<head>`](element/head), specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. This article provides a basic guide to how `preload` works.
Reference
---------
[HTML reference](reference) HTML consists of **elements**, each of which may be modified by some number of **attributes**. HTML documents are connected to each other with [links](link_types).
[HTML element reference](element) Browse a list of all [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) [elements](https://developer.mozilla.org/en-US/docs/Glossary/Element).
[HTML attribute reference](attributes) Elements in HTML have **attributes**. These are additional values that configure the elements or adjust their behavior in various ways.
[Global attributes](global_attributes) Global attributes may be specified on all [HTML elements](element), *even those not specified in the standard*. This means that any non-standard elements must still permit these attributes, even though those elements make the document HTML5-noncompliant.
[Inline elements](inline_elements) and [block-level elements](block-level_elements)
HTML elements are usually "inline" or "block-level" elements. An inline element occupies only the space bounded by the tags that define it. A block-level element occupies the entire space of its parent element (container), thereby creating a "block".
[Link types](link_types) In HTML, various link types can be used to establish and define the relationship between two documents. Link elements that types can be set on include [`<a>`](element/a), [`<area>`](element/area) and [`<link>`](element/link).
[Guide to media types and formats on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats) The [`<audio>`](element/audio) and [`<video>`](element/video) elements allow you to play audio and video media natively within your content without the need for external software support.
[HTML content categories](content_categories) HTML is comprised of several kinds of content, each of which is allowed to be used in certain contexts and is disallowed in others. Similarly, each context has a set of other content categories it can contain and elements that can or can't be used in them. This is a guide to these categories.
[Quirks mode and standards mode](quirks_mode_and_standards_mode) Historical information on quirks mode and standards mode.
Related topics
--------------
[Applying color to HTML elements using CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Colors/Applying_color) This article covers most of the ways you use CSS to add color to HTML content, listing what parts of HTML documents can be colored and what CSS properties to use when doing so. Includes examples, links to palette-building tools, and more.
html Viewport meta tag Viewport meta tag
=================
This article describes how to use the "viewport" `<meta>` tag to control the viewport's size and shape.
Background
----------
The browser's [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport) is the area of the window in which web content can be seen. This is often not the same size as the rendered page, in which case the browser provides scrollbars for the user to scroll around and access all the content.
Some mobile devices and other narrow screens render pages in a virtual window or viewport, which is usually wider than the screen, and then shrink the rendered result down so it can all be seen at once. Users can then pan and zoom to see different areas of the page. For example, if a mobile screen has a width of 640px, pages might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 640px space.
This is done because not all pages are optimized for mobile and break (or at least look bad) when rendered at a small viewport width. This virtual viewport is a way to make non-mobile-optimized sites in general look better on narrow screen devices.
However, this mechanism is not so good for pages that are optimized for narrow screens using [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) — if the virtual viewport is 980px for example, media queries that kick in at 640px or 480px or less will never be used, limiting the effectiveness of such responsive design techniques. The viewport meta tag mitigates this problem of virtual viewport on narrow screen devices.
Viewport basics
---------------
A typical mobile-optimized site contains something like the following:
```
<meta name="viewport" content="width=device-width, initial-scale=1" />
```
Not all devices are the same width; you should make sure that your pages work well in a large variation of screen sizes and orientations.
The basic properties of the "viewport" `<meta>` tag include:
`width` Controls the size of the viewport. It can be set to a specific number of pixels like `width=600` or to the special value `device-width`, which is [100vw](https://developer.mozilla.org/en-US/docs/Web/CSS/length#relative_length_units_based_on_viewport), or 100% of the viewport width. Minimum: `1`. Maximum: `10000`. Negative values: ignored.
`height` Controls the size of the viewport. It can be set to a specific number of pixels like `height=400` or to the special value `device-height`, which is [100vh](https://developer.mozilla.org/en-US/docs/Web/CSS/length#vh), or 100% of the viewport height. Minimum: `1`. Maximum: `10000`. Negative values: ignored.
`initial-scale` Controls the zoom level when the page is first loaded. Minimum: `0.1`. Maximum: `10`. Default: `1`. Negative values: ignored.
`minimum-scale` Controls how much zoom out is allowed on the page. Minimum: `0.1`. Maximum: `10`. Default: `0.1`. Negative values: ignored.
`maximum-scale` Controls how much zoom in is allowed on the page. Any value less than 3 fails accessibility. Minimum: `0.1`. Maximum: `10`. Default: `10`. Negative values: ignored.
`user-scalable` Controls whether zoom in and zoom out actions are allowed on the page. Valid values: `0`, `1`, `yes`, or `no`. Default: `1`, which is the same as `yes`. Setting the value to `0`, which is the same as `no`, is against Web Content Accessibility Guidelines (WCAG).
`interactive-widget` Specifies the effect that interactive UI widgets, such as a virtual keyboard, have on the page's viewports. Valid values: `resizes-visual`, `resizes-content`, or `overlays-content`. Default: `resizes-visual`.
**Warning:** Usage of `user-scalable=no` can cause accessibility issues to users with visual impairments such as low vision. [WCAG](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.4_make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background) requires a minimum of 2× scaling; however, the best practice is to enable a 5× zoom.
Screen density
--------------
Screen resolutions have risen to the size that individual pixels are indistinguishable by the human eye. For example, smartphones often have small screens with resolutions upwards of 1920–1080 pixels (≈400dpi). Because of this, many browsers can display their pages in a smaller physical size by translating multiple hardware pixels for each CSS "pixel". Initially, this caused usability and readability problems on many touch-optimized websites.
On high dpi screens, pages with `initial-scale=1` will effectively be zoomed by browsers. Their text will be smooth and crisp, but their bitmap images may not take advantage of the full screen resolution. To get sharper images on these screens, web developers may want to design images – or whole layouts – at a higher scale than their final size and then scale them down using CSS or viewport properties.
The default pixel ratio depends on the display density. On a display with density less than 200dpi, the ratio is 1.0. On displays with density between 200 and 300dpi, the ratio is 1.5. For displays with density over 300dpi, the ratio is the integer floor (*density*/150dpi). Note that the default ratio is true only when the viewport scale equals 1. Otherwise, the relationship between CSS pixels and device pixels depends on the current zoom level.
Viewport width and screen width
-------------------------------
Sites can set their viewport to a specific size. For example, the definition `"width=320, initial-scale=1"` can be used to fit precisely onto a small phone display in portrait mode. This can cause problems when the browser renders a page at a larger size. To fix this, browsers will expand the viewport width if necessary to fill the screen at the requested scale. This is especially useful on large-screen devices.
For pages that set an initial or maximum scale, this means the `width` property actually translates into a *minimum* viewport width. For example, if your layout needs at least 500 pixels of width then you can use the following markup. When the screen is more than 500 pixels wide, the browser will expand the viewport (rather than zoom in) to fit the screen:
```
<meta name="viewport" content="width=500, initial-scale=1" />
```
Other [attributes](element/meta#attributes) that are available are `minimum-scale`, `maximum-scale`, and `user-scalable`. These properties affect the initial scale and width, as well as limiting changes in zoom level.
The effect of interactive UI widgets
------------------------------------
Interactive UI widgets of the browser can influence the size of the page's viewports. The most common such UI widget is a virtual keyboard. To control which resize behavior the browser should use, set the `interactive-widget` property.
Allowed values are:
`resizes-visual` The [visual viewport](https://developer.mozilla.org/en-US/docs/Glossary/Visual_Viewport) gets resized by the interactive widget.
`resizes-content` The [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport) gets resized by the interactive widget.
`overlays-content` Neither the [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport) nor the [visual viewport](https://developer.mozilla.org/en-US/docs/Glossary/Visual_Viewport) gets resized by the interactive widget.
When the [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport) gets resized, the initial [containing block](https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block) also gets resized, thereby affecting the computed size of [viewport units](https://developer.mozilla.org/en-US/docs/Web/CSS/length#viewport-percentage_lengths).
Common viewport sizes for mobile and tablet devices
---------------------------------------------------
If you want to know what mobile and tablet devices have which viewport widths, there is a comprehensive list of [mobile and tablet viewport sizes here](https://experienceleague.adobe.com/docs/target/using/experiences/vec/mobile-viewports.html). This gives information such as viewport width on portrait and landscape orientation as well as physical screen size, operating system and the pixel density of the device.
Specifications
--------------
| Specification |
| --- |
| [Unknown specification # viewport-meta](https://drafts.csswg.org/css-viewport/#viewport-meta) |
See also
--------
* Article: [Prepare for viewport resize behavior changes coming to Chrome on Android](https://developer.chrome.com/blog/viewport-resize-behavior/)
html Global attributes Global attributes
=================
**Global attributes** are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements.
Global attributes may be specified on all [HTML elements](element), *even those not specified in the standard*. That means that any non-standard elements must still permit these attributes, even though using those elements means that the document is no longer HTML5-compliant. For example, HTML5-compliant browsers hide content marked as `<foo hidden>…</foo>`, even though `<foo>` is not a valid HTML element.
In addition to the basic HTML global attributes, the following global attributes also exist:
* [**`xml:lang`**](#attr-xml:lang) and [**`xml:base`**](#attr-xml:base) — these are inherited from the XHTML specifications and deprecated, but kept for compatibility purposes.
* The ARIA [`role`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles) attribute and the multiple [`aria-*`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes) states and properties, used for ensuring accessibility.
* The [event handler](attributes#event_handler_attributes) attributes: `onabort`, `onautocomplete`, `onautocompleteerror`, `onblur`, `oncancel`, `oncanplay`, `oncanplaythrough`, `onchange`, `onclick`, `onclose`, `oncontextmenu`, `oncuechange`, `ondblclick`, `ondrag`, `ondragend`, `ondragenter`, `ondragleave`, `ondragover`, `ondragstart`, `ondrop`, `ondurationchange`, `onemptied`, `onended`, `onerror`, `onfocus`, `oninput`, `oninvalid`, `onkeydown`, `onkeypress`, `onkeyup`, `onload`, `onloadeddata`, `onloadedmetadata`, `onloadstart`, `onmousedown`, `onmouseenter`, `onmouseleave`, `onmousemove`, `onmouseout`, `onmouseover`, `onmouseup`, `onmousewheel`, `onpause`, `onplay`, `onplaying`, `onprogress`, `onratechange`, `onreset`, `onresize`, `onscroll`, `onseeked`, `onseeking`, `onselect`, `onshow`, `onsort`, `onstalled`, `onsubmit`, `onsuspend`, `ontimeupdate`, `ontoggle`, `onvolumechange`, `onwaiting`.
List of global attributes
-------------------------
[`accesskey`](global_attributes/accesskey) Provides a hint for generating a keyboard shortcut for the current element. This attribute consists of a space-separated list of characters. The browser should use the first one that exists on the computer keyboard layout.
[`autocapitalize`](global_attributes/autocapitalize) Controls whether and how text input is automatically capitalized as it is entered/edited by the user. It can have the following values:
* `off` or `none`, no autocapitalization is applied (all letters default to lowercase)
* `on` or `sentences`, the first letter of each sentence defaults to a capital letter; all other letters default to lowercase
* `words`, the first letter of each word defaults to a capital letter; all other letters default to lowercase
* `characters`, all letters should default to uppercase
[`autofocus`](global_attributes/autofocus) Indicates that an element is to be focused on page load, or as soon as the [`<dialog>`](element/dialog) it is part of is displayed. This attribute is a boolean, initially false.
[`class`](global_attributes/class) A space-separated list of the classes of the element. Classes allows CSS and JavaScript to select and access specific elements via the [class selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors) or functions like the method [`Document.getElementsByClassName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName).
[`contenteditable`](global_attributes/contenteditable) An [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. The attribute must take one of the following values:
* `true` or the *empty string*, which indicates that the element must be editable;
* `false`, which indicates that the element must not be editable.
[`contextmenu`](global_attributes/contextmenu) Deprecated
The [`id`](#id) of a [`<menu>`](element/menu) to use as the contextual menu for this element.
[`data-*`](global_attributes/data-*) Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the [HTML](index) and its [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM) representation that may be used by scripts. All such custom data are available via the [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface of the element the attribute is set on. The [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) property gives access to them.
[`dir`](global_attributes/dir) An enumerated attribute indicating the directionality of the element's text. It can have the following values:
* `ltr`, which means *left to right* and is to be used for languages that are written from the left to the right (like English);
* `rtl`, which means *right to left* and is to be used for languages that are written from the right to the left (like Arabic);
* `auto`, which lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then it applies that directionality to the whole element.
[`draggable`](global_attributes/draggable) An enumerated attribute indicating whether the element can be dragged, using the [Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). It can have the following values:
* `true`, which indicates that the element may be dragged
* `false`, which indicates that the element may not be dragged.
[`enterkeyhint`](global_attributes/enterkeyhint) Hints what action label (or icon) to present for the enter key on virtual keyboards.
[`exportparts`](global_attributes/exportparts) Experimental
Used to transitively export shadow parts from a nested shadow tree into a containing light tree.
[`hidden`](global_attributes/hidden) An enumerated attribute indicating that the element is not yet, or is no longer, *relevant*. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown.
[`id`](global_attributes/id) Defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).
[`inert`](global_attributes/inert) A boolean value that makes the browser disregard user input events for the element. Useful when click events are present.
[`inputmode`](global_attributes/inputmode) Provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. Used primarily on [`<input>`](element/input) elements, but is usable on any element while in [`contenteditable`](global_attributes#contenteditable) mode.
[`is`](global_attributes/is) Allows you to specify that a standard HTML element should behave like a registered custom built-in element (see [Using custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) for more details).
**Note:** The `item*` attributes are part of the [WHATWG HTML Microdata feature](https://html.spec.whatwg.org/multipage/microdata.html#microdata).
[`itemid`](global_attributes/itemid) The unique, global identifier of an item.
[`itemprop`](global_attributes/itemprop) Used to add properties to an item. Every HTML element may have an `itemprop` attribute specified, where an `itemprop` consists of a name and value pair.
[`itemref`](global_attributes/itemref) Properties that are not descendants of an element with the `itemscope` attribute can be associated with the item using an `itemref`. It provides a list of element ids (not `itemid`s) with additional properties elsewhere in the document.
[`itemscope`](global_attributes/itemscope) `itemscope` (usually) works along with [`itemtype`](global_attributes/itemtype) to specify that the HTML contained in a block is about a particular item. `itemscope` creates the Item and defines the scope of the `itemtype` associated with it. `itemtype` is a valid URL of a vocabulary (such as [schema.org](https://schema.org/)) that describes the item and its properties context.
[`itemtype`](global_attributes/itemtype) Specifies the URL of the vocabulary that will be used to define `itemprop`s (item properties) in the data structure. [`itemscope`](global_attributes/itemscope) is used to set the scope of where in the data structure the vocabulary set by `itemtype` will be active.
[`lang`](global_attributes/lang) Helps define the language of an element: the language that non-editable elements are in, or the language that editable elements should be written in by the user. The attribute contains one "language tag" (made of hyphen-separated "language subtags") in the format defined in [RFC 5646: Tags for Identifying Languages (also known as BCP 47)](https://datatracker.ietf.org/doc/html/rfc5646). [**xml:lang**](#attr-xml:lang) has priority over it.
[`nonce`](global_attributes/nonce) A cryptographic nonce ("number used once") which can be used by [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to determine whether or not a given fetch will be allowed to proceed.
[`part`](global_attributes/part) A space-separated list of the part names of the element. Part names allows CSS to select and style specific elements in a shadow tree via the [`::part`](https://developer.mozilla.org/en-US/docs/Web/CSS/::part) pseudo-element.
[`role`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles) Roles define the semantic meaning of content, allowing screen readers and other tools to present and support interaction with an object in a way that is consistent with user expectations of that type of object. `roles` are added to HTML elements using `role="role_type"`, where `role_type` is the name of a role in the ARIA specification.
[`slot`](global_attributes/slot) Assigns a slot in a [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) shadow tree to an element: An element with a `slot` attribute is assigned to the slot created by the [`<slot>`](element/slot) element whose [`name`](element/slot#attr-name) attribute's value matches that `slot` attribute's value.
[`spellcheck`](global_attributes/spellcheck) An enumerated attribute defines whether the element may be checked for spelling errors. It may have the following values:
* empty string or `true`, which indicates that the element should be, if possible, checked for spelling errors;
* `false`, which indicates that the element should not be checked for spelling errors.
[`style`](global_attributes/style) Contains [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) styling declarations to be applied to the element. Note that it is recommended for styles to be defined in a separate file or files. This attribute and the [`<style>`](element/style) element have mainly the purpose of allowing for quick styling, for example for testing purposes.
[`tabindex`](global_attributes/tabindex) An integer attribute indicating if the element can take input focus (is *focusable*), if it should participate to sequential keyboard navigation, and if so, at what position. It can take several values:
* a *negative value* means that the element should be focusable, but should not be reachable via sequential keyboard navigation;
* `0` means that the element should be focusable and reachable via sequential keyboard navigation, but its relative order is defined by the platform convention;
* a *positive value* means that the element should be focusable and reachable via sequential keyboard navigation; the order in which the elements are focused is the increasing value of the [**tabindex**](#tabindex). If several elements share the same tabindex, their relative order follows their relative positions in the document.
[`title`](global_attributes/title) Contains a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip.
[`translate`](global_attributes/translate) An enumerated attribute that is used to specify whether an element's attribute values and the values of its [`Text`](https://developer.mozilla.org/en-US/docs/Web/API/Text) node children are to be translated when the page is localized, or whether to leave them unchanged. It can have the following values:
* empty string or `yes`, which indicates that the element will be translated.
* `no`, which indicates that the element will not be translated.
[`virtualkeyboardpolicy`](global_attributes/virtualkeyboardpolicy) An [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute used to control the on-screen virtual keyboard behavior on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available, for elements that also uses the [`contenteditable`](global_attributes#contenteditable) attribute.
* `auto` or an *empty string*, which automatically shows the virtual keyboard when the element is focused or tapped.
* `manual`, which decouples focus and tap on the element from the virtual keyboard's state.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-accesskey-attribute](https://html.spec.whatwg.org/multipage/interaction.html#the-accesskey-attribute) |
| [HTML Standard # attr-autocapitalize](https://html.spec.whatwg.org/multipage/interaction.html#attr-autocapitalize) |
| [HTML Standard # attr-fe-autocomplete](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-autocomplete) |
| [HTML Standard # dom-fe-autofocus](https://html.spec.whatwg.org/multipage/interaction.html#dom-fe-autofocus) |
| [HTML Standard # global-attributes:classes-2](https://html.spec.whatwg.org/multipage/dom.html#global-attributes:classes-2) |
| [HTML Standard # attr-contenteditable](https://html.spec.whatwg.org/multipage/interaction.html#attr-contenteditable) |
| [HTML Standard # attr-data-\*](https://html.spec.whatwg.org/multipage/dom.html#attr-data-*) |
| [HTML Standard # the-dir-attribute](https://html.spec.whatwg.org/multipage/dom.html#the-dir-attribute) |
| [HTML Standard # the-draggable-attribute](https://html.spec.whatwg.org/multipage/dnd.html#the-draggable-attribute) |
| [HTML Standard # attr-enterkeyhint](https://html.spec.whatwg.org/multipage/interaction.html#attr-enterkeyhint) |
| [CSS Shadow Parts # element-attrdef-html-global-exportparts](https://w3c.github.io/csswg-drafts/css-shadow-parts/#element-attrdef-html-global-exportparts) |
| [HTML Standard # the-hidden-attribute](https://html.spec.whatwg.org/multipage/interaction.html#the-hidden-attribute) |
| [HTML Standard # global-attributes:the-id-attribute-2](https://html.spec.whatwg.org/multipage/dom.html#global-attributes:the-id-attribute-2) |
| [HTML Standard # the-inert-attribute](https://html.spec.whatwg.org/multipage/interaction.html#the-inert-attribute) |
| [HTML Standard # attr-inputmode](https://html.spec.whatwg.org/multipage/interaction.html#attr-inputmode) |
| [HTML Standard # attr-is](https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is) |
| [HTML Standard # attr-itemid](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemid) |
| [HTML Standard # names:-the-itemprop-attribute](https://html.spec.whatwg.org/multipage/microdata.html#names:-the-itemprop-attribute) |
| [HTML Standard # attr-itemref](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemref) |
| [HTML Standard # attr-itemscope](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemscope) |
| [HTML Standard # attr-itemtype](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemtype) |
| [HTML Standard # attr-lang](https://html.spec.whatwg.org/multipage/dom.html#attr-lang) |
| [HTML Standard # attr-nonce](https://html.spec.whatwg.org/multipage/urls-and-fetching.html#attr-nonce) |
| [CSS Shadow Parts # part-attr](https://w3c.github.io/csswg-drafts/css-shadow-parts/#part-attr) |
| [HTML Standard # attr-slot](https://html.spec.whatwg.org/multipage/dom.html#attr-slot) |
| [DOM Standard # ref-for-dom-element-slot①](#) |
| [HTML Standard # attr-spellcheck](https://html.spec.whatwg.org/multipage/interaction.html#attr-spellcheck) |
| [HTML Standard # the-style-attribute](https://html.spec.whatwg.org/multipage/dom.html#the-style-attribute) |
| [HTML Standard # attr-tabindex](https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex) |
| [HTML Standard # the-title-attribute](https://html.spec.whatwg.org/multipage/dom.html#the-title-attribute) |
| [HTML Standard # attr-translate](https://html.spec.whatwg.org/multipage/dom.html#attr-translate) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `accesskey` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `autocapitalize` | 43 | 79 | 83 | No | No | No | 43 | 43 | No | No | 5 | 4.0 |
| `autocomplete` | Yes
["In Chrome 66, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Chrome does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] | ≤79 | Yes | No | Yes | No | Yes
["In Chrome 66, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Chrome does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] | Yes
["In Chrome 66, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Chrome does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] | Yes | Yes | No | Yes
["In Samsung Internet 9.0, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Samsung Internet does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] |
| `autofocus` | 79
1-79
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 79
12-79
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 1
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 10
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 66
≤12.1-66
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 4
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 79
≤37-79
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 79
18-79
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 4
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 57
≤12.1-57
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 3.2
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 12.0
1.0-12.0
Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. |
| `class` | Yes | 12 | 32 | Yes | Yes | Yes | Yes | Yes | 32 | Yes | Yes | Yes |
| `contenteditable` | Yes | 12 | 3 | 5.5 | 9 | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `contextmenu` | No | No | 9-85 | No | No | No | No | No | 32-56
Support for the `contextmenu` attribute has been removed from Firefox for Android (See [bug 1424252](https://bugzil.la/1424252)). | No | No | No |
| `data_attributes` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `dir` | Yes | 79 | Yes | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `draggable` | Yes | 12 | 2 | Yes | 12 | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `enterkeyhint` | 77 | 79 | 94 | No | 66 | 13.1 | 77 | 77 | 94 | 57 | 13.4 | 12.0 |
| `exportparts` | 73 | 79 | 72 | No | 60 | 13.1 | 73 | 73 | 79 | ? | 13.4 | 11.0 |
| `hidden` | Yes | 12 | Yes | 11 | Yes | Yes | 4 | Yes | Yes | Yes | Yes | Yes |
| `id` | Yes | 12 | 32
Yes-32
`id` is a true global attribute only since Firefox 32. | Yes | Yes | Yes | Yes | Yes | 32
Yes-32
`id` is a true global attribute only since Firefox 32. | Yes | Yes | Yes |
| `inert` | 102 | 102 | No | No | 47 | 15.5 | 102 | 102 | No | 70 | 15.5 | 19.0 |
| `inputmode` | 66 | 79 | 95
17-23 | No | 53 | No | 66 | 66 | 79 | 47 | 12.2 | 9.0 |
| `is` | 67 | 79 | 63 | No | 54 | No
See [bug 182671](https://webkit.org/b/182671). | 67 | 67 | 63 | 48 | No
See [bug 182671](https://webkit.org/b/182671). | 9.0 |
| `itemid` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `itemprop` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `itemref` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `itemscope` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `itemtype` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `lang` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `nonce` | Yes | Yes | 31 | No | Yes | Yes | Yes | Yes | 31 | Yes | Yes | Yes |
| `part` | 73 | 79 | 72 | No | 60 | 13.1 | 73 | 73 | No | ? | 13.4 | 11.0 |
| `slot` | 53 | ≤79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `spellcheck` | 9 | 12 | Yes | 11 | Yes | Yes | 47 | 47 | 57 | 37 | 9.3 | 5.0 |
| `style` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `tabindex` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `title` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `translate` | 19 | 79 | No | No | 15 | 6 | 4.4 | 25 | No | 14 | 6 | 1.5 |
See also
--------
* [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element) interface that allows querying most global attributes.
| programming_docs |
html Block-level elements Block-level elements
====================
In this article, we'll examine HTML block-level elements and how they differ from [inline-level elements](inline_elements).
HTML (**HyperText Markup Language**) elements historically were categorized as either "block-level" elements or "inline-level" elements. Since this is a presentational characteristic it is nowadays specified by CSS in the [Flow Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout). A Block-level element occupies the entire horizontal space of its parent element (container), and vertical space equal to the height of its contents, thereby creating a "block".
Browsers typically display the block-level element with a newline both before and after the element. You can visualize them as a stack of boxes.
**Note:** A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
The following example demonstrates the block-level element's influence:
Block-level elements
--------------------
### HTML
```
<p>
This paragraph is a block-level element; its background has been colored to
display the paragraph's parent element.
</p>
```
### CSS
```
p {
background-color: #8abb55;
}
```
Usage
-----
* Block-level elements may appear only within a [`<body>`](element/body) element.
Block-level vs. inline
----------------------
There are a couple of key differences between block-level elements and inline elements:
Content model Generally, block-level elements may contain inline elements and (sometimes) other block-level elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
Default formatting By default, block-level elements begin on new lines, but inline elements can start anywhere in a line.
The distinction of block-level vs. inline elements was used in HTML specifications up to 4.01. Later, this binary distinction is replaced with a more complex set of [content categories](content_categories). While the "inline" category roughly corresponds to the category of [phrasing content](content_categories#phrasing_content), the "block-level" category doesn't directly correspond to any HTML content category, but *"block-level" and "inline" elements combined* correspond to the [flow content](content_categories#flow_content) in HTML. There are also additional categories, e.g. [interactive content](content_categories#interactive_content).
Elements
--------
The following is a complete list of all HTML "block-level" elements (although "block-level" is not technically defined for elements that are new in HTML5).
[`<address>`](element/address) Contact information.
[`<article>`](element/article) Article content.
[`<aside>`](element/aside) Aside content.
[`<blockquote>`](element/blockquote) Long ("block") quotation.
[`<details>`](element/details) Disclosure widget.
[`<dialog>`](element/dialog) Dialog box.
[`<dd>`](element/dd) Describes a term in a description list.
[`<div>`](element/div) Document division.
[`<dl>`](element/dl) Description list.
[`<dt>`](element/dt) Description list term.
[`<fieldset>`](element/fieldset) Field set label.
[`<figcaption>`](element/figcaption) Figure caption.
[`<figure>`](element/figure) Groups media content with a caption (see [`<figcaption>`](element/figcaption)).
[`<footer>`](element/footer) Section or page footer.
[`<form>`](element/form) Input form.
[`<h1>`](element/heading_elements), [`<h2>`](element/heading_elements), [`<h3>`](element/heading_elements), [`<h4>`](element/heading_elements), [`<h5>`](element/heading_elements), [`<h6>`](element/heading_elements)
Heading levels 1-6.
[`<header>`](element/header) Section or page header.
[`<hgroup>`](element/hgroup) Groups header information.
[`<hr>`](element/hr) Horizontal rule (dividing line).
[`<li>`](element/li) List item.
[`<main>`](element/main) Contains the central content unique to this document.
[`<nav>`](element/nav) Contains navigation links.
[`<ol>`](element/ol) Ordered list.
[`<p>`](element/p) Paragraph.
[`<pre>`](element/pre) Preformatted text.
[`<section>`](element/section) Section of a web page.
[`<table>`](element/table) Table.
[`<ul>`](element/ul) Unordered list.
See also
--------
* [Inline elements](inline_elements)
* [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display)
* [Block and Inline Layout in Normal Flow](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/Block_and_Inline_Layout_in_Normal_Flow)
html Date and time formats used in HTML Date and time formats used in HTML
==================================
Certain HTML elements use date and/or time values. The formats of the strings that specify these values are described in this article.
Elements that use such formats include certain forms of the [`<input>`](element/input) element that let the user choose or specify a date, time, or both, as well as the [`<ins>`](element/ins) and [`<del>`](element/del) elements, whose [`datetime`](element/ins#attr-datetime) attribute specifies the date or date and time at which the insertion or deletion of content occurred.
For `<input>`, the values of [`type`](element/input#attr-type) that return a [`value`](global_attributes#value) which contains a string representing a date and/or time are:
* [`date`](element/input/date)
* [`datetime-local`](element/input/datetime-local)
* [`month`](element/input/month)
* [`time`](element/input/time)
* [`week`](element/input/week)
Examples
--------
Before getting into the intricacies of how date and time strings are written and parsed in HTML, here are some examples that should give you a good idea what the more commonly-used date and time string formats look like.
Example HTML date and time strings| String | Date and/or time |
| --- | --- |
| `2005-06-07` | June 7, 2005 | [[details]](date_and_time_formats#date_strings) |
| `08:45` | 8:45 AM | [[details]](date_and_time_formats#time_strings) |
| `08:45:25` | 8:45 AM and 25 seconds | [[details]](date_and_time_formats#time_strings) |
| `0033-08-04T03:40` | 3:40 AM on August 4, 33 | [[details]](date_and_time_formats#local_date_and_time_strings) |
| `1977-04-01T14:00:30` | 30 seconds after 2:00 PM on April 1, 1977 | [[details]](date_and_time_formats#local_date_and_time_strings) |
| `1901-01-01T00:00Z` | Midnight UTC on January 1, 1901 | [[details]](date_and_time_formats#global_date_and_time_strings) |
| `1901-01-01T00:00:01-04:00` | 1 second past midnight Eastern Standard Time (EST) on January 1, 1901 | [[details]](date_and_time_formats#global_date_and_time_strings) |
Basics
------
Before looking at the various formats of date and time related strings used by HTML elements, it is helpful to understand a few fundamental facts about the way they're defined. HTML uses a variation of the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard for its date and time strings. It's worth reviewing the descriptions of the formats you're using in order to ensure that your strings are in fact compatible with HTML, as the HTML specification includes algorithms for parsing these strings that is actually more precise than ISO 8601, so there can be subtle differences in how date and time strings are expected to look.
### Character set
Dates and times in HTML are always strings which use the [ASCII](https://en.wikipedia.org/wiki/ASCII) character set.
### Year numbers
In order to simplify the basic format used for date strings in HTML, the specification requires that all years be given using the modern (or **proleptic**) [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar). While user interfaces may allow entry of dates using other calendars, the underlying value always uses the Gregorian calendar.
While the Gregorian calendar wasn't created until the year 1582 (replacing the similar Julian calendar), for HTML's purposes, the Gregorian calendar is extended back to the year 1 C.E. Make sure any older dates account for this.
For the purposes of HTML dates, years are always at least four digits long; years prior to the year 1000 are padded with leading zeroes ("`0`"), so the year 72 is written as `0072`. Years prior to the year 1 C.E. are not supported, so HTML doesn't support years 1 B.C.E. (1 B.C.) or earlier.
A year is normally 365 days long, except during **[leap years](#leap_years)**.
#### Leap years
A **leap year** is any year which is divisible by 400 *or* the year is divisible by 4 but not by 100. Although the calendar year is normally 365 days long, it actually takes the planet Earth approximately 365.2422 days to complete a single orbit around the sun. Leap years help to adjust the calendar to keep it synchronized with the actual position of the planet in its orbit. Adding a day to the year every four years essentially makes the average year 365.25 days long, which is close to correct.
The adjustments to the algorithm (taking a leap year when the year can be divided by 400, and skipping leap years when the year is divisible by 100) help to bring the average even closer to the correct number of days (365.2425 days). Scientists occasionally add leap seconds to the calendar (seriously) to handle the remaining three ten-thousandths of a day and to compensate for the gradual, naturally occurring slowing of Earth's rotation.
While month `02`, February, normally has 28 days, it has 29 days in leap years.
### Months of the year
There are 12 months in the year, numbered 1 through 12. They are always represented by a two-digit ASCII string whose value ranges from `01` through `12`. See the table in the section [Days of the month](#days_of_the_month) for the month numbers and their corresponding names (and lengths in days).
### Days of the month
Month numbers 1, 3, 5, 7, 8, 10, and 12 are 31 days long. Months 4, 6, 9, and 11 are 30 days long. Month 2, February, is 28 days long most years, but is 29 days long in leap years. This is detailed in the following table.
The months of the year and their lengths in days| Month number | Name (English) | Length in days |
| --- | --- | --- |
| 01 | January | 31 |
| 02 | February | 28 (29 in leap years) |
| 03 | March | 31 |
| 04 | April | 30 |
| 05 | May | 31 |
| 06 | June | 30 |
| 07 | July | 31 |
| 08 | August | 31 |
| 09 | September | 30 |
| 10 | October | 31 |
| 11 | November | 30 |
| 12 | December | 31 |
Week strings
------------
A week string specifies a week within a particular year. A **valid week string** consists of a valid [year number](#year_numbers), followed by a hyphen character ("`-`", or U+002D), then the capital letter "`W`" (U+0057), followed by a two-digit week of the year value.
The week of the year is a two-digit string between `01` and `53`. Each week begins on Monday and ends on Sunday. That means it's possible for the first few days of January to be considered part of the previous week-year, and for the last few days of December to be considered part of the following week-year. The first week of the year is the week that contains the *first Thursday of the year*. For example, the first Thursday of 1953 was on January 1, so that week—beginning on Monday, December 29—is considered the first week of the year. Therefore, December 30, 1952 occurs during the week `1953-W01`.
A year has 53 weeks if:
* The first day of the calendar year (January 1) is a Thursday **or**
* The first day of the year (January 1) is a Wednesday and the year is a [leap year](#leap_years)
All other years have 52 weeks.
| Week string | Week and year (Date range) |
| --- | --- |
| `2001-W37` | Week 37, 2001 (September 10-16, 2001) |
| `1953-W01` | Week 1, 1953 (December 29, 1952-January 4, 1953) |
| `1948-W53` | Week 53, 1948 (December 27, 1948-January 2, 1949) |
| `1949-W01` | Week 1, 1949 (January 3-9, 1949) |
| `0531-W16` | Week 16, 531 (April 13-19, 531) |
| `0042-W04` | Week 4, 42 (January 21-27, 42) |
Note that both the year and week numbers are padded with leading zeroes, with the year padded to four digits and the week to two.
Month strings
-------------
A month string represents a specific month in time, rather than a generic month of the year. That is, rather than representing "January," an HTML month string represents a month and year paired, like "January 1972."
A **valid month string** consists of a valid [year number](#year_numbers) (a string of at least four digits), followed by a hyphen character ("`-`", or U+002D), followed by a two-digit numeric [month number](#months_of_the_year), where `01` represents January and `12` represents December.
| Month string | Month and year |
| --- | --- |
| `17310-09` | September, 17310 |
| `2019-01` | January, 2019 |
| `1993-11` | November, 1993 |
| `0571-04` | April, 571 |
| `0001-07` | July, 1 C.E. |
Notice that all years are at least four characters long; years that are fewer than four digits long are padded with leading zeroes.
Date strings
------------
A valid date string consists of a [month string](#month_strings), followed by a hyphen character ("`-`", or U+002D), followed by a two-digit [day of the month](#days_of_the_month).
| Date string | Full date |
| --- | --- |
| `1993-11-01` | November 1, 1993 |
| `1066-10-14` | October 14, 1066 |
| `0571-04-22` | April 22, 571 |
| `0062-02-05` | February 5, 62 |
Time strings
------------
A time string can specify a time with precision to the minute, second, or to the millisecond. Specifying only the hour or minute isn't permitted. A **valid time string** minimally consists of a two-digit hour followed by a colon ("`:`", U+003A), then a two-digit minute. The minute may optionally be followed by another colon and a two-digit number of seconds. Milliseconds may be specified, optionally, by adding a decimal point character ("`.`", U+002E) followed by one, two, or three digits.
There are some additional basic rules:
* The hour is always specified using the 24-hour clock, with `00` being midnight and 11 PM being `23`. No values outside the range `00` – `23` are permitted.
* The minute must be a two-digit number between `00` and `59`. No values outside that range are allowed.
* If the number of seconds is omitted (to specify a time accurate only to the minute), no colon should follow the number of minutes.
* If specified, the integer portion of the number of seconds must be between `00` and `59`. You *cannot* specify leap seconds by using values like `60` or `61`.
* If the number of seconds is specified and is an integer, it must not be followed by a decimal point.
* If a fraction of a second is included, it may be from one to three digits long, indicating the number of milliseconds. It follows the decimal point placed after the seconds component of the time string.
| Time string | Time |
| --- | --- |
| `00:00:30.75` | 12:00:30.75 AM (30.75 seconds after midnight) |
| `12:15` | 12:15 PM |
| `13:44:25` | 1:44:25 PM (25 seconds after 1:44 PM) |
Local date and time strings
---------------------------
A valid [`datetime-local`](element/input/datetime-local) string consists of a `date` string and a `time` string concatenated together with either the letter "`T`" or a space character separating them. No information about the time zone is included in the string; the date and time is presumed to be in the user's local time zone.
When you set the [`value`](element/input#attr-value) of a `datetime-local` input, the string is **normalized** into a standard form. Normalized `datetime` strings always use the letter "`T`" to separate the date and the time, and the time portion of the string is as short as possible. This is done by leaving out the seconds component if its value is `:00`.
Examples of valid `datetime-local` strings | Date/time string | Normalized date/time string | Actual date and time |
| --- | --- | --- |
| `1986-01-28T11:38:00.01` | `1986-01-28T11:38:00.01` | January 28, 1986 at 11:38:00.01 AM |
| `1986-01-28 11:38:00.010` | `1986-01-28T11:38:00.01` Note that after normalization, this is the same string as the previous `datetime-local` string. The space has been replaced with the "`T`" character and the trailing zero in the fraction of a second has been removed to make the string as short as possible. | January 28, 1986 at 11:38:00.01 AM |
| `0170-07-31T22:00:00` | `0170-07-31T22:00` Note that the normalized form of this date drops the "`:00`" indicating the number of seconds to be zero, because the seconds are optional when zero, and the normalized string minimizes the length of the string. | July 31, 170 at 10:00 PM |
Global date and time strings
----------------------------
A global date and time string specifies a date and time as well as the time zone in which it occurs. A **valid global date and time string** is the same format as a [local date and time string](#local_date_and_time_strings), except it has a time zone string appended to the end, following the time.
### Time zone offset string
A time zone offset string specifies the offset in either a positive or a negative number of hours and minutes from the standard time base. There are two standard time bases, which are very close to the same, but not exactly the same:
* For dates after the establishment of [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) (UTC) in the early 1960s, the time base is `Z` and the offset indicates a particular time zone's offset from the time at the prime meridian at 0º longitude (which passes through the Royal Observatory at Greenwich, England).
* For dates prior to UTC, the time base is instead expressed in terms of [UT1](https://en.wikipedia.org/wiki/UT1), which is the contemporary Earth solar time at the prime meridian.
The time zone string is appended immediately following the time in the date and time string. You can specify "`Z`" as the time zone offset string to indicate that the time is specified in UTC. Otherwise, the time zone string is constructed as follows:
1. A character indicating the sign of the offset: the plus character ("`+`", or U+002B) for time zones to the east of the prime meridian or the minus character ("`-`", or U+002D) for time zones to the west of the prime meridian.
2. A two-digit number of hours that the time zone is offset from the prime meridian. This value must be between `00` and `23`.
3. An optional colon ("`:`") character.
4. A two-digit number of minutes past the hour; this value must be between `00` and `59`.
While this format allows for time zones between -23:59 and +23:59, the current range of time zone offsets is -12:00 to +14:00, and no time zones are currently offset from the hour by anything other than `00`, `30`, or `45` minutes. This may change at more or less anytime, since countries are free to tamper with their time zones at any time and in any way they wish to do so.
Examples of valid global date and time strings| Global date and time string | Actual global date and time | Date and time at prime meridian |
| --- | --- | --- |
| `2005-06-07T00:00Z` | June 7, 2005 at midnight UTC | June 7, 2005 at midnight |
| `1789-08-22T12:30:00.1-04:00` | August 22, 1789 at a tenth of a second past 12:30 PM Eastern Daylight Time (EDT) | August 22, 1789 at a tenth of a second past 4:30 PM |
| `3755-01-01 00:00+10:00` | January 1, 3755 at midnight Australian Eastern Standard Time (AEST) | December 31, 3754 at 2:00 PM |
See also
--------
* [`<input>`](element/input)
* [`<ins>`](element/ins) and [`<del>`](element/del): see the `datetime` attribute, which specifies either a date or a local date and time at which the content was inserted or deleted
* [The ISO 8601 specification](https://www.iso.org/iso-8601-date-and-time-format.html)
* [Numbers and Dates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates) in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
* The JavaScript [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object
* The [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object for formatting dates and times for a given locale
| programming_docs |
html HTML reference HTML reference
==============
This [HTML](index) reference describes all **elements** and **attributes** of HTML, including **global attributes** that apply to all elements.
[HTML element reference](element) This page lists all the HTML elements, which are created using tags.
[HTML attribute reference](attributes) Elements in HTML have attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want.
[Global attributes](global_attributes) Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements.
[Link types](link_types) In HTML, the following link types indicate the relationship between two documents, in which one links to the other using an [`<a>`](element/a), [`<area>`](element/area), or [`<link>`](element/link) element.
[Content categories](content_categories) Every HTML element is a member of one or more content categories — these categories group elements that share common characteristics.
[Date and time formats used in HTML](date_and_time_formats) Certain HTML elements allow you to specify dates and/or times as the value or as the value of an attribute. These include the date and time variations of the [`<input>`](element/input) element as well as the [`<ins>`](element/ins) and [`<del>`](element/del) elements.
html Microdata Microdata
=========
Microdata is part of the [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG) HTML Standard and is used to nest metadata within existing content on web pages. Search engines and web crawlers can extract and process microdata from a web page and use it to provide a richer browsing experience for users. Search engines benefit greatly from direct access to this structured data because it allows search engines to understand the information on web pages and provide more relevant results to users. Microdata uses a supporting vocabulary to describe an item and name-value pairs to assign values to its properties. Microdata is an attempt to provide a simpler way of annotating HTML elements with machine-readable tags than the similar approaches of using RDFa and classic microformats.
At a high level, microdata consists of a group of name-value pairs. The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.
* To create an item, the `itemscope` attribute is used.
* To add a property to an item, the `itemprop` attribute is used on one of the item's descendants.
Vocabularies
------------
Google and other major search engines support the [Schema.org](https://schema.org) vocabulary for structured data. This vocabulary defines a standard set of type names and property names, for example, [Schema.org Music Event](https://schema.org/MusicEvent) indicates a concert performance, with [`startDate`](https://schema.org/startDate) and [`location`](https://schema.org/location) properties to specify the concert's key details. In this case, [Schema.org Music Event](https://schema.org/MusicEvent) would be the URL used by `itemtype` and `startDate` and location would be `itemprop`'s that [Schema.org Music Event](https://schema.org/MusicEvent) defines.
**Note:** More about itemtype attributes can be found at <https://schema.org/Thing>.
Microdata vocabularies provide the semantics or meaning of an *`Item`*. Web developers can design a custom vocabulary or use vocabularies available on the web, such as the widely used [schema.org](https://schema.org) vocabulary. A collection of commonly used markup vocabularies are provided by Schema.org.
Commonly used vocabularies:
* Creative works: [CreativeWork](https://schema.org/CreativeWork), [Book](https://schema.org/Book), [Movie](https://schema.org/Movie), [MusicRecording](https://schema.org/MusicRecording), [Recipe](https://schema.org/Recipe), [TVSeries](https://schema.org/TVSeries)
* Embedded non-text objects: [AudioObject](https://schema.org/AudioObject), [ImageObject](https://schema.org/ImageObject), [VideoObject](https://schema.org/VideoObject)
* [`Event`](https://schema.org/Event)
* [Health and medical types](https://schema.org/docs/meddocs.html): Notes on the health and medical types under [MedicalEntity](https://schema.org/MedicalEntity)
* [`Organization`](https://schema.org/Organization)
* [`Person`](https://schema.org/Person)
* [`Place`](https://schema.org/Place), [LocalBusiness](https://schema.org/LocalBusiness), [Restaurant](https://schema.org/Restaurant)
* [`Product`](https://schema.org/Product), [Offer](https://schema.org/Offer), [AggregateOffer](https://schema.org/AggregateOffer)
* [`Review`](https://schema.org/Review), [AggregateRating](https://schema.org/AggregateRating)
* [`Action`](https://schema.org/Action)
* [`Thing`](https://schema.org/Thing)
* [`Intangible`](https://schema.org/Intangible)
Major search engine operators like Google, Microsoft, and Yahoo! rely on the [schema.org](https://schema.org/) vocabulary to improve search results. For some purposes, an ad hoc vocabulary is adequate. For others, a vocabulary will need to be designed. Where possible, authors are encouraged to re-use existing vocabularies, as this makes content re-use easier.
Localization
------------
In some cases, search engines covering specific regions may provide locally-specific extensions of microdata. For example, [Yandex](https://yandex.com/), a major search engine in Russia, supports microformats such as `hCard` (company contact information), `hRecipe` (food recipe), `hReview` (market reviews) and `hProduct` (product data) and provides its own format for the definition of the terms and encyclopedic articles. This extension was made to solve transliteration problems between the Cyrillic and Latin alphabets. Due to the implementation of additional marking parameters of Schema's vocabulary, the indexation of information in Russian-language web-pages became considerably more successful.
Global attributes
-----------------
[`itemid`](global_attributes/itemid) – The unique, global identifier of an item.
[`itemprop`](global_attributes/itemprop) – Used to add properties to an item. Every HTML element may have an `itemprop` attribute specified, where an `itemprop` consists of a name and value pair.
[`itemref`](global_attributes/itemref) – Properties that are not descendants of an element with the `itemscope` attribute can be associated with the item using an **itemref**. `itemref` provides a list of element ids (not `itemid`s) with additional properties elsewhere in the document.
[`itemscope`](global_attributes/itemscope) – The `itemscope` attribute (usually) works along with [`itemtype`](global_attributes/itemtype) to specify that the HTML contained in a block is about a particular item. The `itemscope` attribute creates the *`Item`* and defines the scope of the itemtype associated with it. The `itemtype` attribute is a valid URL of a vocabulary (such as [schema.org](https://schema.org/)) that describes the item and its properties context.
[`itemtype`](global_attributes/itemtype) – Specifies the URL of the vocabulary that will be used to define `itemprop`'s (item properties) in the data structure. The [`itemscope`](global_attributes/itemscope) attribute is used to set the scope of where in the data structure the vocabulary set by `itemtype will be active.
Example
-------
### HTML
```
<div itemscope itemtype="https://schema.org/SoftwareApplication">
<span itemprop="name">Angry Birds</span> - REQUIRES
<span itemprop="operatingSystem">ANDROID</span><br />
<link
itemprop="applicationCategory"
href="https://schema.org/GameApplication" />
<div
itemprop="aggregateRating"
itemscope
itemtype="https://schema.org/AggregateRating">
RATING:
<span itemprop="ratingValue">4.6</span> (
<span itemprop="ratingCount">8864</span> ratings )
</div>
<div itemprop="offers" itemscope itemtype="https://schema.org/Offer">
Price: $<span itemprop="price">1.00</span>
<meta itemprop="priceCurrency" content="USD" />
</div>
</div>
```
### Structured data
| | | |
| --- | --- | --- |
| itemscope | itemtype | SoftwareApplication (https://schema.org/SoftwareApplication) |
| itemprop | name | Angry Birds |
| itemprop | operatingSystem | ANDROID |
| itemprop | applicationCategory | GameApplication (https://schema.org/GameApplication) |
| itemscope | itemprop[itemtype] | aggregateRating [AggregateRating] |
| itemprop | ratingValue | 4.6 |
| itemprop | ratingCount | 8864 |
| itemscope | itemprop[itemtype] | offers [Offer] |
| itemprop | price | 1.00 |
| itemprop | priceCurrency | USD |
### Result
**Note:** A handy tool for extracting microdata structures from HTML is Google's [Structured Data Testing Tool](https://developers.google.com/search/docs/advanced/structured-data/intro-structured-data). Try it on the HTML shown above.
Browser compatibility
---------------------
Supported in Firefox 16. Removed in Firefox 49.
See also
--------
* [Global Attributes](global_attributes)
html Inline elements Inline elements
===============
In this article, we'll examine HTML inline-level elements and how they differ from [block-level elements](block-level_elements).
HTML (**HyperText Markup Language**) elements historically were categorized as either "block-level" elements or "inline-level" elements. Since this is a presentational characteristic it is nowadays specified by CSS in the [Flow Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout).
Inline elements are those which only occupy the space bounded by the tags defining the element, instead of breaking the flow of the content.
**Note:** An inline element does not start on a new line and only takes up as much width as necessary.
Inline vs. block-level elements: a demonstration
------------------------------------------------
This is most easily demonstrated with a simple example. First, some simple CSS that we'll be using:
```
.highlight {
background-color: #ee3;
}
```
### Inline
Let's look at the following example which demonstrates an inline element:
```
<div>
The following span is an <span class="highlight">inline element</span>; its
background has been colored to display both the beginning and end of the
inline element's influence.
</div>
```
In this example, the [`<div>`](element/div) block-level element contains some text. Within that text is a [`<span>`](element/span) element, which is an inline element. Because the `<span>` element is inline, the paragraph correctly renders as a single, unbroken text flow, like this:
### Block-level
Now let's change that `<span>` into a block-level element, such as [`<p>`](element/p):
```
<div>
The following paragraph is a
<p class="highlight">block-level element;</p>
its background has been colored to display both the beginning and end of the
block-level element's influence.
</div>
```
Rendered using the same CSS as before, we get:
See the difference? The `<p>` element totally changes the layout of the text, splitting it into three segments: the text before the `<p>`, then the `<p>`'s text, and finally the text following the `<p>`.
### Changing element levels
You can change the *visual presentation* of an element using the CSS [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) property. For example, by changing the value of `display` from `"inline"` to `"block"`, you can tell the browser to render the inline element in a block box rather than an inline box, and vice versa. However, doing this will not change the *category* and the *content model* of the element. For example, even if the `display` of the `span` element is changed to `"block"`, it still would not allow to nest a `div` element inside it.
Conceptual differences
----------------------
In brief, here are the basic conceptual differences between inline and block-level elements:
Content model Generally, inline elements may contain only data and other inline elements. An exception is the inline `a` element which may contain block level elements such as `div`.
**Note:** Links that wrap multiple lines of block-level content make for a poor-to-unusable experience for some assistive technologies and should be avoided.
Formatting By default, inline elements do not force a new line to begin in the document flow. Block elements, on the other hand, typically cause a line break to occur (although, as usual, this can be changed using CSS).
List of "inline" elements
-------------------------
The following elements are inline by default (although block and inline elements are no longer defined in HTML 5, use [content categories](content_categories) instead):
* [`<a>`](element/a)
* [`<abbr>`](element/abbr)
* [`<acronym>`](element/acronym)
* [`<audio>`](element/audio) (if it has visible controls)
* [`<b>`](element/b)
* [`<bdi>`](element/bdi)
* [`<bdo>`](element/bdo)
* [`<big>`](element/big)
* [`<br>`](element/br)
* [`<button>`](element/button)
* [`<canvas>`](element/canvas)
* [`<cite>`](element/cite)
* [`<code>`](element/code)
* [`<data>`](element/data)
* [`<datalist>`](element/datalist)
* [`<del>`](element/del)
* [`<dfn>`](element/dfn)
* [`<em>`](element/em)
* [`<embed>`](element/embed)
* [`<i>`](element/i)
* [`<iframe>`](element/iframe)
* [`<img>`](element/img)
* [`<input>`](element/input)
* [`<ins>`](element/ins)
* [`<kbd>`](element/kbd)
* [`<label>`](element/label)
* [`<map>`](element/map)
* [`<mark>`](element/mark)
* [`<meter>`](element/meter)
* [`<noscript>`](element/noscript)
* [`<object>`](element/object)
* [`<output>`](element/output)
* [`<picture>`](element/picture)
* [`<progress>`](element/progress)
* [`<q>`](element/q)
* [`<ruby>`](element/ruby)
* [`<s>`](element/s)
* [`<samp>`](element/samp)
* [`<script>`](element/script)
* [`<select>`](element/select)
* [`<slot>`](element/slot)
* [`<small>`](element/small)
* [`<span>`](element/span)
* [`<strong>`](element/strong)
* [`<sub>`](element/sub)
* [`<sup>`](element/sup)
* [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg)
* [`<template>`](element/template)
* [`<textarea>`](element/textarea)
* [`<time>`](element/time)
* [`<u>`](element/u)
* [`<tt>`](element/tt)
* [`<var>`](element/var)
* [`<video>`](element/video)
* [`<wbr>`](element/wbr)
See also
--------
* [Block-level elements](block-level_elements)
* [HTML element reference](element)
* [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display)
* [Content categories](content_categories)
* [Block and Inline Layout in Normal Flow](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/Block_and_Inline_Layout_in_Normal_Flow)
html Content categories Content categories
==================
Most [HTML](index) elements are a member of one or more **content categories** — these categories group elements that share common characteristics. This is a loose grouping (it doesn't actually create a relationship among elements of these categories), but they help define and describe the categories' shared behavior and their associated rules, especially when you come upon their intricate details. It's also possible for elements to not be a member of *any* of these categories.
There are three types of content categories:
* Main content categories, which describe common rules shared by many elements.
* Form-related content categories, which describe rules common to form-related elements.
* Specific content categories, which describe rare categories shared only by a few elements, sometimes only in a specific context.
**Note:** A more detailed discussion of these content categories and their comparative functionalities is beyond the scope of this article; for that, you may wish to read the [relevant portions of the HTML specification](https://html.spec.whatwg.org/multipage/dom.html#kinds-of-content).
Main content categories
-----------------------
### Metadata content
Elements belonging to the *metadata content* category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other *out-of-band* information.
Elements belonging to this category are [`<base>`](element/base), `<command>` Deprecated , [`<link>`](element/link), [`<meta>`](element/meta), [`<noscript>`](element/noscript), [`<script>`](element/script), [`<style>`](element/style) and [`<title>`](element/title).
### Flow content
Flow content is a broad category that encompasses most elements that can go inside the [`<body>`](element/body) element, including heading elements, sectioning elements, phrasing elements, embedding elements, interactive elements, and form-related elements. It also includes text nodes (but not those that only consist of white space characters).
The flow elements are:
* [`<a>`](element/a)
* [`<abbr>`](element/abbr)
* [`<address>`](element/address)
* [`<article>`](element/article)
* [`<aside>`](element/aside)
* [`<audio>`](element/audio)
* [`<b>`](element/b)
* [`<bdo>`](element/bdo)
* [`<bdi>`](element/bdi)
* [`<blockquote>`](element/blockquote)
* [`<br>`](element/br)
* [`<button>`](element/button)
* [`<canvas>`](element/canvas)
* [`<cite>`](element/cite)
* [`<code>`](element/code)
* `<command>` Deprecated
* [`<data>`](element/data)
* [`<datalist>`](element/datalist)
* [`<del>`](element/del)
* [`<details>`](element/details)
* [`<dfn>`](element/dfn)
* [`<div>`](element/div)
* [`<dl>`](element/dl)
* [`<em>`](element/em)
* [`<embed>`](element/embed)
* [`<fieldset>`](element/fieldset)
* [`<figure>`](element/figure)
* [`<footer>`](element/footer)
* [`<form>`](element/form)
* [`<h1>`](element/heading_elements)
* [`<h2>`](element/heading_elements)
* [`<h3>`](element/heading_elements)
* [`<h4>`](element/heading_elements)
* [`<h5>`](element/heading_elements)
* [`<h6>`](element/heading_elements)
* [`<header>`](element/header)
* [`<hgroup>`](element/hgroup)
* [`<hr>`](element/hr)
* [`<i>`](element/i)
* [`<iframe>`](element/iframe)
* [`<img>`](element/img)
* [`<input>`](element/input)
* [`<ins>`](element/ins)
* [`<kbd>`](element/kbd)
* [`<keygen>`](element/keygen) Deprecated
* [`<label>`](element/label)
* [`<main>`](element/main)
* [`<map>`](element/map)
* [`<mark>`](element/mark)
* `[<math>](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math)`
* [`<menu>`](element/menu)
* [`<meter>`](element/meter)
* [`<nav>`](element/nav)
* [`<noscript>`](element/noscript)
* [`<object>`](element/object)
* [`<ol>`](element/ol)
* [`<output>`](element/output)
* [`<p>`](element/p)
* [`<picture>`](element/picture)
* [`<pre>`](element/pre)
* [`<progress>`](element/progress)
* [`<q>`](element/q)
* [`<ruby>`](element/ruby)
* [`<s>`](element/s)
* [`<samp>`](element/samp)
* [`<script>`](element/script)
* [`<section>`](element/section)
* [`<select>`](element/select)
* [`<small>`](element/small)
* [`<span>`](element/span)
* [`<strong>`](element/strong)
* [`<sub>`](element/sub)
* [`<sup>`](element/sup)
* [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg)
* [`<table>`](element/table)
* [`<template>`](element/template)
* [`<textarea>`](element/textarea)
* [`<time>`](element/time)
* [`<u>`](element/u)
* [`<ul>`](element/ul)
* [`<var>`](element/var)
* [`<video>`](element/video)
* [`<wbr>`](element/wbr)
A few other elements belong to this category, but only if a specific condition is fulfilled:
* [`<area>`](element/area), if it is a descendant of a [`<map>`](element/map) element
* [`<link>`](element/link), if the [itemprop](global_attributes/itemprop) attribute is present
* [`<meta>`](element/meta), if the [itemprop](global_attributes/itemprop) attribute is present
* [`<style>`](element/style), if the `scoped` Deprecated attribute is present
### Sectioning content
Sectioning content is a subset of flow content, and can be used everywhere flow content is expected. Elements belonging to the sectioning content model create a [section in the current outline](element/heading_elements) that defines the scope of [`<header>`](element/header) elements, [`<footer>`](element/footer) elements, and [heading content](#heading_content).
Elements belonging to this category are [`<article>`](element/article), [`<aside>`](element/aside), [`<nav>`](element/nav), and [`<section>`](element/section).
### Heading content
Heading content is a subset of flow content, which defines the title of a section, whether marked by an explicit [sectioning content](#sectioning_content) element, or implicitly defined by the heading content itself. Heading content can be used everywhere flow content is expected.
Elements belonging to this category are [`<h1>`](element/heading_elements), [`<h2>`](element/heading_elements), [`<h3>`](element/heading_elements), [`<h4>`](element/heading_elements), [`<h5>`](element/heading_elements), [`<h6>`](element/heading_elements) and [`<hgroup>`](element/hgroup).
**Note:** Though likely to contain heading content, the [`<header>`](element/header) is not heading content itself.
**Note:** The [`<hgroup>`](element/hgroup) element is not recommended as it does not work properly with assistive technologies. It was removed from the W3C HTML specification prior to HTML 5 being finalized, but is still part of the WHATWG specification and is at least partially supported by most browsers.
### Phrasing content
Phrasing content is a subset of flow content that defines the text and the markup it contains, and can be used everywhere flow content is expected. Runs of phrasing content make up paragraphs.
Elements belonging to this category are:
* [`<abbr>`](element/abbr)
* [`<audio>`](element/audio)
* [`<b>`](element/b)
* [`<bdo>`](element/bdo)
* [`<br>`](element/br)
* [`<button>`](element/button)
* [`<canvas>`](element/canvas)
* [`<cite>`](element/cite)
* [`<code>`](element/code)
* `<command>` Deprecated
* [`<data>`](element/data)
* [`<datalist>`](element/datalist)
* [`<dfn>`](element/dfn)
* [`<em>`](element/em)
* [`<embed>`](element/embed)
* [`<i>`](element/i)
* [`<iframe>`](element/iframe)
* [`<img>`](element/img)
* [`<input>`](element/input)
* [`<kbd>`](element/kbd)
* [`<keygen>`](element/keygen) Deprecated
* [`<label>`](element/label)
* [`<mark>`](element/mark)
* `[<math>](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math)`
* [`<meter>`](element/meter)
* [`<noscript>`](element/noscript)
* [`<object>`](element/object)
* [`<output>`](element/output)
* [`<picture>`](element/picture)
* [`<progress>`](element/progress)
* [`<q>`](element/q)
* [`<ruby>`](element/ruby)
* [`<s>`](element/s)
* [`<samp>`](element/samp)
* [`<script>`](element/script)
* [`<select>`](element/select)
* [`<small>`](element/small)
* [`<span>`](element/span)
* [`<strong>`](element/strong)
* [`<sub>`](element/sub)
* [`<sup>`](element/sup)
* [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg)
* [`<textarea>`](element/textarea)
* [`<time>`](element/time)
* [`<u>`](element/u)
* [`<var>`](element/var)
* [`<video>`](element/video)
* [`<wbr>`](element/wbr) and plain text (not only consisting of white spaces characters).
A few other elements belong to this category, but only if a specific condition is fulfilled:
* [`<a>`](element/a), if it contains only phrasing content
* [`<area>`](element/area), if it is a descendant of a [`<map>`](element/map) element
* [`<del>`](element/del), if it contains only phrasing content
* [`<ins>`](element/ins), if it contains only phrasing content
* [`<link>`](element/link), if the [itemprop](global_attributes/itemprop) attribute is present
* [`<map>`](element/map), if it contains only phrasing content
* [`<meta>`](element/meta), if the [itemprop](global_attributes/itemprop) attribute is present
### Embedded content
Embedded content is a subset of flow content that imports another resource or inserts content from another markup language or namespace into the document, and can be used everywhere flow content is expected. Elements that belong to this category include:
* [`<audio>`](element/audio)
* [`<canvas>`](element/canvas)
* [`<embed>`](element/embed)
* [`<iframe>`](element/iframe)
* [`<img>`](element/img)
* `[<math>](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math)`
* [`<object>`](element/object)
* [`<picture>`](element/picture)
* [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg)
* [`<video>`](element/video).
### Interactive content
Interactive content is a subset of flow content that includes elements that are specifically designed for user interaction, and can be used everywhere flow content is expected. Elements that belong to this category include:
* [`<a>`](element/a)
* [`<button>`](element/button)
* [`<details>`](element/details)
* [`<embed>`](element/embed)
* [`<iframe>`](element/iframe)
* [`<keygen>`](element/keygen) Deprecated
* [`<label>`](element/label)
* [`<select>`](element/select), and [`<textarea>`](element/textarea).
Some elements belong to this category only under specific conditions:
* [`<audio>`](element/audio), if the [`controls`](element/audio#attr-controls) attribute is present
* [`<img>`](element/img), if the [`usemap`](element/img#attr-usemap) attribute is present
* [`<input>`](element/input), if the [type](element/input#type) attribute is not in the hidden state
* [`<object>`](element/object), if the [`usemap`](element/object#attr-usemap) attribute is present
* [`<video>`](element/video), if the [`controls`](element/video#attr-controls) attribute is present
### Palpable content
Content is palpable when it's neither empty nor hidden; it is content that is rendered and is substantive. Elements whose model is flow content should have at least one node which is palpable.
### Form-associated content
Form-associated content is a subset of flow content comprising elements that have a form owner, exposed by a **form** attribute, and can be used everywhere flow content is expected. A form owner is either the containing [`<form>`](element/form) element or the element whose id is specified in the **form** attribute.
* [`<button>`](element/button)
* [`<fieldset>`](element/fieldset)
* [`<input>`](element/input)
* [`<keygen>`](element/keygen) Deprecated
* [`<label>`](element/label)
* [`<meter>`](element/meter)
* [`<object>`](element/object)
* [`<output>`](element/output)
* [`<progress>`](element/progress)
* [`<select>`](element/select)
* [`<textarea>`](element/textarea)
This category contains several sub-categories:
listed Elements that are listed in the [`form.elements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements) and `fieldset.elements` collections. Contains [`<button>`](element/button), [`<fieldset>`](element/fieldset), [`<input>`](element/input), [`<keygen>`](element/keygen) Deprecated , [`<object>`](element/object), [`<output>`](element/output), [`<select>`](element/select), and [`<textarea>`](element/textarea).
labelable Elements that can be associated with [`<label>`](element/label) elements. Contains [`<button>`](element/button), [`<input>`](element/input), [`<keygen>`](element/keygen) Deprecated , [`<meter>`](element/meter), [`<output>`](element/output), [`<progress>`](element/progress), [`<select>`](element/select), and [`<textarea>`](element/textarea).
submittable Elements that can be used for constructing the form data set when the form is submitted. Contains [`<button>`](element/button), [`<input>`](element/input), [`<keygen>`](element/keygen) Deprecated , [`<object>`](element/object), [`<select>`](element/select), and [`<textarea>`](element/textarea).
resettable Elements that can be affected when a form is reset. Contains [`<input>`](element/input), [`<keygen>`](element/keygen) Deprecated , [`<output>`](element/output), [`<select>`](element/select), and [`<textarea>`](element/textarea).
Secondary categories
--------------------
There are some secondary classifications of elements that can be useful to be aware of as well.
### Script-supporting elements
**Script-supporting elements** are elements which don't directly contribute to the rendered output of a document. Instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts.
The script-supporting elements are:
* [`<script>`](element/script)
* [`<template>`](element/template)
Transparent content model
-------------------------
If an element has a transparent content model, then its contents must be structured such that they would be valid HTML 5, even if the transparent element were removed and replaced by the child elements.
For example, the [`<del>`](element/del) and [`<ins>`](element/ins) elements are transparent:
```
<p>
We hold these truths to be <del><em>sacred & undeniable</em></del>
<ins>self-evident</ins>.
</p>
```
If those elements were removed, this fragment would still be valid HTML (if not correct English).
```
<p>We hold these truths to be <em>sacred & undeniable</em> self-evident.</p>
```
| programming_docs |
html Quirks Mode Quirks Mode
===========
In the old days of the web, pages were typically written in two versions: One for Netscape Navigator, and one for Microsoft Internet Explorer. When the web standards were made at W3C, browsers could not just start using them, as doing so would break most existing sites on the web. Browsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites.
There are now three modes used by the layout engines in web browsers: quirks mode, limited-quirks mode, and no-quirks mode. In **quirks mode**, layout emulates behavior in Navigator 4 and Internet Explorer 5. This is essential in order to support websites that were built before the widespread adoption of web standards. In **no-quirks mode**, the behavior is (hopefully) the desired behavior described by the modern HTML and CSS specifications. In **limited-quirks mode**, there are only a very small number of quirks implemented.
The limited-quirks and no-quirks modes used to be called "almost-standards" mode and "full standards" mode, respectively. These names have been changed as the behavior is now standardized.
How do browsers determine which mode to use?
--------------------------------------------
For [HTML](index) documents, browsers use a DOCTYPE in the beginning of the document to decide whether to handle it in quirks mode or standards mode. To ensure that your page uses full standards mode, make sure that your page has a DOCTYPE like in this example:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
</head>
<body></body>
</html>
```
The DOCTYPE shown in the example, `<!DOCTYPE html>`, is the simplest possible, and the one recommended by current HTML standards. Earlier versions of the HTML standard recommended other variants, but all existing browsers today will use full standards mode for this DOCTYPE, even the dated Internet Explorer 6. There are no valid reasons to use a more complicated DOCTYPE. If you do use another DOCTYPE, you may risk choosing one which triggers almost standards mode or quirks mode.
Make sure you put the DOCTYPE right at the beginning of your HTML document. Anything before the DOCTYPE, like a comment or an XML declaration will trigger quirks mode in Internet Explorer 9 and older.
The only purpose of `<!DOCTYPE html>` is to activate no-quirks mode. Older versions of HTML standard DOCTYPEs provided additional meaning, but no browser ever used the DOCTYPE for anything other than switching between render modes.
See also a detailed description of [when different browsers choose various modes](https://hsivonen.fi/doctype/).
### XHTML
If you serve your page as [XHTML](https://developer.mozilla.org/en-US/docs/Glossary/XHTML) using the `application/xhtml+xml` MIME type in the `Content-Type` HTTP header, you do not need a DOCTYPE to enable standards mode, as such documents always use 'full standards mode'. Note however that serving your pages as `application/xhtml+xml` will cause Internet Explorer 8 to show a download dialog box for an unknown format instead of displaying your page, as the first version of Internet Explorer with support for XHTML is Internet Explorer 9.
If you serve XHTML-like content using the `text/html` MIME type, browsers will read it as HTML, and you will need the DOCTYPE to use standards mode.
How do I see which mode is used?
--------------------------------
If the page is rendered in quirks or limited-quirks mode, Firefox will log a warning to the console tab in the developer tools. If this warning is not shown, Firefox is using no-quirks mode.
The value of `document.compatMode` in JavaScript will show whether or not the document is in quirks mode. If its value us `"quirks"`, the document is in quirks mode. If it isn't, it will have value `"CSS1Compat"`.
html Constraint validation Constraint validation
=====================
The creation of web forms has always been a complex task. While marking up the form itself is easy, checking whether each field has a valid and coherent value is more difficult, and informing the user about the problem may become a headache. [HTML5](https://developer.mozilla.org/en-US/docs/Glossary/HTML5) introduced new mechanisms for forms: it added new semantic types for the [`<input>`](element/input) element and *constraint validation* to ease the work of checking the form content on the client side. Basic, usual constraints can be checked, without the need for JavaScript, by setting new attributes; more complex constraints can be tested using the Constraint Validation API.
For a basic introduction to these concepts, with examples, see the [Form validation tutorial](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation).
**Note:** HTML Constraint validation doesn't remove the need for validation on the *server side*. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent such as by bad people trying to trick your web application. Therefore, you need to always also validate input constraints on the server side, in a way that is consistent with what is done on the client side.
Intrinsic and basic constraints
-------------------------------
In HTML, basic constraints are declared in two ways:
* By choosing the most semantically appropriate value for the [`type`](element/input#attr-type) attribute of the [`<input>`](element/input) element, e.g., choosing the `email` type automatically creates a constraint that checks whether the value is a valid email address.
* By setting values on validation-related attributes, allowing basic constraints to be described in a simple way, without the need for JavaScript.
### Semantic input types
The intrinsic constraints for the [`type`](element/input#attr-type) attribute are:
| Input type | Constraint description | Associated violation |
| --- | --- | --- |
| [`<input type="URL">`](element/input/url) | The value must be an absolute [URL](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL), as defined in the [URL Living Standard](https://url.spec.whatwg.org/). | **[TypeMismatch](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/typeMismatch)** constraint violation |
| [`<input type="email">`](element/input/email) | The value must be a syntactically valid email address, which generally has the format `[email protected]` but can also be local such as `username@hostname`. | **[TypeMismatch](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/typeMismatch)** constraint violation |
For both of these input types, if the [`multiple`](element/input#attr-multiple) attribute is set, several values can be set, as a comma-separated list. If any of these do not satisfy the condition described here, the **Type mismatch** constraint violation is triggered.
Note that most input types don't have intrinsic constraints, as some are barred from constraint validation or have a sanitization algorithm transforming incorrect values to a correct default.
### Validation-related attributes
In addition to the `type` attribute described above, the following attributes are used to describe basic constraints:
| Attribute | Input types supporting the attribute | Possible values | Constraint description | Associated violation |
| --- | --- | --- | --- | --- |
| `[pattern](attributes/pattern)` | `text`, `search`, `url`, `tel`, `email`, `password` | A [JavaScript regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) (compiled with the [`global`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global), [`ignoreCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase), and [`multiline`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline) flags *disabled*) | The value must match the pattern. | [`patternMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/patternMismatch) constraint violation |
| `[min](attributes/min)` | `range`, `number` | A valid number | The value must be greater than or equal to the value. | `[rangeUnderflow](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeUnderflow)` constraint violation |
| `date`, `month`, `week` | A valid date |
| `datetime-local`, `time` | A valid date and time |
| `[max](attributes/max)` | `range`, `number` | A valid number | The value must be less than or equal to the value | `[rangeOverflow](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow)` constraint violation |
| `date`, `month`, `week` | A valid date |
| `datetime-local`, `time` | A valid date and time |
| `[required](attributes/required)` | `text`, `search`, `url`, `tel`, `email`, `password`, `date`, `datetime-local`, `month`, `week`, `time`, `number`, `checkbox`, `radio`, `file`; also on the [`<select>`](element/select) and [`<textarea>`](element/textarea) elements | *none* as it is a Boolean attribute: its presence means *true*, its absence means *false* | There must be a value (if set). | `[valueMissing](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/valueMissing)` constraint violation |
| `[step](attributes/step)` | `date` | An integer number of days | Unless the step is set to the `any` literal, the value must be **min** + an integral multiple of the step. | `[stepMismatch](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/stepMismatch)` constraint violation |
| `month` | An integer number of months |
| `week` | An integer number of weeks |
| `datetime-local`, `time` | An integer number of seconds |
| `range`, `number` | An integer |
| `[minlength](attributes/minlength)` | `text`, `search`, `url`, `tel`, `email`, `password`; also on the [`<textarea>`](element/textarea) element | An integer length | The number of characters (code points) must not be less than the value of the attribute, if non-empty. All newlines are normalized to a single character (as opposed to CRLF pairs) for [`<textarea>`](element/textarea). | `[tooShort](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooShort)` constraint violation |
| `[maxlength](attributes/maxlength)` | `text`, `search`, `url`, `tel`, `email`, `password`; also on the [`<textarea>`](element/textarea) element | An integer length | The number of characters (code points) must not exceed the value of the attribute. | `[tooLong](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooLong)` constraint violation |
Constraint validation process
-----------------------------
Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the [`<form>`](element/form) element itself. The constraint validation is done in the following ways:
* By a call to the `checkValidity()` or `reportValidity()` method of a form-associated DOM interface, ([`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement), [`HTMLSelectElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement), [`HTMLButtonElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement), [`HTMLOutputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement) or [`HTMLTextAreaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement)), which evaluates the constraints only on this element, allowing a script to get this information. The `checkValidity()` method returns a Boolean indicating whether the element's value passes its constraints. (This is typically done by the user-agent when determining which of the CSS pseudo-classes, [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) or [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid), applies.) In contrast, the `reportValidity()` method reports any constraint failures to the user.
* By a call to the `checkValidity()` or `reportValidity()` method on the [`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement) interface.
* By submitting the form itself.
Calling `checkValidity()` is called *statically* validating the constraints, while calling `reportValidity()` or submitting the form is called *interactively* validating the constraints.
**Note:**
* If the [`novalidate`](element/form#attr-novalidate) attribute is set on the [`<form>`](element/form) element, interactive validation of the constraints doesn't happen.
* Calling the `submit()` method on the [`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement) interface doesn't trigger a constraint validation. In other words, this method sends the form data to the server even if it doesn't satisfy the constraints. Call the `click()` method on a submit button instead.
Complex constraints using the Constraint Validation API
-------------------------------------------------------
Using JavaScript and the Constraint API, it is possible to implement more complex constraints, for example, constraints combining several fields, or constraints involving complex calculations.
Basically, the idea is to trigger JavaScript on some form field event (like **onchange**) to calculate whether the constraint is violated, and then to use the method `field.setCustomValidity()` to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an error and this string is the error message to display to the user.
### Constraint combining several fields: Postal code validation
The postal code format varies from one country to another. Not only do most countries allow an optional prefix with the country code (like `D-` in Germany, `F-` in France or Switzerland), but some countries have postal codes with only a fixed number of digits; others, like the UK, have more complex structures, allowing letters at some specific positions.
**Note:** This is not a comprehensive postal code validation library, but rather a demonstration of the key concepts.
As an example, we will add a script checking the constraint validation for this simple form:
```
<form>
<label for="ZIP">ZIP : </label>
<input type="text" id="ZIP" />
<label for="Country">Country : </label>
<select id="Country">
<option value="ch">Switzerland</option>
<option value="fr">France</option>
<option value="de">Germany</option>
<option value="nl">The Netherlands</option>
</select>
<input type="submit" value="Validate" />
</form>
```
This displays the following form:
First, we write a function checking the constraint itself:
```
function checkZIP() {
// For each country, defines the pattern that the ZIP has to follow
const constraints = {
ch: [
"^(CH-)?\\d{4}$",
"Switzerland ZIPs must have exactly 4 digits: e.g. CH-1950 or 1950",
],
fr: [
"^(F-)?\\d{5}$",
"France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012",
],
de: [
"^(D-)?\\d{5}$",
"Germany ZIPs must have exactly 5 digits: e.g. D-12345 or 12345",
],
nl: [
"^(NL-)?\\d{4}\\s\*([A-RT-Z][A-Z]|S[BCE-RT-Z])$",
"Netherland ZIPs must have exactly 4 digits, followed by 2 letters except SA, SD and SS",
],
};
// Read the country id
const country = document.getElementById("Country").value;
// Get the NPA field
const ZIPField = document.getElementById("ZIP");
// Build the constraint checker
const constraint = new RegExp(constraints[country][0], "");
console.log(constraint);
// Check it!
if (constraint.test(ZIPField.value)) {
// The ZIP follows the constraint, we use the ConstraintAPI to tell it
ZIPField.setCustomValidity("");
} else {
// The ZIP doesn't follow the constraint, we use the ConstraintAPI to
// give a message about the format required for this country
ZIPField.setCustomValidity(constraints[country][1]);
}
}
```
Then we link it to the **onchange** event for the [`<select>`](element/select) and the **oninput** event for the [`<input>`](element/input):
```
window.onload = () => {
document.getElementById("Country").onchange = checkZIP;
document.getElementById("ZIP").oninput = checkZIP;
};
```
### Limiting the size of a file before its upload
Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint Validation API, and especially the `field.setCustomValidity()` method, with another JavaScript API, here the File API.
Here is the HTML part:
```
<label for="FS">Select a file smaller than 75 kB : </label>
<input type="file" id="FS" />
```
This displays:
The JavaScript reads the file selected, uses the `File.size()` method to get its size, compares it to the (hard coded) limit, and calls the Constraint API to inform the browser if there is a violation:
```
function checkFileSize() {
const FS = document.getElementById("FS");
const files = FS.files;
// If there is (at least) one file selected
if (files.length > 0) {
if (files[0].size > 75 \* 1024) {
// Check the constraint
FS.setCustomValidity("The selected file must not be larger than 75 kB");
return;
}
}
// No custom constraint violation
FS.setCustomValidity("");
}
```
Finally, we hook the method with the correct event:
```
window.onload = () => {
document.getElementById("FS").onchange = checkFileSize;
};
```
Visual styling of constraint validation
---------------------------------------
Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled.
### Controlling the look of elements
The look of elements can be controlled via CSS pseudo-classes.
#### :required and :optional CSS pseudo-classes
The [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required) and [`:optional`](https://developer.mozilla.org/en-US/docs/Web/CSS/:optional) [pseudo-classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes) allow writing selectors that match form elements that have the [`required`](global_attributes#required) attribute, or that don't have it.
#### :placeholder-shown CSS pseudo-class
See [`:placeholder-shown`](https://developer.mozilla.org/en-US/docs/Web/CSS/:placeholder-shown).
#### :valid :invalid CSS pseudo-classes
The [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) [pseudo-classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes) are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly.
### Controlling the text of constraint violation
The following items can help with controlling the text of a constraint violation:
* The `setCustomValidity(message)` method on the following elements:
+ [`<fieldset>`](element/fieldset). Note: Setting a custom validity message on fieldset elements will not prevent form submission in most browsers.
+ [`<input>`](element/input)
+ [`<output>`](element/output)
+ [`<select>`](element/select)
+ Submit buttons (created with either a [`<button>`](element/button) element with the `submit` type, or an `input` element with the [submit](element/input/submit) type. Other types of buttons do not participate in constraint validation.
+ [`<textarea>`](element/textarea)
* The [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) interface describes the object returned by the `validity` property of the element types listed above. It represents various ways that an entered value can be invalid. Together, they help explain why an element's value fails to validate, if it's not valid.
| programming_docs |
html Link types Link types
==========
In HTML, link types indicate the relationship between two documents, in which one links to the other using an [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form), or [`<link>`](element/link) element.
List of the defined link types and their significance in HTML| Link Type | Description | Allowed in these elements | Not allowed in these elements |
| --- | --- | --- | --- |
| `alternate` | * If the element is [`<link>`](element/link) and the [`rel`](element/link#attr-rel) attribute also contains the `stylesheet` type, the link defines an [alternative style sheet](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets); in that case the [`title`](element/link#attr-title) attribute must be present and not be the empty string.
* If the [`type`](element/link#attr-type) is set to `application/rss+xml` or `application/atom+xml`, the link defines a [syndication feed](https://developer.mozilla.org/en-US/docs/Archive/RSS/Getting_Started/Syndicating). The first one defined on the page is the default.
* Otherwise, the link defines an alternative page, of one of these types:
+ for another medium, like a handheld device (if the [`media`](element/link#attr-media) attribute is set)
+ in another language (if the [`hreflang`](element/link#attr-hreflang) attribute is set),
+ in another format, such as a PDF (if the [`type`](element/link#attr-type) attribute is set)
+ a combination of these
| [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
| `archives` Deprecated | Defines a hyperlink to a document that contains an archive link to this one. For example, a blog entry could link to a monthly index page this way.**Note:** Although recognized, the singular `archive` is incorrect and must be avoided. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
| `author` | Defines a hyperlink to a page describing the author or providing a way to contact the author.**Note:** This may be a `mailto:` hyperlink, but this is not recommended on public pages as robot harvesters will quickly lead to a lot of spam sent to the address. In that case, it is better to lead to a page containing a contact form.Although recognized, the [`rev`](element/link#attr-rev) attribute on [`<a>`](element/a), [`<area>`](element/area) or [`<link>`](element/link) elements with a link type of `made` is incorrect and should be replaced by the [`rel`](element/link#attr-rel) attribute with this link type. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
| `bookmark` | Indicates that the hyperlink is a [permalink](https://developer.mozilla.org/en-US/docs/Permalink) for the nearest ancestor [`<article>`](element/article) element. If none, it is a permalink for the [section](element/heading_elements) that the element is most closely associated to.This allows for bookmarking a single article in a page containing multiple articles, such as on a monthly summary blog page, or a blog aggregator. | [`<a>`](element/a), [`<area>`](element/area) | [`<link>`](element/link), [`<form>`](element/form) |
| `canonical` | From Wikipedia, the free encyclopedia: [Canonical\_link\_element](https://en.wikipedia.org/wiki/Canonical_link_element)A canonical link element is an HTML element that helps webmasters prevent duplicate content issues by specifying the "canonical" or "preferred" version of a web page as part of search engine optimization. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `[dns-prefetch](link_types/dns-prefetch)` Experimental | Hints to the browser that a resource is needed, allowing the browser to do a DNS lookup and protocol handshaking before a user clicks the link. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `external` | Indicates that the hyperlink leads to a resource outside the site of the current page; that is, following the link will make the user leave the site. | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) | [`<link>`](element/link) |
| `first` Deprecated | Indicates that the hyperlink leads to the first resource of the *sequence* the current page is in.**Note:** Other link types related to linking resources in the same sequence are `last`, `prev`, `next`.Although recognized, the synonyms `begin` and `start` are incorrect and must be avoided. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
| `help` | * If the element is [`<a>`](element/a) or [`<area>`](element/area), it indicates that the hyperlink leads to a resource giving further help about the parent of the element, and its descendants.
* If the element is [`<link>`](element/link) it indicates that the hyperlink leads to a resource giving further help about the page as a whole.
| [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form), [`<link>`](element/link) | *None.* |
| `icon` | Defines a resource for representing the page in the user interface, usually an icon (auditory or visual). In the browser, it is usually referred to as the [favicon](https://developer.mozilla.org/en-US/docs/Glossary/Favicon).If there are multiple `<link rel="icon">`s, the browser uses their [`media`](element/link#attr-media), [`type`](element/link#attr-type), and [`sizes`](element/link#attr-sizes) attributes to select the most appropriate icon. If several icons are equally appropriate, the last one is used. If the most appropriate icon is later found to be inappropriate, for example because it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on. **Note:** Apple's iOS does not use this link type, nor the [`sizes`](element/link#attr-sizes) attribute, like others mobile browsers do, to select a webpage icon for Web Clip or a start-up placeholder. Instead it uses the non-standard [`apple-touch-icon`](https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW4) and [`apple-touch-startup-image`](https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW6) respectively. **Warning:** The `shortcut` link type is often seen before `icon`, but this link type is non-conforming, ignored and **web authors must not use it anymore**. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `index` Deprecated | Indicates that the page is part of a *hierarchical* structure and that the hyperlink leads to the top level resource of that structure.If one or several `up` link types are also present, the number of these `up` indicates the depth of the current page in the hierarchy. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
| `last` Deprecated | Indicates that the hyperlink leads to the *last* resource of the *sequence* the current page is in.**Note:** Other link types related to linking resources in the same sequence are `first`, `prev`, `next`.Although recognized, the synonym `end` is incorrect and must be avoided. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
| `license` | Indicates that the hyperlink leads to a document describing the licensing information. If not inside the [`<head>`](element/head) element, the standard doesn't distinguish between a hyperlink applying to a specific part of the document or to the document as a whole. Only the data on the page can indicate this.**Note:** Although recognized, the synonym `copyright` is incorrect and must be avoided. | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form), [`<link>`](element/link) | *None.* |
| `[manifest](link_types/manifest)` | Indicates that the linked file is a [Web App Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest). | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `[me](link_types/me)` | Indicates that the current document is represented by the person to which the `me` value links. The `me` value is commonly used in distributed forms of verification such as [RelMeAuth](https://microformats.org/wiki/RelMeAuth). | [`<link>`](element/link), [`<a>`](element/a) | [`<area>`](element/area), [`<form>`](element/form) |
| `[modulepreload](link_types/modulepreload)` | Initiates early (and high-priority) loading of module scripts. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `next` | Indicates that the hyperlink leads to the *next* resource of the *sequence* the current page is in.**Note:** Other link types related to linking resources in the same sequence are `first`, `prev`, `last`. | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form), [`<link>`](element/link) | *None.* |
| `nofollow` | Indicates that the linked document is not endorsed by the author of this one, for example if it has no control over it, if it is a bad example or if there is commercial relationship between the two (sold link). This link type may be used by some search engines that use popularity ranking techniques. | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) | [`<link>`](element/link) |
| `[noopener](link_types/noopener)` | Instructs the browser to open the link without granting the new browsing context access to the document that opened it — by not setting the [`Window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) property on the opened window (it returns `null`).This is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the [`Window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) property (see [About rel=noopener](https://mathiasbynens.github.io/rel-noopener/) for more details), while still providing the `Referer` HTTP header (unless `noreferrer` is used as well). Note that when `noopener` is used, nonempty target names other than `_top`, `_self`, and `_parent` are all treated like `_blank` in terms of deciding whether to open a new window/tab. | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) | [`<link>`](element/link) |
| `[noreferrer](link_types/noreferrer)` | Prevents the browser, when navigating to another page, to send this page address, or any other value, as referrer via the `Referer:` HTTP header.(In Firefox, before Firefox 37, this worked only in links found in pages. Links clicked in the UI, like "Open in a new tab" via the contextual menu, ignored this). | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) | [`<link>`](element/link) |
| `opener` Experimental | Reverts implicit `rel="noopener"` addition on links with `target="_blank"` (See [related HTML spec discussion](https://github.com/whatwg/html/issues/4078), [WebKit change](https://trac.webkit.org/changeset/237144/webkit/), and [Firefox bug discussion](https://bugzilla.mozilla.org/show_bug.cgi?id=1503681)). | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) | [`<link>`](element/link) |
| `pingback` | Defines an external resource URI to call if one wishes to make a comment or a citation about the webpage. The protocol used to make such a call is defined in the [Pingback 1.0](https://www.hixie.ch/specs/pingback/pingback) specification.**Note:** if the `X-Pingback:` HTTP header is also present, it supersedes the [`<link>`](element/link) element with this link type. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `[preconnect](link_types/preconnect)` Experimental | Provides a hint to the browser suggesting that it open a connection to the linked website in advance, without disclosing any private information or downloading any content, so that when the link is followed the linked content can be fetched more quickly. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `[prefetch](link_types/prefetch)` | Suggests that the browser fetch the linked resource in advance, as it is likely to be requested by the user. Starting with Firefox 44, the value of the [`crossorigin`](element/link#attr-crossorigin) attribute is taken into consideration, making it possible to make anonymous prefetches.**Note:** The [Link Prefetch FAQ](https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ) has details on which links can be prefetched and on alternative methods. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `[preload](link_types/preload)` | Tells the browser to download a resource because this resource will be needed later during the current navigation. See [Preloading content with rel="preload"](link_types/preload) for more details. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `[prerender](link_types/prerender)` Experimental | Suggests that the browser fetch the linked resource in advance, and that it also render the prefetched content offscreen so it can be quickly presented to the user once needed. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `prev` | Indicates that the hyperlink leads to the *preceding* resource of the *sequence* the current page is in.**Note:** You can also use the `next` keyword to specify a link to the next page in the sequence.Although recognized, the synonym `previous` is incorrect and must be avoided. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link), [`<form>`](element/form) | *None.* |
| `search` | Indicates that the hyperlink references a document whose interface is specially designed for searching in this document, or site, and its resources.If the [`type`](element/link#attr-type) attribute is set to `application/opensearchdescription+xml` the resource is an [OpenSearch plugin](https://developer.mozilla.org/en-US/docs/Web/OpenSearch) that can be easily added to the interface of some browsers like Firefox or Internet Explorer. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link), [`<form>`](element/form) | *None.* |
| `shortlink` | [`shortlink` Specification](https://code.google.com/archive/p/shortlink/wikis/Specification.wiki)From Wikipedia, the free encyclopedia: [URL shortening](https://en.wikipedia.org/wiki/URL_shortening)Some websites create short links to make sharing links via instant messaging easier. | [`<link>`](element/link) | ??? |
| `sidebar` Non-standard Deprecated | Indicates that the hyperlink leads to a resource that would be better suited for a secondary browsing context, like a *sidebar*. Browsers, that don't have such a context will ignore this keyword.While once part of the HTML specification, this has been removed from the spec and is only implemented by versions of Firefox prior to Firefox 63. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
| `stylesheet` | Defines an external resource to be used as a stylesheet. If the `type` is not set, the browser should assume it is a `text/css` stylesheet until further inspection.If used in combination with the `alternate` keyword, it defines an [alternative style sheet](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets); in that case the [`title`](element/link#attr-title) attribute must be present and not be the empty string. | [`<link>`](element/link) | [`<a>`](element/a), [`<area>`](element/area), [`<form>`](element/form) |
| `tag` | Indicates that the hyperlink refers to a document describing a *tag* that applies to this document.**Note:** This link type should not be set on links to a member of a tag cloud as these do not apply to a single document but to a set of pages. | [`<a>`](element/a), [`<area>`](element/area) | [`<link>`](element/link), [`<form>`](element/form) |
| `up` Deprecated | Indicates that the page is part of a *hierarchical* structure and that the hyperlink leads to the higher level resource of that structure.The number of `up` link types indicates the depth difference between the current page and the linked resource. | [`<a>`](element/a), [`<area>`](element/area), [`<link>`](element/link) | [`<form>`](element/form) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # linkTypes](https://html.spec.whatwg.org/multipage/links.html#linkTypes) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Link_types` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `alternate_stylesheet` | 1-48 | No | 3 | 8 | Yes | No | No | No | 4 | No | No | No |
| `dns-prefetch` | 46 | ≤79 | 3 | No | 33 | No | 46 | Yes | 4 | No | No | Yes |
| `icon` | 4
If both ICO and PNG are available, will use ICO over PNG if ICO has better matching sizes set. (Per caniuse.com.). | 12
In version 79 and later (Blink-based Edge), if both ICO and PNG are available, will use ICO over PNG if ICO has better matching sizes set. (Per caniuse.com.) | 2
Before Firefox 83, the `crossorigin` attribute is not supported for `rel="icon"`. | 11 | 9
In version 15 and later (Blink-based Opera), if both ICO and PNG are available, will use ICO over PNG if ICO has better matching sizes set. (Per caniuse.com.) | 3.1
If both ICO and PNG are available, will ALWAYS use ICO file, regardless of sizes set. (Per caniuse.com.) | 38 | 18 | 4 | No | No
Does not use favicons at all (but may have alternative for bookmarks, etc.). (Per caniuse.com.) | 4.0 |
| `manifest` | No | No | No | No | No | No | 39 | 39 | No | No | No | 4.0 |
| `modulepreload` | 66 | ≤79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `preconnect` | 46 | 79 | 39
Before Firefox 41, it doesn't obey the `crossorigin` attribute. | No | 33 | 11.1 | 46 | 46 | 39
Before Firefox 41, it doesn't obey the `crossorigin` attribute. | 33 | 11.3 | 4.0 |
| `prefetch` | 8 | 12 | 2 | 11 | 15 | No | 4.4 | 18 | 4 | 14 | No | 1.5 |
| `preload` | 50
Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | ≤79
Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | 85
56-57
Disabled due to various web compatibility issues (e.g. [bug 1405761](https://bugzil.la/1405761)). | No | 37 | No | 50
`as="document"` is unsupported. See [bug 593267](https://crbug.com/593267). | 50
Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | 85
56-57
Disabled due to various web compatibility issues (e.g. [bug 1405761](https://bugzil.la/1405761)). | No | No | 5.0
`as="document"` is unsupported. See [bug 593267](https://crbug.com/593267). |
| `prerender` | 13 | 79 | No | 11 | 15 | No | 4.4 | 18 | No | 14 | No | 1.5 |
html Allowing cross-origin use of images and canvas Allowing cross-origin use of images and canvas
==============================================
HTML provides a [`crossorigin`](element/img#attr-crossorigin) attribute for images that, in combination with an appropriate [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) header, allows images defined by the [`<img>`](element/img) element that are loaded from foreign origins to be used in a [`<canvas>`](element/canvas) as if they had been loaded from the current origin.
See [CORS settings attributes](attributes/crossorigin) for details on how the `crossorigin` attribute is used.
Security and tainted canvases
-----------------------------
Because the pixels in a canvas's bitmap can come from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise.
As soon as you draw into a canvas any data that was loaded from another origin without CORS approval, the canvas becomes **tainted**. A tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back from the canvas will cause an exception to be thrown.
If the source of the foreign content is an HTML [`<img>`](element/img) or SVG [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg) element, attempting to retrieve the contents of the canvas isn't allowed.
If the foreign content comes from an image obtained from either as [`HTMLCanvasElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) or [`ImageBitMap`](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap), and the image source doesn't meet the same origin rules, attempts to read the canvas's contents are blocked.
Calling any of the following on a tainted canvas will result in an error:
* Calling [`getImageData()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData) on the canvas's context
* Calling [`toBlob()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob), [`toDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL) or [`captureStream()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/captureStream) on the [`<canvas>`](element/canvas) element itself
Attempting any of these when the canvas is tainted will cause a `SecurityError` to be thrown. This protects users from having private data exposed by using images to pull information from remote websites without permission.
Storing an image from a foreign origin
--------------------------------------
In this example, we wish to permit images from a foreign origin to be retrieved and saved to local storage. Implementing this requires configuring the server as well as writing code for the website itself.
### Web server configuration
The first thing we need is a server that's configured to host images with the [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) header configured to permit cross-origin access to image files.
Let's assume we're serving our site using [Apache](https://httpd.apache.org/). Consider the HTML5 Boilerplate [Apache server configuration file for CORS images](https://github.com/h5bp/server-configs-apache/blob/main/h5bp/cross-origin/images.conf), shown below:
```
<IfModule mod\_setenvif.c>
<IfModule mod\_headers.c>
<FilesMatch "\.(avifs?|bmp|cur|gif|ico|jpe?g|jxl|a?png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
```
In short, this configures the server to allow graphic files (those with the extensions ".bmp", ".cur", ".gif", ".ico", ".jpg", ".jpeg", ".png", ".svg", ".svgz", and ".webp") to be accessed cross-origin from anywhere on the internet.
### Implementing the save feature
Now that the server has been configured to allow retrieval of the images cross-origin, we can write the code that allows the user to save them to [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API), just as if they were being served from the same domain the code is running on.
The key is to use the [`crossorigin`](global_attributes#crossorigin) attribute by setting [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin) on the [`HTMLImageElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement) into which the image will be loaded. This tells the browser to request cross-origin access when trying to download the image data.
#### Starting the download
The code that starts the download (say, when the user clicks a "Download" button), looks like this:
```
function startDownload() {
let imageURL = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn\_logo-only\_color.svg?1535749917189";
let imageDescription = "The Mozilla logo";
downloadedImg = new Image();
downloadedImg.crossOrigin = "Anonymous";
downloadedImg.addEventListener("load", imageReceived, false);
downloadedImg.alt = imageDescription;
downloadedImg.src = imageURL;
}
```
We're using a hard-coded URL (`imageURL`) and associated descriptive text (`imageDescription`) here, but that could easily come from anywhere. To begin downloading the image, we create a new [`HTMLImageElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement) object by using the [`Image()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image) constructor. The image is then configured to allow cross-origin downloading by setting its `crossOrigin` attribute to `"Anonymous"` (that is, allow non-authenticated downloading of the image cross-origin). An event listener is added for the [`load`](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event) event being fired on the image element, which means the image data has been received. Alternative text is added to the image; while `<canvas>` does not support the `alt` attribute, the value can be used to set an `aria-label` or the canvas's inner content.
Finally, the image's [`src`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/src) attribute is set to the URL of the image to download; this triggers the download to begin.
#### Receiving and saving the image
The code that handles the newly-downloaded image is found in the `imageReceived()` method:
```
function imageReceived() {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = downloadedImg.width;
canvas.height = downloadedImg.height;
canvas.innerText = downloadedImg.alt;
context.drawImage(downloadedImg, 0, 0);
imageBox.appendChild(canvas);
try {
localStorage.setItem("saved-image-example", canvas.toDataURL("image/png"));
} catch (err) {
console.error(`Error: ${err}`);
}
}
```
`imageReceived()` is called to handle the `"load"` event on the `HTMLImageElement` that receives the downloaded image. This event is triggered once the downloaded data is all available. It begins by creating a new [`<canvas>`](element/canvas) element that we'll use to convert the image into a data URL, and by getting access to the canvas's 2D drawing context ([`CanvasRenderingContext2D`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D)) in the variable `context`.
The canvas's size is adjusted to match the received image, the inner text is set to the image description, then the image is drawn into the canvas using [`drawImage()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage). The canvas is then inserted into the document so the image is visible.
Now it's time to actually save the image locally. To do this, we use the Web Storage API's local storage mechanism, which is accessed through the [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) global. The canvas method [`toDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL) is used to convert the image into a data:// URL representing a PNG image, which is then saved into local storage using [`setItem()`](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem).
See also
--------
* [Using Cross-domain images in WebGL and Chrome 13](https://blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html)
* [HTML Specification - the `crossorigin` attribute](https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-crossorigin)
* [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)
| programming_docs |
html <meta>: The metadata element <meta>: The metadata element
============================
The `<meta>` [HTML](../index) element represents [metadata](https://developer.mozilla.org/en-US/docs/Glossary/Metadata) that cannot be represented by other HTML meta-related elements, like [`<base>`](base), [`<link>`](link), [`<script>`](script), [`<style>`](style) or [`<title>`](title).
| | |
| --- | --- |
| [Content categories](../content_categories) | [Metadata content](../content_categories#metadata_content). If the [`itemprop`](../global_attributes/itemprop) attribute is present: [flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content). |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | As it is a void element, the start tag must be present and the end tag must not be present. |
| Permitted parents | * `<meta charset>`, `<meta http-equiv>`: a [`<head>`](head) element. If the [`http-equiv`](meta#attr-http-equiv) is not an encoding declaration, it can also be inside a [`<noscript>`](noscript) element, itself inside a `<head>` element.
* `<meta name>`: any element that accepts [metadata content](../content_categories#metadata_content).
* `<meta itemprop>`: any element that accepts [metadata content](../content_categories#metadata_content) or [flow content](../content_categories#flow_content).
|
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLMetaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMetaElement) |
The type of metadata provided by the `<meta>` element can be one of the following:
* If the [`name`](meta#attr-name) attribute is set, the `<meta>` element provides *document-level metadata*, applying to the whole page.
* If the [`http-equiv`](meta#attr-http-equiv) attribute is set, the `<meta>` element is a *pragma directive*, providing information equivalent to what can be given by a similarly-named HTTP header.
* If the [`charset`](meta#attr-charset) attribute is set, the `<meta>` element is a *charset declaration*, giving the character encoding in which the document is encoded.
* If the [`itemprop`](../global_attributes/itemprop) attribute is set, the `<meta>` element provides *user-defined metadata*.
Attributes
----------
This element includes the [global attributes](../global_attributes).
**Note:** the attribute [`name`](meta#attr-name) has a specific meaning for the `<meta>` element, and the [`itemprop`](../global_attributes/itemprop) attribute must not be set on the same `<meta>` element that has any existing [`name`](meta#attr-name), [`http-equiv`](meta#attr-http-equiv) or [`charset`](meta#attr-charset) attributes.
[**`charset`**](#attr-charset) This attribute declares the document's character encoding. If the attribute is present, its value must be an ASCII case-insensitive match for the string "`utf-8`", because UTF-8 is the only valid encoding for HTML5 documents. `<meta>` elements which declare a character encoding must be located entirely within the first 1024 bytes of the document.
[**`content`**](#attr-content) This attribute contains the value for the [`http-equiv`](meta#attr-http-equiv) or [`name`](meta#attr-name) attribute, depending on which is used.
[**`http-equiv`**](#attr-http-equiv) Defines a pragma directive. The attribute is named `http-equiv(alent)` because all the allowed values are names of particular HTTP headers:
* `content-security-policy` Allows page authors to define a [content policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) for the current page. Content policies mostly specify allowed server origins and script endpoints which help guard against cross-site scripting attacks.
* `content-type` Declares the [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) and character encoding of the document. If specified, the `content` attribute must have the value "`text/html; charset=utf-8`". This is equivalent to a `<meta>` element with the [`charset`](meta#attr-charset) attribute specified, and carries the same restriction on placement within the document. **Note:** Can only be used in documents served with a `text/html` — not in documents served with an XML MIME type.
* `default-style` Sets the name of the default [CSS style sheet](https://developer.mozilla.org/en-US/docs/Web/CSS) set.
* `x-ua-compatible` If specified, the `content` attribute must have the value "`IE=edge`". User agents are required to ignore this pragma.
* `refresh` This instruction specifies:
+ The number of seconds until the page should be reloaded - only if the [`content`](meta#attr-content) attribute contains a non-negative integer.
+ The number of seconds until the page should redirect to another - only if the [`content`](meta#attr-content) attribute contains a non-negative integer followed by the string '`;url=`', and a valid URL. **Warning:**
Pages set with a `refresh` value run the risk of having the time interval being too short. People navigating with the aid of assistive technology such as a screen reader may be unable to read through and understand the page's content before being automatically redirected. The abrupt, unannounced updating of the page content may also be disorienting for people experiencing low vision conditions.
+ [MDN Understanding WCAG, Guideline 2.1 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.2_%E2%80%94_enough_time_provide_users_enough_time_to_read_and_use_content)
+ [MDN Understanding WCAG, Guideline 3.1 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.2_%E2%80%94_predictable_make_web_pages_appear_and_operate_in_predictable_ways)
+ [Understanding Success Criterion 2.2.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-required-behaviors.html)
+ [Understanding Success Criterion 2.2.4 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-postponed.html)
+ [Understanding Success Criterion 3.2.5 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/consistent-behavior-no-extreme-changes-context.html)
[**`name`**](#attr-name) The `name` and `content` attributes can be used together to provide document metadata in terms of name-value pairs, with the `name` attribute giving the metadata name, and the `content` attribute giving the value.
See [standard metadata names](meta/name) for details about the set of standard metadata names defined in the HTML specification.
Examples
--------
```
<meta charset="utf-8" />
<!-- Redirect page after 3 seconds -->
<meta http-equiv="refresh" content="3;url=https://www.mozilla.org" />
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-meta-element](https://html.spec.whatwg.org/multipage/semantics.html#the-meta-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `meta` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `charset` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `content` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `http-equiv` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `name` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
See also
--------
* [Standard metadata names](meta/name)
* [Learn: `<meta>`](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#metadata_the_meta_element)
* [The viewport meta tag](../viewport_meta_tag)
html <center>: The Centered Text element <center>: The Centered Text element
===================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<center>` [HTML](../index) element is a [block-level element](../block-level_elements) that displays its block-level or inline contents centered horizontally within its containing element. The container is usually, but isn't required to be, [`<body>`](body).
This tag has been deprecated in HTML 4 (and XHTML 1) in favor of the [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property, which can be applied to the [`<div>`](div) element or to an individual [`<p>`](p). For centering blocks, use other CSS properties like [`margin-left`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left) and [`margin-right`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right) and set them to `auto` (or set [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) to `0 auto`).
DOM interface
-------------
This element implements the [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface.
Example 1
---------
```
<center>
This text will be centered.
<p>So will this paragraph.</p>
</center>
```
Example 2 (CSS alternative)
---------------------------
```
<div style="text-align:center">
This text will be centered.
<p>So will this paragraph.</p>
</div>
```
Example 3 (CSS alternative)
---------------------------
```
<p style="text-align:center">
This line will be centered.<br />
And so will this line.
</p>
```
Note
----
Applying [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align)`:center` to a [`<div>`](div) or [`<p>`](p) element centers the *contents* of those elements while leaving their overall dimensions unchanged.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # center](https://html.spec.whatwg.org/multipage/obsolete.html#center) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `center` | Yes | 12 | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes |
See also
--------
* [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align)
* [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display)
html <legend>: The Field Set Legend element <legend>: The Field Set Legend element
======================================
The `<legend>` [HTML](../index) element represents a caption for the content of its parent [`<fieldset>`](fieldset).
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
See [`<form>`](form) for examples on `<legend>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content) and [headings](heading_elements) (h1–h6 elements). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | A [`<fieldset>`](fieldset) whose first child is this `<legend>` element |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLLegendElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLegendElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-legend-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-legend-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `legend` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
See also
--------
* [ARIA: Form role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/form_role)
html <b>: The Bring Attention To element <b>: The Bring Attention To element
===================================
The `<b>` [HTML](../index) element is used to draw the reader's attention to the element's contents, which are not otherwise granted special importance. This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use `<b>` for styling text; instead, you should use the CSS [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) property to create boldface text, or the [`<strong>`](strong) element to indicate that text is of special importance.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Use the `<b>` for cases like keywords in a summary, product names in a review, or other spans of text whose typical presentation would be boldfaced (but not including any special importance).
* Do not confuse the `<b>` element with the [`<strong>`](strong), [`<em>`](em), or [`<mark>`](mark) elements. The [`<strong>`](strong) element represents text of certain *importance*, [`<em>`](em) puts some emphasis on the text and the [`<mark>`](mark) element represents text of certain *relevance*. The `<b>` element doesn't convey such special semantic information; use it only when no others fit.
* Similarly, do not mark titles and headings using the `<b>` element. For this purpose, use the [`<h1>`](heading_elements) to [`<h6>`](heading_elements) tags. Further, stylesheets can change the default style of these elements, with the result that they are not *necessarily* displayed in bold.
* It is a good practice to use the [`class`](../global_attributes#class) attribute on the `<b>` element in order to convey additional semantic information as needed (for example `<b class="lead">` for the first sentence in a paragraph). This makes it easier to manage multiple use cases of `<b>` if your stylistic needs change, without the need to change all of its uses in the HTML.
* Historically, the `<b>` element was meant to make text boldface. Styling information has been deprecated since HTML4, so the meaning of the `<b>` element has been changed.
* If there is no semantic purpose to using the `<b>` element, you should use the CSS [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) property with the value `"bold"` instead in order to make text bold.
Examples
--------
```
<p>
This article describes several <b class="keywords">text-level</b> elements. It
explains their usage in an <b class="keywords">HTML</b> document.
</p>
Keywords are displayed with the default style of the
<b>element, likely in bold.</b>
```
### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-b-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-b-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `b` | Yes | 12 | 1
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Other elements conveying text-level semantics: [`<a>`](a), [`<em>`](em), [`<strong>`](strong), [`<small>`](small), [`<cite>`](cite), [`<q>`](q), [`<dfn>`](dfn), [`<abbr>`](abbr), [`<time>`](time), [`<code>`](code), [`<var>`](var), [`<samp>`](samp), [`<kbd>`](kbd), [`<sub>`](sub), [`<sup>`](sup), [`<i>`](i), [`<mark>`](mark), [`<ruby>`](ruby), [`<rp>`](rp), [`<rt>`](rt), [`<bdo>`](bdo), [`<span>`](span), [`<br>`](br), [`<wbr>`](wbr).
* [Using <b> and <i> elements (W3C)](https://www.w3.org/International/questions/qa-b-and-i-tags)
html <select>: The HTML Select element <select>: The HTML Select element
=================================
The `<select>` [HTML](../index) element represents a control that provides a menu of options.
Try it
------
The above example shows typical `<select>` usage. It is given an `id` attribute to enable it to be associated with a [`<label>`](label) for accessibility purposes, as well as a `name` attribute to represent the name of the associated data point submitted to the server. Each menu option is defined by an [`<option>`](option) element nested inside the `<select>`.
Each `<option>` element should have a [`value`](option#attr-value) attribute containing the data value to submit to the server when that option is selected. If no `value` attribute is included, the value defaults to the text contained inside the element. You can include a [`selected`](option#attr-selected) attribute on an `<option>` element to make it selected by default when the page first loads.
The `<select>` element has some unique attributes you can use to control it, such as `multiple` to specify whether multiple options can be selected, and `size` to specify how many options should be shown at once. It also accepts most of the general form input attributes such as `required`, `disabled`, `autofocus`, etc.
You can further nest `<option>` elements inside [`<optgroup>`](optgroup) elements to create separate groups of options inside the dropdown.
For further examples, see [The native form widgets: Drop-down content](https://developer.mozilla.org/en-US/docs/Learn/Forms/Other_form_controls#drop-down_controls).
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`autocomplete`**](#attr-autocomplete) A string providing a hint for a [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) autocomplete feature. See [The HTML autocomplete attribute](../attributes/autocomplete) for a complete list of values and details on how to use autocomplete.
[**`autofocus`**](#attr-autofocus) This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form element in a document can have the `autofocus` attribute.
[**`disabled`**](#attr-disabled) This Boolean attribute indicates that the user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example [`<fieldset>`](fieldset); if there is no containing element with the `disabled` attribute set, then the control is enabled.
[**`form`**](#attr-form) The [`<form>`](form) element to associate the `<select>` with (its *form owner*). The value of this attribute must be the [`id`](../global_attributes#id) of a `<form>` in the same document. (If this attribute is not set, the `<select>` is associated with its ancestor `<form>` element, if any.)
This attribute lets you associate `<select>` elements to `<form>`s anywhere in the document, not just inside a `<form>`. It can also override an ancestor `<form>` element.
[**`multiple`**](#attr-multiple) This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When `multiple` is specified, most browsers will show a scrolling list box instead of a single line dropdown.
[**`name`**](#attr-name) This attribute is used to specify the name of the control.
[**`required`**](#attr-required) A Boolean attribute indicating that an option with a non-empty string value must be selected.
[**`size`**](#attr-size) If the control is presented as a scrolling list box (e.g. when `multiple` is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is `0`.
**Note:** According to the HTML specification, the default value for size should be `1`; however, in practice, this has been found to break some websites, and no other browser currently does that, so Mozilla has opted to continue to return `0` for the time being with Firefox.
Usage notes
-----------
### Selecting multiple options
On a desktop computer, there are a number of ways to select multiple options in a `<select>` element with a `multiple` attribute:
Mouse users can hold the `Ctrl`, `Command`, or `Shift` keys (depending on what makes sense for your operating system) and then click multiple options to select/deselect them.
**Warning:** The mechanism for selecting multiple non-contiguous items via the keyboard described below currently only seems to work in Firefox.
On macOS, the `Ctrl` + `Up` and `Ctrl` + `Down` shortcuts conflict with the OS default shortcuts for *Mission Control* and *Application windows*, so you'll have to turn these off before it will work.
Keyboard users can select multiple contiguous items by:
* Focusing on the `<select>` element (e.g. using `Tab` ).
* Selecting an item at the top or bottom of the range they want to select using the `Up` and `Down` cursor keys to go up and down the options.
* Holding down the `Shift` key and then using the `Up` and `Down` cursor keys to increase or decrease the range of items selected.
Keyboard users can select multiple non-contiguous items by:
* Focusing on the `<select>` element (e.g. using `Tab` ).
* Holding down the `Ctrl` key then using the `Up` and `Down` cursor keys to change the "focused" select option, i.e. the one that will be selected if you choose to do so. The "focused" select option is highlighted with a dotted outline, in the same way as a keyboard-focused link.
* Pressing `Space` to select/deselect "focused" select options.
Styling with CSS
----------------
The `<select>` element is notoriously difficult to style productively with CSS. You can affect certain aspects like any element — for example, manipulating the [box model](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model), the [displayed font](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts), etc., and you can use the [`appearance`](https://developer.mozilla.org/en-US/docs/Web/CSS/appearance) property to remove the default system `appearance`.
However, these properties don't produce a consistent result across browsers, and it is hard to do things like line different types of form element up with one another in a column. The `<select>` element's internal structure is complex, and hard to control. If you want to get full control, you should consider using a library with good facilities for styling form widgets, or try rolling your own dropdown menu using non-semantic elements, JavaScript, and [WAI-ARIA](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) to provide semantics.
For more useful information on styling `<select>`, see:
* [Styling HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms/Styling_web_forms)
* [Advanced styling for HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms/Advanced_form_styling)
Also see the "Customizing select styles" example below for an example of you could attempt a simple `<select>` styling.
Examples
--------
### Basic select
The following example creates a very simple dropdown menu, the second option of which is selected by default.
```
<!-- The second value will be selected initially -->
<select name="choice">
<option value="first">First Value</option>
<option value="second" selected>Second Value</option>
<option value="third">Third Value</option>
</select>
```
### Advanced select with multiple features
The follow example is more complex, showing off more features you can use on a `<select>` element:
```
<label>Please choose one or more pets:
<select name="pets" multiple size="4">
<optgroup label="4-legged pets">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="hamster" disabled>Hamster</option>
</optgroup>
<optgroup label="Flying pets">
<option value="parrot">Parrot</option>
<option value="macaw">Macaw</option>
<option value="albatross">Albatross</option>
</optgroup>
</select>
</label>
```
You'll see that:
* Multiple options are selectable because we've included the `multiple` attribute.
* The `size` attribute causes only 4 lines to display at a time; you can scroll to view all the options.
* We've included [`<optgroup>`](optgroup) elements to divide the options up into different groups. This is a purely visual grouping, its visualization generally consists of the group name being bolded, and the options being indented.
* The "Hamster" option includes a `disabled` attribute and therefore can't be selected at all.
### Customizing select styles
This example shows how you could use some CSS and JavaScript to provide extensive custom styling for a `<select>` box.
This example basically:
* Clones the `<select>`'s context (the [`<option>`s](option)) in a parent wrapper and reimplements the standard expected behavior using additional HTML elements and JavaScript. This includes basic tab behavior to provide keyboard accessibility.
* Maps some standards native `attributes` to `data-attributes` of the new elements in order to manage state and CSS.
**Note:** Not all native features are supported, it's a Proof of Concept. IT starts from standard HTML but the same results can be achieved starting from JSON data, custom HTML, or other solutions.
#### HTML
```
<form>
<fieldset>
<legend>Standard controls</legend>
<select name="1A" id="select" autocomplete="off" required>
<option>Carrots</option>
<option>Peas</option>
<option>Beans</option>
<option>Pneumonoultramicroscopicsilicovolcanoconiosis</option>
</select>
</fieldset>
<fieldset id="custom">
<legend>Custom controls</legend>
<select name="2A" id="select" autocomplete="off" required>
<option>Carrots</option>
<option>Peas</option>
<option>Beans</option>
<option>Pneumonoultramicroscopicsilicovolcanoconiosis</option>
</select>
</fieldset>
</form>
```
#### CSS
```
body {
font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;
}
.select:focus {
border-color: blue;
}
html body form fieldset#custom div.select[data-multiple] div.header {
display: none;
}
html body form fieldset#custom div.select div.header {
content: "↓";
display: flex;
flex: 1;
align-items: center;
padding: 0;
position: relative;
width: auto;
box-sizing: border-box;
border-width: 1px;
border-style: inherit;
border-color: inherit;
border-radius: inherit;
}
html body form fieldset#custom div.select div.header::after {
content: "↓";
align-self: stretch;
display: flex;
align-content: center;
justify-content: center;
justify-items: center;
align-items: center;
padding: 0.5em;
}
html body form fieldset#custom div.select div.header:hover::after {
background-color: blue;
}
.select .header select {
appearance: none;
font-family: inherit;
font-size: inherit;
padding: 0;
border-width: 0;
width: 100%;
flex: 1;
display: none;
}
.select .header select optgroup {
display: none;
}
.select select div.option {
display: none;
}
html body form fieldset#custom div.select {
user-select: none;
box-sizing: border-box;
position: relative;
border-radius: 4px;
border-style: solid;
border-width: 0;
border-color: gray;
width: auto;
display: inline-block;
}
html body form fieldset#custom div.select:focus,
html body form fieldset#custom div.select:hover {
border-color: blue;
}
html body form fieldset#custom div.select[data-open] {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
html body form fieldset#custom div.select[data-open] datalist {
display: initial;
}
html body form fieldset#custom div.select datalist {
appearance: none;
position: absolute;
border-style: solid;
border-width: 1px;
border-color: gray;
left: 0;
display: none;
width: 100%;
box-sizing: border-box;
z-index: 2;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
html body form fieldset#custom div.select datalist div.option {
background-color: white;
margin-bottom: 1px;
cursor: pointer;
padding: 0.5em;
border-width: 0;
}
html body form fieldset#custom div.select datalist div.option:hover,
html body form fieldset#custom div.select datalist div.option:focus,
html body form fieldset#custom div.select datalist div.option:checked {
background-color: blue;
color: white;
}
html
body
form
fieldset#custom
div.select
div.optgroup
div.option[data-disabled] {
color: gray;
}
html
body
form
fieldset#custom
div.select
div.optgroup
div.option[data-checked] {
background-color: blue;
color: white;
}
html body form fieldset#custom div.select div.optgroup div.label {
font-weight: bold;
}
html body form fieldset#custom div.select div.optgroup div.option div.label {
font-weight: normal;
padding: 0.25em;
}
html body form fieldset#custom div.select div.header span {
flex: 1;
padding: 0.5em;
}
```
#### JavaScript
```
const selects = custom.querySelectorAll('select');
for (const select of selects) {
const div = document.createElement('div');
const header = document.createElement('div');
const datalist = document.createElement('datalist');
const optgroups = select.querySelectorAll('optgroup');
const span = document.createElement('span');
const options = select.options;
const parent = select.parentElement;
const multiple = select.hasAttribute('multiple');
function onclick(e) {
const disabled = this.hasAttribute('data-disabled');
select.value = this.dataset.value;
span.innerText = this.dataset.label;
if (disabled) return;
if (multiple) {
if (e.shiftKey) {
const checked = this.hasAttribute("data-checked");
if (checked) {
this.removeAttribute("data-checked");
} else {
this.setAttribute("data-checked", "");
}
} else {
const options = div.querySelectorAll('.option');
for (let i = 0; i < options.length; i++) {
const option = options[i];
option.removeAttribute("data-checked");
}
this.setAttribute("data-checked", "");
}
}
}
function onkeyup(e) {
e.preventDefault();
e.stopPropagation();
if (e.keyCode === 13) {
this.click();
}
}
div.classList.add('select');
header.classList.add('header');
div.tabIndex = 1;
select.tabIndex = -1;
span.innerText = select.label;
header.appendChild(span);
for (const attribute of select.attributes) {
div.dataset[attribute.name] = attribute.value;
}
for (let i = 0; i < options.length; i++) {
const option = document.createElement('div');
const label = document.createElement('div');
const o = options[i];
for (const attribute of o.attributes) {
option.dataset[attribute.name] = attribute.value;
}
option.classList.add('option');
label.classList.add('label');
label.innerText = o.label;
option.dataset.value = o.value;
option.dataset.label = o.label;
option.onclick = onclick;
option.onkeyup = onkeyup;
option.tabIndex = i + 1;
option.appendChild(label);
datalist.appendChild(option);
}
div.appendChild(header);
for (const o of optgroups) {
const optgroup = document.createElement('div');
const label = document.createElement('div');
const options = o.querySelectorAll('option');
Object.assign(optgroup, o);
optgroup.classList.add('optgroup');
label.classList.add('label');
label.innerText = o.label;
optgroup.appendChild(label);
div.appendChild(optgroup);
for (const o of options) {
const option = document.createElement('div');
const label = document.createElement('div');
for (const attribute of o.attributes) {
option.dataset[attribute.name] = attribute.value;
}
option.classList.add('option');
label.classList.add('label');
label.innerText = o.label;
option.tabIndex = i + 1;
option.dataset.value = o.value;
option.dataset.label = o.label;
option.onclick = onclick;
option.onkeyup = onkeyup;
option.tabIndex = i + 1;
option.appendChild(label);
optgroup.appendChild(option);
}
}
div.onclick = (e) => {
e.preventDefault();
};
parent.insertBefore(div, select);
header.appendChild(select);
div.appendChild(datalist);
datalist.style.top = `${header.offsetTop + header.offsetHeight}px`;
div.onclick = (e) => {
if (!multiple) {
const open = this.hasAttribute("data-open");
e.stopPropagation();
if (open) {
div.removeAttribute("data-open");
} else {
div.setAttribute("data-open", "");
}
}
};
div.onkeyup = (event) => {
event.preventDefault();
if (event.keyCode === 13) {
div.click();
}
};
document.addEventListener('click', (e) => {
if (div.hasAttribute("data-open")) {
div.removeAttribute("data-open");
}
});
const width = Math.max(...Array.from(options).map((e) => {
span.innerText = e.label;
return div.offsetWidth;
}));
console.log(width);
div.style.width = `${width}px`;
}
document.forms[0].onsubmit = (e) => {
const data = new FormData(this);
e.preventDefault();
submit.innerText = JSON.stringify([...data.entries()]);
};
```
#### Result
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [interactive content](../content_categories#interactive_content), [listed](../content_categories#form_listed), [labelable](../content_categories#form_labelable), [resettable](../content_categories#form_resettable), and [submittable](../content_categories#form_submittable) [form-associated](../content_categories#form-associated_) element |
| Permitted content | Zero or more [`<option>`](option) or [`<optgroup>`](optgroup) elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | `[combobox](https://w3c.github.io/aria/#combobox)` with **no** `multiple` attribute and **no** `size` attribute greater than 1, otherwise `[listbox](https://w3c.github.io/aria/#listbox)` |
| Permitted ARIA roles | `[menu](https://w3c.github.io/aria/#menu)` with **no** `multiple` attribute and **no** `size` attribute greater than 1, otherwise no `role` permitted |
| DOM interface | [`HTMLSelectElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-select-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-select-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `select` | Yes
`border-radius` on `<select>` elements is ignored unless `-webkit-appearance` is overridden to an appropriate value. | 12 | 1
Historically, Firefox has allowed keyboard and mouse events to bubble up from the `<option>` element to the parent `<select>` element, although this behavior is inconsistent across many browsers. For better Web compatibility (and for technical reasons), when Firefox is in multi-process mode the `<select>` element is displayed as a drop-down list. The behavior is unchanged if the `<select>` is presented inline and it has either the multiple attribute defined or a size attribute set to more than 1. Rather than watching `<option>` elements for events, you should watch for change events on `<select>`. See [bug 1090602](https://bugzil.la/1090602) for details. | Yes | Yes | Yes
`border-radius` on `<select>` elements is ignored unless `-webkit-appearance` is overridden to an appropriate value. | Yes
["In the Browser app for Android 4.1 (and possibly later versions), there is a bug where the menu indicator triangle on the side of a `<select>` will not be displayed if a `background`, `border`, or `border-radius` style is applied to the `<select>`.", "`border-radius` on `<select>` elements is ignored unless `-webkit-appearance` is overridden to an appropriate value."] | Yes
`border-radius` on `<select>` elements is ignored unless `-webkit-appearance` is overridden to an appropriate value. | 4
Firefox for Android, by default, sets a `background-image` gradient on all `<select multiple>` elements. This can be disabled using `background-image: none`. | Yes | Yes
`border-radius` on `<select>` elements is ignored unless `-webkit-appearance` is overridden to an appropriate value. | Yes
`border-radius` on `<select>` elements is ignored unless `-webkit-appearance` is overridden to an appropriate value. |
| `disabled` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `form` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `multiple` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `name` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `required` | Yes | 12 | 4 | 10 | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `size` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Events fired by `<select>`: [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event), [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
* The [`<option>`](option) element
* The [`<optgroup>`](optgroup) element
| programming_docs |
html <dl>: The Description List element <dl>: The Description List element
==================================
The `<dl>` [HTML](../index) element represents a description list. The element encloses a list of groups of terms (specified using the [`<dt>`](dt) element) and descriptions (provided by [`<dd>`](dd) elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs).
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), and if the `<dl>` element's children include one name-value group, palpable content. |
| Permitted content | Either: Zero or more groups each consisting of one or more [`<dt>`](dt) elements followed by one or more [`<dd>`](dd) elements, optionally intermixed with [`<script>`](script) and [`<template>`](template) elements.Or: (in [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG) HTML, [W3C](https://developer.mozilla.org/en-US/docs/Glossary/W3C) HTML 5.2 and later) One or more [`<div>`](div) elements, optionally intermixed with [`<script>`](script) and [`<template>`](template) elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[group](https://w3c.github.io/aria/#group)`, `[list](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/list_role)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)` |
| DOM interface | [`HTMLDListElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDListElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
### Single term and description
```
<dl>
<dt>Firefox</dt>
<dd>
A free, open source, cross-platform, graphical web browser developed by the
Mozilla Corporation and hundreds of volunteers.
</dd>
<!-- Other terms and descriptions -->
</dl>
```
### Multiple terms, single description
```
<dl>
<dt>Firefox</dt>
<dt>Mozilla Firefox</dt>
<dt>Fx</dt>
<dd>
A free, open source, cross-platform, graphical web browser developed by the
Mozilla Corporation and hundreds of volunteers.
</dd>
<!-- Other terms and descriptions -->
</dl>
```
### Single term, multiple descriptions
```
<dl>
<dt>Firefox</dt>
<dd>
A free, open source, cross-platform, graphical web browser developed by the
Mozilla Corporation and hundreds of volunteers.
</dd>
<dd>
The Red Panda also known as the Lesser Panda, Wah, Bear Cat or Firefox, is a
mostly herbivorous mammal, slightly larger than a domestic cat (60 cm long).
</dd>
<!-- Other terms and descriptions -->
</dl>
```
### Multiple terms and descriptions
It is also possible to define multiple terms with multiple corresponding descriptions, by combining the examples above.
### Metadata
Description lists are useful for displaying metadata as a list of key-value pairs.
```
<dl>
<dt>Name</dt>
<dd>Godzilla</dd>
<dt>Born</dt>
<dd>1952</dd>
<dt>Birthplace</dt>
<dd>Japan</dd>
<dt>Color</dt>
<dd>Green</dd>
</dl>
```
Tip: It can be handy to define a key-value separator in the CSS, such as:
```
dt::after {
content: ": ";
}
```
### Wrapping name-value groups in `div` elements
[WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG) HTML allows wrapping each name-value group in a [`<dl>`](dl) element in a [`<div>`](div) element. This can be useful when using [microdata](../microdata), or when [global attributes](../global_attributes) apply to a whole group, or for styling purposes.
```
<dl>
<div>
<dt>Name</dt>
<dd>Godzilla</dd>
</div>
<div>
<dt>Born</dt>
<dd>1952</dd>
</div>
<div>
<dt>Birthplace</dt>
<dd>Japan</dd>
</div>
<div>
<dt>Color</dt>
<dd>Green</dd>
</div>
</dl>
```
Notes
-----
Do not use this element (nor [`<ul>`](ul) elements) to merely create indentation on a page. Although it works, this is a bad practice and obscures the meaning of description lists.
To change the indentation of a description term, use the [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) property.
Accessibility concerns
----------------------
Each screen reader exposes `<dl>` content differently, including total count, terms/definitions context, and navigation methods. These differences are not necessarily bugs. As of iOS 14, VoiceOver will announce that `<dl>` content is a list when navigating with the virtual cursor (not via the read-all command). VoiceOver does not support list navigation commands with `<dl>`. Be careful applying ARIA `term` and `definition` roles to `<dl>` constructs as VoiceOver (macOS and iOS) will adjust how they are announced.
* [VoiceOver on iOS 14 Supports Description Lists](https://adrianroselli.com/2020/09/voiceover-on-ios-14-supports-description-lists.html)
* [Brief Note on Description List Support](https://adrianroselli.com/2022/12/brief-note-on-description-list-support.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-dl-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-dl-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `dl` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<dt>`](dt)
* [`<dd>`](dd)
html <mark>: The Mark Text element <mark>: The Mark Text element
=============================
The `<mark>` [HTML](../index) element represents text which is **marked** or **highlighted** for reference or notation purposes due to the marked passage's relevance in the enclosing context.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
Typical use cases for `<mark>` include:
* When used in a quotation ([`<q>`](q)) or block quote ([`<blockquote>`](blockquote)), it generally indicates text which is of special interest but is not marked in the original source material, or material which needs special scrutiny even though the original author didn't think it was of particular importance. Think of this like using a highlighter pen in a book to mark passages that you find of interest.
* Otherwise, `<mark>` indicates a portion of the document's content which is likely to be relevant to the user's current activity. This might be used, for example, to indicate the words that matched a search operation.
* Don't use `<mark>` for syntax highlighting purposes; instead, use the [`<span>`](span) element with appropriate CSS applied to it.
**Note:** Don't confuse `<mark>` with the [`<strong>`](strong) element; `<mark>` is used to denote content which has a degree of *relevance*, while `<strong>` indicates spans of text of *importance*.
Examples
--------
### Marking text of interest
In this first example, a `<mark>` element is used to mark some text within a quote which is of particular interest to the user.
```
<blockquote>
It is a period of civil war. Rebel spaceships, striking from a hidden base,
have won their first victory against the evil Galactic Empire. During the
battle, <mark>Rebel spies managed to steal secret plans</mark> to the Empire's
ultimate weapon, the DEATH STAR, an armored space station with enough power to
destroy an entire planet.
</blockquote>
```
The resulting output looks like this:
### Identifying context-sensitive passages
This example demonstrates using `<mark>` to mark search results within a passage.
```
<p>
It is a dark time for the Rebellion. Although the Death Star has been
destroyed, <mark class="match">Imperial</mark> troops have driven the Rebel
forces from their hidden base and pursued them across the galaxy.
</p>
<p>
Evading the dreaded <mark class="match">Imperial</mark> Starfleet, a group of
freedom fighters led by Luke Skywalker has established a new secret base on
the remote ice world of Hoth.
</p>
```
To help distinguish the use of `<mark>` for search results from other potential usage, this example applies the custom class `"match"` to each match.
The results look like this:
Accessibility concerns
----------------------
The presence of the `mark` element is not announced by most screen reading technology in its default configuration. It can be made to be announced by using the CSS [`content`](https://developer.mozilla.org/en-US/docs/Web/CSS/content) property, along with the [`::before`](https://developer.mozilla.org/en-US/docs/Web/CSS/::before) and [`::after`](https://developer.mozilla.org/en-US/docs/Web/CSS/::after) pseudo-elements.
```
mark::before,
mark::after {
clip-path: inset(100%);
clip: rect(1px, 1px, 1px, 1px);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
mark::before {
content: " [highlight start] ";
}
mark::after {
content: " [highlight end] ";
}
```
Some people who use screen readers deliberately disable announcing content that creates extra verbosity. Because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has been highlighted would adversely affect understanding.
* [Short note on making your mark (more accessible) | The Paciello Group](https://www.tpgi.com/short-note-on-making-your-mark-more-accessible/)
* [Tweaking Text Level Styles | Adrian Roselli](https://adrianroselli.com/2017/12/tweaking-text-level-styles.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-mark-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-mark-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `mark` | Yes | 12 | 4 | 9 | 11 | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
html <td>: The Table Data Cell element <td>: The Table Data Cell element
=================================
The `<td>` [HTML](../index) element defines a cell of a table that contains data. It participates in the *table model*.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`colspan`**](#attr-colspan) This attribute contains a non-negative integer value that indicates for how many columns the cell extends. Its default value is `1`. Values higher than 1000 will be considered as incorrect and will be set to the default value (1).
[**`headers`**](#attr-headers) This attribute contains a list of space-separated strings, each corresponding to the **id** attribute of the [`<th>`](th) elements that apply to this element.
[**`rowspan`**](#attr-rowspan) This attribute contains a non-negative integer value that indicates for how many rows the cell extends. Its default value is `1`; if its value is set to `0`, it extends until the end of the table section ([`<thead>`](thead), [`<tbody>`](tbody), [`<tfoot>`](tfoot), even if implicitly defined), that the cell belongs to. Values higher than 65534 are clipped down to 65534.
### Deprecated attributes
[**`abbr`**](#attr-abbr) Deprecated
This attribute contains a short abbreviated description of the cell's content. Some user-agents, such as speech readers, may present this description before the content itself.
**Note:** Do not use this attribute as it is obsolete in the latest standard. Alternatively, you can put the abbreviated description inside the cell and place the long content in the **title** attribute.
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute specifies how the cell content's horizontal alignment will be handled. Possible values are:
* `left`: The content is aligned to the left of the cell.
* `center`: The content is centered in the cell.
* `right`: The content is aligned to the right of the cell.
* `justify` (with text only): The content is stretched out inside the cell so that it covers its entire width.
* `char` (with text only): The content is aligned to a character inside the `<th>` element with minimal offset. This character is defined by the [`char`](td#attr-char) and [`charoff`](td#attr-charoff) attributes Unimplemented (see [bug 2212](https://bugzilla.mozilla.org/show_bug.cgi?id=2212)).
The default value when this attribute is not specified is `left`.
**Note:**
* To achieve the same effect as the `left`, `center`, `right` or `justify` values, apply the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to the element.
* To achieve the same effect as the `char` value, give the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property the same value you would use for the [`char`](td#attr-char). Unimplemented in CSS.
[**`axis`**](#attr-axis) Deprecated
This attribute contains a list of space-separated strings. Each string is the `id` of a group of cells that this header applies to.
[**`bgcolor`**](#attr-bgcolor) Deprecated
This attribute defines the background color of each cell in a column. It is a [6-digit hexadecimal RGB code](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors), prefixed by a '`#`'. One of the predefined [color keywords](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) can also be used.
To achieve a similar effect, use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property.
[**`char`**](#attr-char) Deprecated
The content in the cell element is aligned to a character. Typical values include a period (.) to align numbers or monetary values. If [`align`](td#attr-align) is not set to `char`, this attribute is ignored.
[**`charoff`**](#attr-charoff) Deprecated
This attribute is used to shift column data to the right of the character specified by the **char** attribute. Its value specifies the length of this shift.
[**`height`**](#attr-height) Deprecated
This attribute is used to define a recommended cell height. Use the CSS [`height`](https://developer.mozilla.org/en-US/docs/Web/CSS/height) property instead.
[**`scope`**](#attr-scope) Deprecated
This enumerated attribute defines the cells that the header (defined in the [`<th>`](th)) element relates to. Only use this attribute with the `<th>` element to define the row or column for which it is a header.
[**`valign`**](#attr-valign) Deprecated
This attribute specifies how a text is vertically aligned inside a cell. Possible values for this attribute are:
* `baseline`: Positions the text near the bottom of the cell and aligns it with the [baseline](https://en.wikipedia.org/wiki/Baseline_%28typography%29) of the characters instead of the bottom. If characters don't descend below the baseline, the baseline value achieves the same effect as `bottom`.
* `bottom`: Positions the text near the bottom of the cell.
* `middle`: Centers the text in the cell.
* and `top`: Positions the text near the top of the cell.
To achieve a similar effect, use the CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property.
[**`width`**](#attr-width) Deprecated
This attribute is used to define a recommended cell width. Use the CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property instead.
Examples
--------
See [`<table>`](table) for examples on `<td>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | Sectioning root. |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | The start tag is mandatory.The end tag may be omitted, if it is immediately followed by a [`<th>`](th) or [`<td>`](td) element or if there are no more data in its parent element. |
| Permitted parents | A [`<tr>`](tr) element. |
| Implicit ARIA role | `[cell](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role)` if a descendant of a [`<table>`](table) element |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLTableCellElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-td-element](https://html.spec.whatwg.org/multipage/tables.html#the-td-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `td` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `abbr` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `axis` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `char` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `charoff` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `colspan` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `headers` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `rowspan` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `scope` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `valign` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `width` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
html <frameset> <frameset>
==========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<frameset>` [HTML](../index) element is used to contain [`<frame>`](frame) elements.
**Note:** Because the use of frames is now discouraged in favor of using [`<iframe>`](iframe), this element is not typically used by modern websites.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes).
[**`cols`**](#attr-cols) Deprecated
This attribute specifies the number and size of horizontal spaces in a frameset.
[**`rows`**](#attr-rows) Deprecated
This attribute specifies the number and size of vertical spaces in a frameset.
Example
-------
```
<frameset cols="50%,50%">
<frame
src="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frameset" />
<frame
src="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame" />
</frameset>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # frameset](https://html.spec.whatwg.org/multipage/obsolete.html#frameset) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `frameset` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `cols` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `rows` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* [`<frame>`](frame)
* [`<iframe>`](iframe)
| programming_docs |
html <cite>: The Citation element <cite>: The Citation element
============================
The `<cite>` [HTML](../index) element is used to describe a reference to a cited creative work, and must include the title of that work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
In the context of the `<cite>` element, a creative work that might be cited could be, for example, one of the following:
* A book
* A research paper
* An essay
* A poem
* A musical score
* A song
* A play or film script
* A film
* A television show
* A game
* A sculpture
* A painting
* A theatrical production
* A play
* An opera
* A musical
* An exhibition
* A legal case report
* A computer program
* A web site
* A web page
* A blog post or comment
* A forum post or comment
* A tweet
* A Facebook post
* A written or oral statement
* And so forth.
It's worth noting that the W3C specification says that a reference to a creative work, as included within a `<cite>` element, may include the name of the work's author. However, the WHATWG specification for `<cite>` says the opposite: that a person's name must *never* be included, under any circumstances.
To include a reference to the source of quoted material which is contained within a [`<blockquote>`](blockquote) or [`<q>`](q) element, use the [`cite`](blockquote#attr-cite) attribute on the element.
Typically, browsers style the contents of a `<cite>` element in italics by default. To avoid this, apply the CSS [`font-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) property to the `<cite>` element.
Example
-------
```
<p>More information can be found in <cite>[ISO-0000]</cite>.</p>
```
The HTML above outputs:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the [`HTMLSpanElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement) interface for this element. |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-cite-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-cite-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `cite` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The element [`<blockquote>`](blockquote) for long quotations.
* The element [`<q>`](q) for inline quotations.
html <map>: The Image Map element <map>: The Image Map element
============================
The `<map>` [HTML](../index) element is used with [`<area>`](area) elements to define an image map (a clickable link area).
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`name`**](#attr-name) The `name` attribute gives the map a name so that it can be referenced. The attribute must be present and must have a non-empty value with no space characters. The value of the `name` attribute must not be equal to the value of the `name` attribute of another `<map>` element in the same document. If the [`id`](../global_attributes#id) attribute is also specified, both attributes must have the same value.
Examples
--------
### Image map with two areas
Click the left-hand parrot for JavaScript, or the right-hand parrot for CSS.
#### HTML
```
<!-- Photo by Juliana e Mariana Amorim on Unsplash -->
<map name="primary">
<area
shape="circle"
coords="75,75,75"
href="https://developer.mozilla.org/docs/Web/JavaScript"
target="\_blank"
alt="JavaScript" />
<area
shape="circle"
coords="275,75,75"
href="https://developer.mozilla.org/docs/Web/CSS"
target="\_blank"
alt="CSS" />
</map>
<img
usemap="#primary"
src="parrots.jpg"
alt="350 x 150 picture of two parrots" />
```
#### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | Any [transparent](../content_categories#transparent_content_model) element. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLMapElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMapElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-map-element](https://html.spec.whatwg.org/multipage/image-maps.html#the-map-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `map` | 1 | 12 | 1
["Before Firefox 5, in Quirks Mode, empty maps were no longer skipped over in favor of non-empty ones when matching.", "Before Firefox 17, the default styling of the `<map>` HTML element was `display: block;`. This is now `display: inline;` and matches the behavior of the other browsers. It was already the case in Quirks Mode."] | Yes | Yes | 1 | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `name` | 1 | 12 | 1 | Yes | Yes | 1 | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
See also
--------
* [`<a>`](a)
* [`<area>`](area)
html <blink>: The Blinking Text element <blink>: The Blinking Text element
==================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<blink>` [HTML](../index) element is a non-standard element which causes the enclosed text to flash slowly.
**Warning:** Do not use this element as it is **obsolete** and is bad design practice. Blinking text is frowned upon by several accessibility standards and the CSS specification allows browsers to ignore the `<blink>` element.
DOM interface
-------------
This element is unsupported and thus implements the [`HTMLUnknownElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLUnknownElement) interface.
Example
-------
```
<blink>Why would somebody use this?</blink>
```
### Result (toned down!)
CSS polyfill
------------
If you really do need a polyfill, then you can use the following CSS polyfill. Works in IE10+.
```
blink {
animation: 2s linear infinite condemned_blink_effect;
}
@keyframes condemned\_blink\_effect {
0% {
visibility: hidden;
}
50% {
visibility: hidden;
}
100% {
visibility: visible;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # blink](https://html.spec.whatwg.org/multipage/obsolete.html#blink) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `blink` | No | No | 1-22 | No | 2-15 | No | No | No | 4-22 | 10.1-14 | No | No |
See also
--------
* [History of the creation of the HTML `<blink>` element](https://web.archive.org/web/20220331020029/http://www.montulli.org/theoriginofthe%3Cblink%3Etag).
* [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration), where a blink value exists, though browsers are not required to effectively make it blink.
* [`<marquee>`](marquee), another similar non-standard element.
* [CSS animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations) are the way to go to create such an effect.
html <th>: The Table Header element <th>: The Table Header element
==============================
The `<th>` [HTML](../index) element defines a cell as header of a group of table cells. The exact nature of this group is defined by the [`scope`](th#attr-scope) and [`headers`](th#attr-headers) attributes.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`abbr`**](#attr-abbr) This attribute contains a short abbreviated description of the cell's content. Some user-agents, such as speech readers, may present this description before the content itself.
[**`colspan`**](#attr-colspan) This attribute contains a non-negative integer value that indicates for how many columns the cell extends. Its default value is `1`. Values higher than 1000 will be considered as incorrect and will be set to the default value (1).
[**`headers`**](#attr-headers) This attribute contains a list of space-separated strings, each corresponding to the **id** attribute of the [`<th>`](th) elements that apply to this element.
[**`rowspan`**](#attr-rowspan) This attribute contains a non-negative integer value that indicates for how many rows the cell extends. Its default value is `1`; if its value is set to `0`, it extends until the end of the table section ([`<thead>`](thead), [`<tbody>`](tbody), [`<tfoot>`](tfoot), even if implicitly defined), that the cell belongs to. Values higher than 65534 are clipped down to 65534.
[**`scope`**](#attr-scope) This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute defines the cells that the header (defined in the [`<th>`](th)) element relates to. It may have the following values:
* `row`: The header relates to all cells of the row it belongs to.
* `col`: The header relates to all cells of the column it belongs to.
* `rowgroup`: The header belongs to a rowgroup and relates to all of its cells. These cells can be placed to the right or the left of the header, depending on the value of the [`dir`](../global_attributes/dir) attribute in the [`<table>`](table) element.
* `colgroup`: The header belongs to a colgroup and relates to all of its cells.
If the `scope` attribute is not specified, or its value is not `row`, `col`, or `rowgroup`, or `colgroup`, then browsers automatically select the set of cells to which the header cell applies.
### Deprecated attributes
[**`align`**](#attr-align) Deprecated
This enumerated attribute specifies how the cell content's horizontal alignment will be handled. Possible values are:
* `left`: The content is aligned to the left of the cell.
* `center`: The content is centered in the cell.
* `right`: The content is aligned to the right of the cell.
* `justify` (with text only): The content is stretched out inside the cell so that it covers its entire width.
* `char` (with text only): The content is aligned to a character inside the `<th>` element with minimal offset. This character is defined by the [`char`](th#attr-char) and [`charoff`](th#attr-charoff) attributes.
The default value when this attribute is not specified is `left`.
**Note:** Do not use this attribute as it is obsolete in the latest standard.
* To achieve the same effect as the `left`, `center`, `right` or `justify` values, apply the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to the element.
* To achieve the same effect as the `char` value, give the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property the same value you would use for the [`char`](th#attr-char).
[**`axis`**](#attr-axis) Deprecated
This attribute contains a list of space-separated strings. Each string is the `id` of a group of cells that this header applies to.
**Note:** Do not use this attribute as it is obsolete in the latest standard: use the [`scope`](th#attr-scope) attribute instead.
[**`bgcolor`**](#attr-bgcolor) Deprecated
This attribute defines the background color of each cell in a column. It consists of a 6-digit hexadecimal code as defined in [sRGB](https://www.w3.org/Graphics/Color/sRGB) and is prefixed by '#'.
[**`char`**](#attr-char) Deprecated
The content in the cell element is aligned to a character. Typical values include a period (.) to align numbers or monetary values. If [`align`](th#attr-align) is not set to `char`, this attribute is ignored.
**Note:** Do not use this attribute as it is obsolete in the latest standard. To achieve the same effect, you can specify the character as the first value of the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property.
[**`charoff`**](#attr-charoff) Deprecated
This attribute is used to shift column data to the right of the character specified by the **char** attribute. Its value specifies the length of this shift.
**Note:** Do not use this attribute as it is obsolete in the latest standard.
[**`height`**](#attr-height) Deprecated
This attribute is used to define a recommended cell height.
**Note:** Do not use this attribute as it is obsolete in the latest standard: use the CSS [`height`](https://developer.mozilla.org/en-US/docs/Web/CSS/height) property instead.
[**`valign`**](#attr-valign) Deprecated
This attribute specifies how a text is vertically aligned inside a cell. Possible values for this attribute are:
* `baseline`: Positions the text near the bottom of the cell and aligns it with the [baseline](https://en.wikipedia.org/wiki/Baseline_%28typography%29) of the characters instead of the bottom. If characters don't descend below the baseline, the baseline value achieves the same effect as `bottom`.
* `bottom`: Positions the text near the bottom of the cell.
* `middle`: Centers the text in the cell.
* and `top`: Positions the text near the top of the cell.
**Note:** Do not use this attribute as it is obsolete in the latest standard: use the CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property instead.
[**`width`**](#attr-width) Deprecated
This attribute is used to define a recommended cell width. Additional space can be added with the [`cellspacing`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/cellSpacing) and [`cellpadding`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/cellPadding) properties and the width of the [`<col>`](col) element can also create extra width. But, if a column's width is too narrow to show a particular cell properly, it will be widened when displayed.
**Note:** Do not use this attribute as it is obsolete in the latest standard: use the CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property instead.
Examples
--------
See [`<table>`](table) for examples on `<th>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Flow content](../content_categories#flow_content), but with no header, footer, sectioning content, or heading content descendants. |
| Tag omission | The start tag is mandatory.The end tag may be omitted, if it is immediately followed by a [`<th>`](th) or [`<td>`](td) element or if there are no more data in its parent element. |
| Permitted parents | A [`<tr>`](tr) element. |
| Implicit ARIA role | `[columnheader](https://w3c.github.io/aria/#columnheader)` or `[rowheader](https://w3c.github.io/aria/#rowheader)` |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLTableCellElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-th-element](https://html.spec.whatwg.org/multipage/tables.html#the-th-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `th` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `abbr` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `axis` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `char` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `charoff` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `colspan` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `headers` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `rowspan` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `scope` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `valign` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `width` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Other table-related HTML Elements: [`<caption>`](caption), [`<col>`](col), [`<colgroup>`](colgroup), [`<table>`](table), [`<tbody>`](tbody), [`<td>`](td), [`<tfoot>`](tfoot), [`<thead>`](thead), [`<tr>`](tr).
html <form>: The Form element <form>: The Form element
========================
The `<form>` [HTML](../index) element represents a document section containing interactive controls for submitting information.
Try it
------
It is possible to use the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS [pseudo-classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes) to style a `<form>` element based on whether the [`elements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements) inside the form are valid.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`accept`**](#attr-accept) Deprecated
Comma-separated [content types](https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type) the server accepts.
**Note:** **This attribute has been deprecated and should not be used.** Instead, use the [`accept`](input#attr-accept) attribute on `<input type=file>` elements.
[**`accept-charset`**](#attr-accept-charset) Space-separated [character encodings](https://developer.mozilla.org/en-US/docs/Glossary/Character_encoding) the server accepts. The browser uses them in the order in which they are listed. The default value means [the same encoding as the page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding). (In previous versions of HTML, character encodings could also be delimited by commas.)
[**`autocapitalize`**](#attr-autocapitalize) Non-standard
A nonstandard attribute used by iOS Safari that controls how textual form elements should be automatically capitalized. `autocapitalize` attributes on a form elements override it on `<form>`. Possible values:
* `none`: No automatic capitalization.
* `sentences` (default): Capitalize the first letter of each sentence.
* `words`: Capitalize the first letter of each word.
* `characters`: Capitalize all characters — that is, uppercase.
[**`autocomplete`**](#attr-autocomplete) Indicates whether input elements can by default have their values automatically completed by the browser. `autocomplete` attributes on form elements override it on `<form>`. Possible values:
* `off`: The browser may not automatically complete entries. (Browsers tend to ignore this for suspected login forms; see [The autocomplete attribute and login fields](https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#the_autocomplete_attribute_and_login_fields).)
* `on`: The browser may automatically complete entries.
[**`name`**](#attr-name) The name of the form. The value must not be the empty string, and must be unique among the `form` elements in the forms collection that it is in, if any.
[**`rel`**](#attr-rel) Controls the annotations and what kinds of links the form creates. Annotations include [`external`](../attributes/rel#attr-external), [`nofollow`](../attributes/rel#attr-nofollow), [`opener`](../attributes/rel#attr-opener), [`noopener`](../attributes/rel#attr-noopener), and [`noreferrer`](../attributes/rel#attr-noreferrer). Link types include [`help`](../attributes/rel#attr-help), [`prev`](../attributes/rel#attr-prev), [`next`](../attributes/rel#attr-next), [`search`](../attributes/rel#attr-search), and [`license`](../attributes/rel#attr-license). The [`rel`](../attributes/rel) value is a space-separated list of these enumerated values.
### Attributes for form submission
The following attributes control behavior during form submission.
[**`action`**](#attr-action) The URL that processes the form submission. This value can be overridden by a [`formaction`](button#attr-formaction) attribute on a [`<button>`](button), [`<input type="submit">`](input/submit), or [`<input type="image">`](input/image) element. This attribute is ignored when `method="dialog"` is set.
[**`enctype`**](#attr-enctype) If the value of the `method` attribute is `post`, `enctype` is the [MIME type](https://en.wikipedia.org/wiki/Mime_type) of the form submission. Possible values:
* `application/x-www-form-urlencoded`: The default value.
* `multipart/form-data`: Use this if the form contains [`<input>`](input) elements with `type=file`.
* `text/plain`: Useful for debugging purposes.
This value can be overridden by [`formenctype`](button#attr-formenctype) attributes on [`<button>`](button), [`<input type="submit">`](input/submit), or [`<input type="image">`](input/image) elements.
[**`method`**](#attr-method) The [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) method to submit the form with. The only allowed methods/values are (case insensitive):
* `post`: The [POST method](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5); form data sent as the [request body](https://developer.mozilla.org/en-US/docs/Web/API/Request/body).
* `get` (default): The [GET method](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3); form data appended to the `action` URL with a `?` separator. Use this method when the form [has no side effects](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent).
* `dialog`: When the form is inside a [`<dialog>`](dialog), closes the dialog and throws a submit event on submission without submitting data or clearing the form.
This value is overridden by [`formmethod`](button#attr-formmethod) attributes on [`<button>`](button), [`<input type="submit">`](input/submit), or [`<input type="image">`](input/image) elements.
[**`novalidate`**](#attr-novalidate) This Boolean attribute indicates that the form shouldn't be validated when submitted. If this attribute is not set (and therefore the form ***is*** validated), it can be overridden by a [`formnovalidate`](button#attr-formnovalidate) attribute on a [`<button>`](button), [`<input type="submit">`](input/submit), or [`<input type="image">`](input/image) element belonging to the form.
[**`target`**](#attr-target) Indicates where to display the response after submitting the form. It is a name/keyword for a *browsing context* (for example, tab, window, or iframe). The following keywords have special meanings:
* `_self` (default): Load into the same browsing context as the current one.
* `_blank`: Load into a new unnamed browsing context. This provides the same behavior as setting [`rel="noopener"`](#attr-rel) which does not set [`window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener).
* `_parent`: Load into the parent browsing context of the current one. If no parent, behaves the same as `_self`.
* `_top`: Load into the top-level browsing context (i.e., the browsing context that is an ancestor of the current one and has no parent). If no parent, behaves the same as `_self`.
This value can be overridden by a [`formtarget`](button#attr-formtarget) attribute on a [`<button>`](button), [`<input type="submit">`](input/submit), or [`<input type="image">`](input/image) element.
Examples
--------
### HTML
```
<!-- Form which will send a GET request to the current URL -->
<form method="get">
<label>Name:
<input name="submitted-name" autocomplete="name" />
</label>
<button>Save</button>
</form>
<!-- Form which will send a POST request to the current URL -->
<form method="post">
<label>Name:
<input name="submitted-name" autocomplete="name" />
</label>
<button>Save</button>
</form>
<!-- Form with fieldset, legend, and label -->
<form method="post">
<fieldset>
<legend>Do you agree to the terms?</legend>
<label><input type="radio" name="radio" value="yes" /> Yes</label>
<label><input type="radio" name="radio" value="no" /> No</label>
</fieldset>
</form>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [palpable content](../content_categories#palpable_content) |
| Permitted content | [Flow content](../content_categories#flow_content), but not containing `<form>` elements |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content) |
| Implicit ARIA role | `[form](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/form_role)` if the form has an [accessible name](https://www.w3.org/TR/accname-1.1/#dfn-accessible-name), otherwise [no corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[search](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/search_role)`, `[none](https://w3c.github.io/aria/#none)` or `[presentation](https://w3c.github.io/aria/#presentation)` |
| DOM interface | [`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-form-element](https://html.spec.whatwg.org/multipage/forms.html#the-form-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `form` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `accept` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `accept-charset` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `action` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `autocapitalize` | No | No | No | No | No | No | No | No | No | No | Yes | No |
| `autocomplete` | Yes
The Google Chrome UI for auto-complete request varies, depending on whether `autocomplete` is set to `off` on `<input>` elements as well as their form. Specifically, when a form has `autocomplete` set to `off` and its `<input>` element's `autocomplete` attribute is not set, then if the user asks for autofill suggestions for the `<input>` element, Chrome might display a message saying 'autocomplete has been disabled for this form.' On the other hand, if both the form and the input element have `autocomplete` set to `off`, the browser will not display that message. For this reason, you should set `autocomplete` to `off` for each `<input>` that has custom auto-completion. | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `enctype` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `method` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `name` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `novalidate` | 10 | 12 | 4 | 10 | 15 | 10.1 | 37 | 18 | 4 | 14 | 10.3 | 1.0 |
| `target` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms)
* Other elements that are used when creating forms: [`<button>`](button), [`<datalist>`](datalist), [`<fieldset>`](fieldset), [`<input>`](input), [`<label>`](label), [`<legend>`](legend), [`<meter>`](meter), [`<optgroup>`](optgroup), [`<option>`](option), [`<output>`](output), [`<progress>`](progress), [`<select>`](select), [`<textarea>`](textarea).
* Getting a list of the elements in the form: [`HTMLFormElement.elements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements)
* [ARIA: Form role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/form_role)
* [ARIA: Search role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/search_role)
| programming_docs |
html <image>: The Image element <image>: The Image element
==========================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The `<image>` [HTML](../index) element is an ancient and poorly supported precursor to the [`<img>`](img) element. **It should not be used**.
Some browsers will attempt to automatically convert this into an [`<img>`](img) element, and may succeed if the [`src`](img#attr-src) attribute is specified as well.
Specifications
--------------
This does not appear to have been part of any formal specification. It was mentioned in [HTML+ Discussion Document - Dave Raggett, November 8, 1993](https://www.w3.org/MarkUp/HTMLPlus/htmlplus_21.html) (Section 5.9 - Images), but was not part of the first revision of [HyperText Markup Language Specification - 2.0](https://datatracker.ietf.org/doc/html/draft-ietf-html-spec-00) in 1994.
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `image` | No | No | Yes
Before Firefox 22, creating an <image> element incorrectly resulted in an `HTMLSpanElement` object, instead of the expected `HTMLElement`. | No | No | No | No | No | Yes
Before Firefox 22, creating an <image> element incorrectly resulted in an `HTMLSpanElement` object, instead of the expected `HTMLElement`. | No | No | No |
See also
--------
* [`<img>`](img): The correct way to display an image in a document
* [`<picture>`](picture): A more powerful correct way to display an image in a document
html <thead>: The Table Head element <thead>: The Table Head element
===============================
The `<thead>` [HTML](../index) element defines a set of rows defining the head of the columns of the table.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
### Deprecated attributes
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute specifies how horizontal alignment of each cell content will be handled. Possible values are:
* `left`, aligning the content to the left of the cell
* `center`, centering the content in the cell
* `right`, aligning the content to the right of the cell
* `justify`, inserting spaces into the textual content so that the content is justified in the cell
* `char`, aligning the textual content on a special character with a minimal offset, defined by the [`char`](thead#attr-char) and [`charoff`](thead#attr-charoff) attributes.
If this attribute is not set, the `left` value is assumed.
**Warning:** Do not use this attribute as it is obsolete (not supported) in the latest standard.
* To align values, use the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property instead.
[**`bgcolor`**](#attr-bgcolor) Deprecated
This attribute defines the background color of each column cell. It accepts a 6-digit hexadecimal color or a named color. Alpha transparency is not supported.
**Note:** Do not use this attribute, as it is non-standard. The `thead` element should be styled using the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property, which can be applied to any element, including the `thead`, [`<tr>`](tr), [`<td>`](td) and [`<th>`](th) elements.
[**`char`**](#attr-char) Deprecated
This attribute is used to set the character to align the cells in a column on. Typical values for this include a period (.) when attempting to align numbers or monetary values. If [`align`](thead#attr-align) is not set to `char`, this attribute is ignored.
**Note:** Do not use this attribute as it is obsolete (and not supported) in the latest standard.
[**`charoff`**](#attr-charoff) Deprecated
This attribute is used to indicate the number of characters to offset the column data from the alignment characters specified by the **char** attribute.
**Note:** Do not use this attribute as it is obsolete (and not supported) in the latest standard.
[**`valign`**](#attr-valign) Deprecated
This attribute specifies the vertical alignment of the text within each row of cells of the table header. Possible values for this attribute are:
* `baseline`, which will put the text as close to the bottom of the cell as it is possible, but align it on the [baseline](https://en.wikipedia.org/wiki/Baseline_%28typography%29) of the characters instead of the bottom of them. If characters are all of the size, this has the same effect as `bottom`.
* `bottom`, which will put the text as close to the bottom of the cell as it is possible;
* `middle`, which will center the text in the cell;
* `top`, which will put the text as close to the top of the cell as it is possible.
**Note:** Do not use this attribute as it is obsolete (and not supported) in the latest standard: instead set the CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property on it.
Examples
--------
See [`<table>`](table) for examples on `<thead>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | Zero or more [`<tr>`](tr) elements. |
| Tag omission | The start tag is mandatory. The end tag may be omitted if the [`<thead>`](thead) element is immediately followed by a [`<tbody>`](tbody) or [`<tfoot>`](tfoot) element. |
| Permitted parents | A [`<table>`](table) element. The [`<thead>`](thead) must appear after any [`<caption>`](caption) or [`<colgroup>`](colgroup) element, even implicitly defined, but before any [`<tbody>`](tbody), [`<tfoot>`](tfoot) and [`<tr>`](tr) element. |
| Implicit ARIA role | `[rowgroup](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/rowgroup_role)` |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLTableSectionElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableSectionElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-thead-element](https://html.spec.whatwg.org/multipage/tables.html#the-thead-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `thead` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `char` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `charoff` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `valign` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
See also
--------
* Other table-related HTML Elements: [`<caption>`](caption), [`<col>`](col), [`<colgroup>`](colgroup), [`<table>`](table), [`<tbody>`](tbody), [`<td>`](td), [`<tfoot>`](tfoot), [`<th>`](th), [`<tr>`](tr);
* CSS properties and pseudo-classes that may be specially useful to style the `<thead>` element:
+ the [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child) pseudo-class to set the alignment on the cells of the column;
+ the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to align all cells content on the same character, like '.'.
html <rp>: The Ruby Fallback Parenthesis element <rp>: The Ruby Fallback Parenthesis element
===========================================
The `<rp>` [HTML](../index) element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the [`<ruby>`](ruby) element. One `<rp>` element should enclose each of the opening and closing parentheses that wrap the [`<rt>`](rt) element that contains the annotation's text.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Ruby annotations are for showing pronunciation of East Asian characters, like using Japanese furigana or Taiwanese bopomofo characters. The `<rp>` element is used in the case of lack of [`<ruby>`](ruby) element support; the `<rp>` content provides what should be displayed in order to indicate the presence of a ruby annotation, usually parentheses.
Examples
--------
### Using ruby annotations
This example uses ruby annotations to display the [Romaji](https://en.wikipedia.org/wiki/Romaji) equivalents for each character.
```
<ruby>
漢 <rp>(</rp><rt>Kan</rt><rp>)</rp>
字 <rp>(</rp><rt>ji</rt><rp>)</rp>
</ruby>
```
The result looks like this in your browser:
See the article about the [`<ruby>`](ruby) element for further examples.
### Without ruby support
If your browser does not support ruby annotations, the result looks like this instead:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | Text |
| Tag omission | The end tag can be omitted if the element is immediately followed by an [`<rt>`](rt) or another `<rp>` element, or if there is no more content in the parent element. |
| Permitted parents | A [`<ruby>`](ruby) element. `<rp>` must be positioned immediately before or after an [`<rt>`](rt) element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-rp-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-rp-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `rp` | 5 | 79 | 38 | 5 | 15 | 5 | Yes | Yes | 38 | 14 | Yes | Yes |
See also
--------
* [`<ruby>`](ruby)
* [`<rt>`](rt)
* [`<rb>`](rb)
* [`<rtc>`](rtc)
html <link>: The External Resource Link element <link>: The External Resource Link element
==========================================
The `<link>` [HTML](../index) element specifies relationships between the current document and an external resource. This element is most commonly used to link to [stylesheets](https://developer.mozilla.org/en-US/docs/Glossary/CSS), but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things.
Try it
------
To link an external stylesheet, you'd include a `<link>` element inside your [`<head>`](head) like this:
```
<link href="main.css" rel="stylesheet" />
```
This simple example provides the path to the stylesheet inside an `href` attribute, and a `rel` attribute with a value of `stylesheet`. The `rel` stands for "relationship", and is one of the key features of the `<link>` element — the value denotes how the item being linked to is related to the containing document. As you'll see from our [Link types](../link_types) reference, there are many kinds of relationship.
There are a number of other common types you'll come across. For example, a link to the site's favicon:
```
<link rel="icon" href="favicon.ico" />
```
There are a number of other icon `rel` values, mainly used to indicate special icon types for use on various mobile platforms, e.g.:
```
<link
rel="apple-touch-icon-precomposed"
sizes="114x114"
href="apple-icon-114.png"
type="image/png" />
```
The `sizes` attribute indicates the icon size, while the `type` contains the MIME type of the resource being linked. These provide useful hints to allow the browser to choose the most appropriate icon available.
You can also provide a media type or query inside a `media` attribute; this resource will then only be loaded if the media condition is true. For example:
```
<link href="print.css" rel="stylesheet" media="print" />
<link
href="mobile.css"
rel="stylesheet"
media="screen and (max-width: 600px)" />
```
Some interesting new performance and security features have been added to the `<link>` element too. Take this example:
```
<link
rel="preload"
href="myFont.woff2"
as="font"
type="font/woff2"
crossorigin="anonymous" />
```
A `rel` value of `preload` indicates that the browser should preload this resource (see [Preloading content with rel="preload"](../link_types/preload) for more details), with the `as` attribute indicating the specific class of content being fetched. The `crossorigin` attribute indicates whether the resource should be fetched with a [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) request.
Other usage notes:
* A `<link>` element can occur either in the [`<head>`](head) or [`<body>`](body) element, depending on whether it has a [link type](https://html.spec.whatwg.org/multipage/links.html#body-ok) that is **body-ok**. For example, the `stylesheet` link type is body-ok, and therefore `<link rel="stylesheet">` is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your `<link>` elements from your body content, putting them in the `<head>`.
* When using `<link>` to establish a favicon for a site, and your site uses a Content Security Policy (CSP) to enhance its security, the policy applies to the favicon. If you encounter problems with the favicon not loading, verify that the [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) header's [`img-src` directive](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/img-src) is not preventing access to it.
* The HTML and XHTML specifications define event handlers for the `<link>` element, but it is unclear how they would be used.
* Under XHTML 1.0, [void elements](https://developer.mozilla.org/en-US/docs/Glossary/Void_element) such as `<link>` require a trailing slash: `<link />`.
* WebTV supports the use of the value `next` for `rel` to preload the next page in a document series.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`as`**](#attr-as) This attribute is only used when `rel="preload"` or `rel="prefetch"` has been set on the `<link>` element. It specifies the type of content being loaded by the `<link>`, which is necessary for request matching, application of correct [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), and setting of correct [`Accept`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) request header. Furthermore, `rel="preload"` uses this as a signal for request prioritization. The table below lists the valid values for this attribute and the elements or resources they apply to.
| Value | Applies To |
| --- | --- |
| audio | `<audio>` elements |
| document | `<iframe>` and `<frame>` elements |
| embed | `<embed>` elements |
| fetch | fetch, XHR **Note:** This value also requires `<link>` to contain the crossorigin attribute. |
| font | CSS @font-face |
| image | `<img>` and `<picture>` elements with srcset or imageset attributes, SVG `<image>` elements, CSS `*-image` rules |
| object | `<object>` elements |
| script | `<script>` elements, Worker `importScripts` |
| style | `<link rel=stylesheet>` elements, CSS `@import` |
| track | `<track>` elements |
| video | `<video>` elements |
| worker | Worker, SharedWorker |
[**`crossorigin`**](#attr-crossorigin) This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute indicates whether [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) must be used when fetching the resource. [CORS-enabled images](../cors_enabled_image) can be reused in the [`<canvas>`](canvas) element without being *tainted*. The allowed values are:
`anonymous` A cross-origin request (i.e. with an [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) HTTP header) is performed, but no credential is sent (i.e. no cookie, X.509 certificate, or HTTP Basic authentication). If the server does not give credentials to the origin site (by not setting the [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) HTTP header) the resource will be tainted and its usage restricted.
`use-credentials` A cross-origin request (i.e. with an `Origin` HTTP header) is performed along with a credential sent (i.e. a cookie, certificate, and/or HTTP Basic authentication is performed). If the server does not give credentials to the origin site (through [`Access-Control-Allow-Credentials`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials) HTTP header), the resource will be *tainted* and its usage restricted.
If the attribute is not present, the resource is fetched without a [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) request (i.e. without sending the `Origin` HTTP header), preventing its non-tainted usage. If invalid, it is handled as if the enumerated keyword **anonymous** was used. See [CORS settings attributes](../attributes/crossorigin) for additional information.
[**`disabled`**](#attr-disabled) Deprecated Non-standard
For `rel="stylesheet"` only, the `disabled` Boolean attribute indicates whether the described stylesheet should be loaded and applied to the document. If `disabled` is specified in the HTML when it is loaded, the stylesheet will not be loaded during page load. Instead, the stylesheet will be loaded on-demand, if and when the `disabled` attribute is changed to `false` or removed.
Setting the `disabled` property in the DOM causes the stylesheet to be removed from the document's [`Document.styleSheets`](https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets) list.
[**`fetchpriority`**](#attr-fetchpriority) Experimental
Provides a hint of the relative priority to use when fetching a preloaded resource. Allowed values:
`high` Signals a high-priority fetch relative to other resources of the same type.
`low` Signals a low-priority fetch relative to other resources of the same type.
`auto` Default: Signals automatic determination of fetch priority relative to other resources of the same type.
[**`href`**](#attr-href) This attribute specifies the [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL) of the linked resource. A URL can be absolute or relative.
[**`hreflang`**](#attr-hreflang) This attribute indicates the language of the linked resource. It is purely advisory. Allowed values are specified by [RFC 5646: Tags for Identifying Languages (also known as BCP 47)](https://datatracker.ietf.org/doc/html/rfc5646). Use this attribute only if the [`href`](a#attr-href) attribute is present.
[**`imagesizes`**](#attr-imagesizes) For `rel="preload"` and `as="image"` only, the `imagesizes` attribute is [a sizes attribute](https://html.spec.whatwg.org/multipage/images.html#sizes-attribute) that indicates to preload the appropriate resource used by an `img` element with corresponding values for its `srcset` and `sizes` attributes.
[**`imagesrcset`**](#attr-imagesrcset) For `rel="preload"` and `as="image"` only, the `imagesrcset` attribute is [a sourceset attribute](https://html.spec.whatwg.org/multipage/images.html#srcset-attribute) that indicates to preload the appropriate resource used by an `img` element with corresponding values for its `srcset` and `sizes` attributes.
[**`integrity`**](#attr-integrity) Contains inline metadata — a base64-encoded cryptographic hash of the resource (file) you're telling the browser to fetch. The browser can use this to verify that the fetched resource has been delivered free of unexpected manipulation. See [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
[**`media`**](#attr-media) This attribute specifies the media that the linked resource applies to. Its value must be a media type / [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries). This attribute is mainly useful when linking to external stylesheets — it allows the user agent to pick the best adapted one for the device it runs on.
**Note:**
* In HTML 4, this can only be a simple white-space-separated list of media description literals, i.e., [media types and groups](https://developer.mozilla.org/en-US/docs/Web/CSS/@media), where defined and allowed as values for this attribute, such as `print`, `screen`, `aural`, `braille`. HTML5 extended this to any kind of [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries), which are a superset of the allowed values of HTML 4.
* Browsers not supporting [CSS Media Queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) won't necessarily recognize the adequate link; do not forget to set fallback links, the restricted set of media queries defined in HTML 4.
[**`prefetch`**](#attr-prefetch) Secure context Experimental
Identifies a resource that might be required by the next navigation and that the user agent should retrieve it. This allows the user agent to respond faster when the resource is requested in the future.
[**`referrerpolicy`**](#attr-referrerpolicy) A string indicating which referrer to use when fetching the resource:
* `no-referrer` means that the [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent.
* `no-referrer-when-downgrade` means that no [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will be sent when navigating to an origin without TLS (HTTPS). This is a user agent's default behavior, if no policy is otherwise specified.
* `origin` means that the referrer will be the origin of the page, which is roughly the scheme, the host, and the port.
* `origin-when-cross-origin` means that navigating to other origins will be limited to the scheme, the host, and the port, while navigating on the same origin will include the referrer's path.
* `unsafe-url` means that the referrer will include the origin and the path (but not the fragment, password, or username). This case is unsafe because it can leak origins and paths from TLS-protected resources to insecure origins.
[**`rel`**](#attr-rel) This attribute names a relationship of the linked document to the current document. The attribute must be a space-separated list of [link type values](../link_types).
[**`sizes`**](#attr-sizes) Experimental
This attribute defines the sizes of the icons for visual media contained in the resource. It must be present only if the [`rel`](link#attr-rel) contains a value of `icon` or a non-standard type such as Apple's `apple-touch-icon`. It may have the following values:
* `any`, meaning that the icon can be scaled to any size as it is in a vector format, like `image/svg+xml`.
* a white-space separated list of sizes, each in the format `<width in pixels>x<height in pixels>` or `<width in pixels>X<height in pixels>`. Each of these sizes must be contained in the resource.
**Note:** Most icon formats are only able to store one single icon; therefore most of the time the [`sizes`](../global_attributes#sizes) attribute contains only one entry. MS's ICO format does, as well as Apple's ICNS. ICO is more ubiquitous, so you should use this format if cross-browser support is a concern (especially for old IE versions).
[**`title`**](#attr-title) The `title` attribute has special semantics on the `<link>` element. When used on a `<link rel="stylesheet">` it defines a [default or an alternate stylesheet](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets).
[**`type`**](#attr-type) This attribute is used to define the type of the content linked to. The value of the attribute should be a MIME type such as **text/html**, **text/css**, and so on. The common use of this attribute is to define the type of stylesheet being referenced (such as **text/css**), but given that CSS is the only stylesheet language used on the web, not only is it possible to omit the `type` attribute, but is actually now recommended practice. It is also used on `rel="preload"` link types, to make sure the browser only downloads file types that it supports.
[**`blocking`**](#attr-blocking) This attribute explicitly indicates that certain operations should be blocked on the fetching of an external resource. The operations that are to be blocked must be a space-separated list of blocking attributes listed below.
* `render`: The rendering of content on the screen is blocked.
### Non-standard attributes
[**`methods`**](#attr-methods) Non-standard Deprecated
The value of this attribute provides information about the functions that might be performed on an object. The values generally are given by the HTTP protocol when it is used, but it might (for similar reasons as for the **title** attribute) be useful to include advisory information in advance in the link. For example, the browser might choose a different rendering of a link as a function of the methods specified; something that is searchable might get a different icon, or an outside link might render with an indication of leaving the current site. This attribute is not well understood nor supported, even by the defining browser, Internet Explorer 4.
[**`target`**](#attr-target) Deprecated
Defines the frame or window name that has the defined linking relationship or that will show the rendering of any linked resource.
### Obsolete attributes
[**`charset`**](#attr-charset) Deprecated
This attribute defines the character encoding of the linked resource. The value is a space- and/or comma-delimited list of character sets as defined in [RFC 2045](https://datatracker.ietf.org/doc/html/rfc2045). The default value is `iso-8859-1`.
**Note:** To produce the same effect as this obsolete attribute, use the [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header on the linked resource.
[**`rev`**](#attr-rev) Deprecated
The value of this attribute shows the relationship of the current document to the linked document, as defined by the [`href`](link#attr-href) attribute. The attribute thus defines the reverse relationship compared to the value of the `rel` attribute. [Link type values](../link_types) for the attribute are similar to the possible values for [`rel`](link#attr-rel).
**Note:** Instead of `rev`, you should use the [`rel`](link#attr-rel) attribute with the opposite [link type value](../link_types). For example, to establish the reverse link for `made`, specify `author`. Also, this attribute doesn't stand for "revision" and must not be used with a version number, even though many sites misuse it in this way.
Examples
--------
### Including a stylesheet
To include a stylesheet in a page, use the following syntax:
```
<link href="style.css" rel="stylesheet" />
```
### Providing alternative stylesheets
You can also specify [alternative style sheets](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets).
The user can choose which style sheet to use by choosing it from the **View > Page Style** menu. This provides a way for users to see multiple versions of a page.
```
<link href="default.css" rel="stylesheet" title="Default Style" />
<link href="fancy.css" rel="alternate stylesheet" title="Fancy" />
<link href="basic.css" rel="alternate stylesheet" title="Basic" />
```
### Providing icons for different usage contexts
You can include links to several icons on the same page, and the browser will choose which one works best for its particular context using the `rel` and `sizes` values as hints.
```
<!-- third-generation iPad with high-resolution Retina display: -->
<link
rel="apple-touch-icon-precomposed"
sizes="144x144"
href="favicon144.png" />
<!-- iPhone with high-resolution Retina display: -->
<link
rel="apple-touch-icon-precomposed"
sizes="114x114"
href="favicon114.png" />
<!-- first- and second-generation iPad: -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon72.png" />
<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
<link rel="apple-touch-icon-precomposed" href="favicon57.png" />
<!-- basic favicon -->
<link rel="icon" href="favicon32.png" />
```
### Conditionally loading resources with media queries
You can provide a media type or query inside a `media` attribute; this resource will then only be loaded if the media condition is true. For example:
```
<link href="print.css" rel="stylesheet" media="print" />
<link href="mobile.css" rel="stylesheet" media="all" />
<link
href="desktop.css"
rel="stylesheet"
media="screen and (min-width: 600px)" />
<link
href="highres.css"
rel="stylesheet"
media="screen and (min-resolution: 300dpi)" />
```
### Stylesheet load events
You can determine when a style sheet has been loaded by watching for a `load` event to fire on it; similarly, you can detect if an error has occurred while processing a style sheet by watching for an `error` event:
```
<script>
const stylesheet = document.querySelector("#my-stylesheet");
stylesheet.onload = () => {
// Do something interesting; the sheet has been loaded
};
stylesheet.onerror = () => {
console.log("An error occurred loading the stylesheet!");
};
</script>
<link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet" />
```
**Note:** The `load` event fires once the stylesheet and all of its imported content has been loaded and parsed, and immediately before the styles start being applied to the content.
### Preload examples
You can find a number of `<link rel="preload">` examples in [Preloading content with `rel="preload"`](../link_types/preload).
### Blocking rendering till a resource is fetched
You can include `render` token inside a `blocking` attribute; the rendering of the page will be blocked till the resource is fetched. For example:
```
<link blocking="render" href="critical-font.woff2" as="font">
```
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | Metadata content. If `[itemprop](../global_attributes/itemprop)` is present: [Flow content](../content_categories#flow_content) and [phrasing content](../content_categories#phrasing_content). |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | As it is a void element, the start tag must be present and the end tag must not be present |
| Permitted parents | Any element that accepts metadata elements. If [itemprop](../global_attributes/itemprop) is present: any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | `[link](https://w3c.github.io/aria/#link)` with `href` attribute |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLLinkElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-link-element](https://html.spec.whatwg.org/multipage/semantics.html#the-link-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `link` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `charset` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `crossorigin` | 34 | 17 | 18
Before Firefox 83, `crossorigin` is not supported for `rel="icon"`. | No | 21 | 10 | 37 | 34 | 18
Before Firefox 83, `crossorigin` is not supported for `rel="icon"`. | 21 | 10 | 2.0 |
| `disabled` | 1
In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 12
Since Edge 79, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 1 | ≤6 | ≤12.1
In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | ≤4 | 1
In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 18
In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 4 | ≤12.1
In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | ≤3 | 1.0
In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. |
| `fetchpriority` | 101 | 101 | No | No | No | No | 101 | 101 | No | 70 | No | 19.0 |
| `href` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `hreflang` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `imagesizes` | 73 | 79 | 78 | No | 60 | No | 73 | 73 | 79 | 52 | No | 11.0 |
| `imagesrcset` | 73 | 79 | 78 | No | 60 | No | 73 | 73 | 79 | 52 | No | 11.0 |
| `integrity` | 45 | 17 | 43 | No | 32 | 11.1 | 45 | 45 | 43 | 32 | 11.3 | 5.0 |
| `media` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `methods` | No | 12-79 | No | 4 | No | No | No | No | No | No | No | No |
| `prefetch` | 56 | ≤79 | No | No | 43 | No | 56 | 56 | No | 43 | No | 6.0 |
| `referrerpolicy` | 51 | 79 | 50 | No | 38 | 14 | 51 | 51 | 50 | 41 | 14 | 7.2 |
| `rel` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `rev` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `sizes` | No | No | No
See [bug 441770](https://bugzil.la/441770). | No | No | No | No | No | No
See [bug 441770](https://bugzil.la/441770). | No | No | No |
| `target` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `title` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
See also
--------
* [`Link`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) HTTP header
| programming_docs |
html <pre>: The Preformatted Text element <pre>: The Preformatted Text element
====================================
The `<pre>` [HTML](../index) element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional, or [monospaced](https://en.wikipedia.org/wiki/Monospaced_font), font. Whitespace inside this element is displayed as written.
Try it
------
If you have to display reserved characters such as `<`, `>`, `&`, and `"` within the `<pre>` tag, the characters must be escaped using their respective [HTML entity](https://developer.mozilla.org/en-US/docs/Glossary/Entity).
Attributes
----------
This element only includes the [global attributes](../global_attributes).
[**`cols`**](#attr-cols) Non-standard Deprecated
Contains the *preferred* count of characters that a line should have. It was a non-standard synonym of [`width`](pre#attr-width). To achieve such an effect, use CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) instead.
[**`width`**](#attr-width) Deprecated Non-standard
Contains the *preferred* count of characters that a line should have. Though technically still implemented, this attribute has no visual effect; to achieve such an effect, use CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) instead.
[**`wrap`**](#attr-wrap) Non-standard Deprecated
Is a *hint* indicating how the overflow must happen. In modern browser this hint is ignored and no visual effect results in its present; to achieve such an effect, use CSS [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) instead.
Accessibility concerns
----------------------
It is important to provide an alternate description for any images or diagrams created using preformatted text. The alternate description should clearly and concisely describe the image or diagram's content.
People experiencing low vision conditions and browsing with the aid of assistive technology such as a screen reader may not understand what the preformatted text characters are representing when they are read out in sequence.
A combination of the [`<figure>`](figure) and [`<figcaption>`](figcaption) elements, supplemented by the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) `role` and [`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attributes on the `pre` element allow the preformatted ASCII art to be announced as an image with alternative text, and the `figcaption` serving as the image's caption.
### Example
```
<figure>
<pre role="img" aria-label="ASCII COW">
___________________________
< I'm an expert in my field. >
---------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
</pre>
<figcaption id="cow-caption">
A cow saying, "I'm an expert in my field." The cow is illustrated using
preformatted text characters.
</figcaption>
</figure>
```
* [MDN Understanding WCAG, Guideline 1.1 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.1_%E2%80%94_providing_text_alternatives_for_non-text_content)
* [H86: Providing text alternatives for ASCII art, emoticons, and leetspeak | W3C Techniques for WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/H86.html)
Examples
--------
### Basic example
#### HTML
```
<p>Using CSS to change the font color is easy.</p>
<pre>
body {
color: red;
}
</pre>
```
#### Result
### Escaping reserved characters
#### HTML
```
<pre>
let i = 5;
if (i < 10 && i > 0)
return "Single Digit Number"
</pre>
```
#### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLPreElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLPreElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-pre-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `pre` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `cols` | No | No | 1-29 | No | No | No | No | No | 4-29 | No | No | No |
| `width` | Yes
Specifying the `width` attribute has no layout effect. | 12
Specifying the `width` attribute has no layout effect. | 1
Since Firefox 29, specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. | 4
Since Firefox 29, specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. | Yes
Specifying the `width` attribute has no layout effect. |
| `wrap` | No | No | 1 | No | No | No | No | No | 4 | No | No | No |
See also
--------
* CSS: [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space), [`word-break`](https://developer.mozilla.org/en-US/docs/Web/CSS/word-break)
* [HTML Entity](https://developer.mozilla.org/en-US/docs/Glossary/Entity)
* Related element: [`<code>`](code)
html <label>: The Label element <label>: The Label element
==========================
The `<label>` [HTML](../index) element represents a caption for an item in a user interface.
Try it
------
Associating a `<label>` with a form control, such as [`<input>`](input) or [`<textarea>`](textarea) offers some major advantages:
* The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
* When a user clicks or touches/taps a label, the browser passes the focus to its associated input (the resulting event is also raised for the input). That increased hit area for focusing the input provides an advantage to anyone trying to activate it — including those using a touch-screen device.
To explicitly associate a `<label>` element with an `<input>` element, you first need to add the `id` attribute to the `<input>` element. Next, you add the `for` attribute to the `<label>` element, where the value of `for` is the same as the `id` in the `<input>` element.
Alternatively, you can nest the `<input>` directly inside the `<label>`, in which case the `for` and `id` attributes are not needed because the association is implicit:
```
<label>
Do you like peas?
<input type="checkbox" name="peas" />
</label>
```
The form control that a label is labeling is called the *labeled control* of the label element. Multiple labels can be associated with the same form control:
```
<label for="username">Enter your username:</label>
<input id="username" name="username" type="text" />
<label for="username">Forgot your username?</label>
```
Elements that can be associated with a `<label>` element include [`<button>`](button), [`<input>`](input) (except for `type="hidden"`), [`<meter>`](meter), [`<output>`](output), [`<progress>`](progress), [`<select>`](select) and [`<textarea>`](textarea).
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`for`**](#attr-for) The value of the `for` attribute must be a single [`id`](../global_attributes#id) for a [labelable](../content_categories#labelable) form-related element in the same document as the `<label>` element. So, any given `label` element can be associated with only one form control.
**Note:** To programmatically set the `for` attribute, use [`htmlFor`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor).
The first element in the document with an `id` attribute matching the value of the `for` attribute is the *labeled control* for this `label` element — if the element with that `id` is actually a [labelable element](https://html.spec.whatwg.org/multipage/forms.html#category-label). If it is *not* a labelable element, then the `for` attribute has no effect. If there are other elements that also match the `id` value, later in the document, they are not considered.
Multiple `label` elements can be given the same value for their `for` attribute; doing so causes the associated form control (the form control that `for` value references) to have multiple labels.
**Note:** A `<label>` element can have both a `for` attribute and a contained control element, as long as the `for` attribute points to the contained control element.
Styling with CSS
----------------
There are no special styling considerations for `<label>` elements — structurally they are simple inline elements, and so can be styled in much the same way as a [`<span>`](span) or [`<a>`](a) element. You can apply styling to them in any way you want, as long as you don't cause the text to become difficult to read.
Examples
--------
### Defining an implicit label
```
<label>Click me <input type="text" /></label>
```
### Defining an explicit label with the "for" attribute
```
<label for="username">Click me to focus on the input field</label>
<input type="text" id="username" />
```
Accessibility concerns
----------------------
### Interactive content
Don't place interactive elements such as [anchors](a) or [buttons](button) inside a `label`. Doing so makes it difficult for people to activate the form input associated with the `label`.
#### Don't
```
<label for="tac">
<input id="tac" type="checkbox" name="terms-and-conditions" />
I agree to the <a href="terms-and-conditions.html">Terms and Conditions</a>
</label>
```
#### Do
```
<label for="tac">
<input id="tac" type="checkbox" name="terms-and-conditions" />
I agree to the Terms and Conditions
</label>
<p>
<a href="terms-and-conditions.html">Read our Terms and Conditions</a>
</p>
```
### Headings
Placing [heading elements](heading_elements) within a `<label>` interferes with many kinds of assistive technology, because headings are commonly used as [a navigation aid](heading_elements#navigation). If the label's text needs to be adjusted visually, use CSS classes applied to the `<label>` element instead.
If a <form>, or a section of a form needs a title, use the [`<legend>`](legend) element placed within a [`<fieldset>`](fieldset).
#### Don't
```
<label for="your-name">
<h3>Your name</h3>
<input id="your-name" name="your-name" type="text" />
</label>
```
#### Do
```
<label class="large-label" for="your-name">
Your name
<input id="your-name" name="your-name" type="text" />
</label>
```
### Buttons
An [`<input>`](input) element with a `type="button"` declaration and a valid `value` attribute does not need a label associated with it. Doing so may actually interfere with how assistive technology parses the button input. The same applies for the [`<button>`](button) element.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [interactive content](../content_categories#interactive_content), [form-associated element](../content_categories#form-associated_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content), but no descendant `label` elements. No [labelable](../content_categories#labelable) elements other than the labeled control are allowed. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLLabelElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-label-element](https://html.spec.whatwg.org/multipage/forms.html#the-label-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `label` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `for` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
html <figure>: The Figure with Optional Caption element <figure>: The Figure with Optional Caption element
==================================================
The `<figure>` [HTML](../index) element represents self-contained content, potentially with an optional caption, which is specified using the [`<figcaption>`](figcaption) element. The figure, its caption, and its contents are referenced as a single unit.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Usually a `<figure>` is an image, illustration, diagram, code snippet, etc., that is referenced in the main flow of a document, but that can be moved to another part of the document or to an appendix without affecting the main flow.
* A caption can be associated with the `<figure>` element by inserting a [`<figcaption>`](figcaption) inside it (as the first or the last child). The first `<figcaption>` element found in the figure is presented as the figure's caption.
Examples
--------
### Images
```
<!-- Just an image -->
<figure>
<img src="favicon-192x192.png" alt="The beautiful MDN logo." />
</figure>
<!-- Image with a caption -->
<figure>
<img src="favicon-192x192.png" alt="The beautiful MDN logo." />
<figcaption>MDN Logo</figcaption>
</figure>
```
### Code snippets
```
<figure>
<figcaption>Get browser details using <code>navigator</code>.</figcaption>
<pre>
function NavigatorExample() {
var txt;
txt = "Browser CodeName: " + navigator.appCodeName + "; ";
txt+= "Browser Name: " + navigator.appName + "; ";
txt+= "Browser Version: " + navigator.appVersion + "; ";
txt+= "Cookies Enabled: " + navigator.cookieEnabled + "; ";
txt+= "Platform: " + navigator.platform + "; ";
txt+= "User-agent header: " + navigator.userAgent + "; ";
console.log("NavigatorExample", txt);
}
</pre>
</figure>
```
### Quotations
```
<figure>
<figcaption><b>Edsger Dijkstra:</b></figcaption>
<blockquote>
If debugging is the process of removing software bugs, then programming must
be the process of putting them in.
</blockquote>
</figure>
```
### Poems
```
<figure>
<p style="white-space:pre">
Bid me discourse, I will enchant thine ear,
Or like a fairy trip upon the green,
Or, like a nymph, with long dishevelled hair,
Dance on the sands, and yet no footing seen:
Love is a spirit all compact of fire,
Not gross to sink, but light, and will aspire.
</p>
<figcaption><cite>Venus and Adonis</cite>, by William Shakespeare</figcaption>
</figure>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [palpable content](../content_categories#palpable_content). |
| Permitted content | A [`<figcaption>`](figcaption) element, followed by [flow content](../content_categories#flow_content); or flow content followed by a [`<figcaption>`](figcaption) element; or flow content. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [Flow content](../content_categories#flow_content). |
| Implicit ARIA role | [figure](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/figure_role) |
| Permitted ARIA roles | With no <figcaption>descendant: [any](https://www.w3.org/TR/html-aria/#dfn-any-role), otherwise no permitted roles |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-figure-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-figure-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `figure` | 8 | 12 | 4 | 9 | 11 | 5.1 | Yes | Yes | 4 | 11 | 5 | Yes |
See also
--------
* The [`<figcaption>`](figcaption) element.
html <strong>: The Strong Importance element <strong>: The Strong Importance element
=======================================
The `<strong>` [HTML](../index) element indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
The `<strong>` element is for content that is of "strong importance," including things of great seriousness or urgency (such as warnings). This could be a sentence that is of great importance to the whole page, or you could merely try to point out that some words are of greater importance compared to nearby content.
Typically this element is rendered by default using a bold font weight. However, it should *not* be used to apply bold styling; use the CSS [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) property for that purpose. Use the [`<b>`](b) element to draw attention to certain text without indicating a higher level of importance. Use the [`<em>`](em) element to mark text that has stress emphasis.
Another accepted use for `<strong>` is to denote the labels of paragraphs which represent notes or warnings within the text of a page.
### <b> vs. <strong>
It is often confusing to new developers why there are so many ways to express the same thing on a rendered website. [`<b>`](b) and `<strong>` are perhaps one of the most common sources of confusion, causing developers to ask "Should I use `<b>` or `<strong>`? Don't they both do the same thing?"
Not exactly. The `<strong>` element is for content that is of greater importance, while the `<b>` element is used to draw attention to text without indicating that it's more important.
It may help to realize that both are valid and semantic elements in HTML and that it's a coincidence that they both have the same default styling (boldface) in most browsers (although some older browsers actually underline `<strong>`). Each element is meant to be used in certain types of scenarios, and if you want to bold text for decoration, you should instead actually use the CSS [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) property.
The intended meaning or purpose of the enclosed text should be what determines which element you use. Communicating meaning is what semantics are all about.
### <em> vs. <strong>
Adding to the confusion is the fact that while HTML 4 defined `<strong>` as indicating a stronger emphasis, HTML 5 defines `<strong>` as representing "strong importance for its contents." This is an important distinction to make.
While `<em>` is used to change the meaning of a sentence as spoken emphasis does ("I *love* carrots" vs. "I love *carrots*"), `<strong>` is used to give portions of a sentence added importance (e.g., "**Warning!** This is **very dangerous.**") Both `<strong>` and `<em>` can be nested to increase the relative degree of importance or stress emphasis, respectively.
Examples
--------
### Basic example
```
<p>
Before proceeding, <strong>make sure you put on your safety goggles</strong>.
</p>
```
The resulting output:
### Labeling warnings
```
<p>
<strong>Important:</strong> Before proceeding, make sure you add plenty of
butter.
</p>
```
This results in:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None; must have both a start tag and an end tag. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content), or any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-strong-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-strong-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `strong` | 1 | 12 | 1
Before Firefox 4, creating a `<strong>` element incorrectly resulted in an `HTMLSpanElement` object, instead of the expected `HTMLElement`. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The [`<b>`](b) element
* The [`<em>`](em) element
* The [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) property
| programming_docs |
html <dt>: The Description Term element <dt>: The Description Term element
==================================
The `<dt>` [HTML](../index) element specifies a term in a description or definition list, and as such must be used inside a [`<dl>`](dl) element. It is usually followed by a [`<dd>`](dd) element; however, multiple `<dt>` elements in a row indicate several terms that are all defined by the immediate next [`<dd>`](dd) element.
The subsequent [`<dd>`](dd) (**Description Details**) element provides the definition or other related text associated with the term specified using `<dt>`.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
For examples, see the [examples provided for the `<dl>` element](dl#examples).
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Flow content](../content_categories#flow_content), but with no [`<header>`](header), [`<footer>`](footer), sectioning content or heading content descendants. |
| Tag omission | The start tag is required. The end tag may be omitted if this element is immediately followed by another `<dt>` element or a [`<dd>`](dd) element, or if there is no more content in the parent element. |
| Permitted parents | A [`<dl>`](dl) or (in [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG) HTML, [W3C](https://developer.mozilla.org/en-US/docs/Glossary/W3C) HTML 5.2 and later) a [`<div>`](div) that is a child of a [`<dl>`](dl).This element can be used before a [`<dd>`](dd) or another [`<dt>`](dt) element. |
| Implicit ARIA role | `[term](https://w3c.github.io/aria/#term)` |
| Permitted ARIA roles | `[listitem](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listitem_role)` |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the [`HTMLSpanElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement) interface for this element. |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-dt-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-dt-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `dt` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<dl>`](dl)
* [`<dd>`](dd)
html <datalist>: The HTML Data List element <datalist>: The HTML Data List element
======================================
The `<datalist>` [HTML](../index) element contains a set of [`<option>`](option) elements that represent the permissible or recommended options available to choose from within other controls.
Try it
------
To bind the `<datalist>` element to the control, we give it a unique identifier in the [`id`](../global_attributes/id) attribute, and then add the [`list`](input#attr-list) attribute to the [`<input>`](input) element with the same identifier as value. Only certain types of [`<input>`](input) support this behavior, and it can also vary from browser to browser.
**Note:** The `<option>` element can store a value as internal content and in the `value` and `label` attributes. Which one will be visible in the drop-down menu depends on the browser, but when clicked, content entered into control field will always come from the `value` attribute.
Attributes
----------
This element has no other attributes than the [global attributes](../global_attributes), common to all elements.
Examples
--------
### Textual types
Recommended values in types [text](input/text), [search](input/search), [url](input/url), [tel](input/tel), [email](input/email) and [number](input/number), are displayed in a drop-down menu when user clicks or double-clicks on the control. Typically the right side of a control will also have an arrow pointing to the presence of predefined values.
```
<label for="myBrowser">Choose a browser from this list:</label>
<input list="browsers" id="myBrowser" name="myBrowser" />
<datalist id="browsers">
<option value="Chrome"></option>
<option value="Firefox"></option>
<option value="Internet Explorer"></option>
<option value="Opera"></option>
<option value="Safari"></option>
<option value="Microsoft Edge"></option>
</datalist>
```
### Date and Time types
The types [month](input/month), [week](input/week), [date](input/date), [time](input/time) and [datetime-local](input/datetime-local) can show an interface that allows a convenient selection of a date and time. Predefined values can be shown there, allowing the user to quickly fill the control value.
**Note:** When type is not supported, `text` type creating simple text field will be used instead. That field will correctly recognize recommended values and display them to the user in a drop-down menu.
```
<input type="time" list="popularHours" />
<datalist id="popularHours">
<option value="12:00"></option>
<option value="13:00"></option>
<option value="14:00"></option>
</datalist>
```
### Range type
The recommended values in the [range](input/range) type will be shown as series of hash marks that the user can easily select.
```
<label for="tick">Tip amount:</label>
<input type="range" list="tickmarks" min="0" max="100" id="tick" name="tick" />
<datalist id="tickmarks">
<option value="0"></option>
<option value="10"></option>
<option value="20"></option>
<option value="30"></option>
</datalist>
```
### Color type
The [color](input/color) type can show predefined colors in a browser-provided interface.
```
<label for="colors">Pick a color (preferably a red tone):</label>
<input type="color" list="redColors" id="colors" />
<datalist id="redColors">
<option value="#800000"></option>
<option value="#8B0000"></option>
<option value="#A52A2A"></option>
<option value="#DC143C"></option>
</datalist>
```
### Password type
The specification allows linking `<datalist>` with a [password](input/password) type, but no browser supports it for security reasons.
```
<label for="pwd">Enter a password:</label>
<input type="password" list="randomPassword" id="pwd" />
<datalist id="randomPassword">
<option value="5Mg[\_3DnkgSu@!q#"></option>
</datalist>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content). |
| Permitted content | Either [phrasing content](../content_categories#phrasing_content) or zero or more [`<option>`](option) elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [listbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLDataListElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDataListElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-datalist-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-datalist-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `datalist` | 20 | 12 | 4
The `<datalist>` element will only create a dropdown for textual types, such as `text`, `search`, `url`, `tel`, `email` and `number`. The `date`, `time`, `range` and `color` types are not supported. | 10 | 9.5 | 12.1 | 4.4.3 | 33 | 79
The dropdown menu containing available options does not appear. See [bug 1535985](https://bugzil.la/1535985).
4-79 | 20 | 12.2 | 2.0 |
See also
--------
* The [`<input>`](input) element, and more specifically its [`list`](input#attr-list) attribute;
* The [`<option>`](option) element.
html <track>: The Embed Text Track element <track>: The Embed Text Track element
=====================================
The `<track>` [HTML](../index) element is used as a child of the media elements, [`<audio>`](audio) and [`<video>`](video). It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in [WebVTT format](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API) (`.vtt` files) — Web Video Text Tracks.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | None |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | As it is a void element, the start tag must be present and the end tag must not be present. |
| Permitted parents | A media element, [`<audio>`](audio) or [`<video>`](video). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLTrackElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTrackElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`default`**](#attr-default) This attribute indicates that the track should be enabled unless the user's preferences indicate that another track is more appropriate. This may only be used on one `track` element per media element.
[**`kind`**](#attr-kind) How the text track is meant to be used. If omitted the default kind is `subtitles`. If the attribute contains an invalid value, it will use `metadata` (Versions of Chrome earlier than 52 treated an invalid value as `subtitles`). The following keywords are allowed:
* `subtitles`
+ Subtitles provide translation of content that cannot be understood by the viewer. For example speech or text that is not English in an English language film.
+ Subtitles may contain additional content, usually extra background information. For example the text at the beginning of the Star Wars films, or the date, time, and location of a scene.
* `captions`
+ Closed captions provide a transcription and possibly a translation of audio.
+ It may include important non-verbal information such as music cues or sound effects. It may indicate the cue's source (e.g. music, text, character).
+ Suitable for users who are deaf or when the sound is muted.
* `descriptions`
+ Textual description of the video content.
+ Suitable for users who are blind or where the video cannot be seen.
* `chapters`
+ Chapter titles are intended to be used when the user is navigating the media resource.
* `metadata`
+ Tracks used by scripts. Not visible to the user.
[**`label`**](#attr-label) A user-readable title of the text track which is used by the browser when listing available text tracks.
[**`src`**](#attr-src) Address of the track (`.vtt` file). Must be a valid URL. This attribute must be specified and its URL value must have the same origin as the document — unless the [`<audio>`](audio) or [`<video>`](video) parent element of the `track` element has a [`crossorigin`](../attributes/crossorigin) attribute.
[**`srclang`**](#attr-srclang) Language of the track text data. It must be a valid [BCP 47](https://r12a.github.io/app-subtags/) language tag. If the `kind` attribute is set to `subtitles`, then `srclang` must be defined.
Usage notes
-----------
### Track data types
The type of data that `track` adds to the media is set in the `kind` attribute, which can take values of `subtitles`, `captions`, `descriptions`, `chapters` or `metadata`. The element points to a source file containing timed text that the browser exposes when the user requests additional data.
A media element cannot have more than one `track` with the same `kind`, `srclang`, and `label`.
### Detecting cue changes
The underlying [`TextTrack`](https://developer.mozilla.org/en-US/docs/Web/API/TextTrack), indicated by the `track` property, receives a `cuechange` event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element.
If the track *is* associated with a media element, using the [`<track>`](track) element as a child of the [`<audio>`](audio) or [`<video>`](video) element, the `cuechange` event is also sent to the [`HTMLTrackElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTrackElement).
```
let textTrackElem = document.getElementById("texttrack");
textTrackElem.addEventListener("cuechange", (event) => {
let cues = event.target.track.activeCues;
});
```
Examples
--------
```
<video controls poster="/images/sample.gif">
<source src="sample.mp4" type="video/mp4" />
<source src="sample.ogv" type="video/ogv" />
<track kind="captions" src="sampleCaptions.vtt" srclang="en" />
<track kind="descriptions" src="sampleDescriptions.vtt" srclang="en" />
<track kind="chapters" src="sampleChapters.vtt" srclang="en" />
<track kind="subtitles" src="sampleSubtitles\_de.vtt" srclang="de" />
<track kind="subtitles" src="sampleSubtitles\_en.vtt" srclang="en" />
<track kind="subtitles" src="sampleSubtitles\_ja.vtt" srclang="ja" />
<track kind="subtitles" src="sampleSubtitles\_oz.vtt" srclang="oz" />
<track kind="metadata" src="keyStage1.vtt" srclang="en" label="Key Stage 1" />
<track kind="metadata" src="keyStage2.vtt" srclang="en" label="Key Stage 2" />
<track kind="metadata" src="keyStage3.vtt" srclang="en" label="Key Stage 3" />
<!-- Fallback -->
…
</video>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-track-element](https://html.spec.whatwg.org/multipage/media.html#the-track-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `track` | 23 | 12 | 31 | 10 | 12.1 | 6 | Yes
Doesn't work for fullscreen video. | 25
Doesn't work for fullscreen video. | 31 | No | 6 | 1.5
Doesn't work for fullscreen video. |
| `default` | 23 | 12 | 31 | 10 | 12.1 | 6 | 4.4 | 25 | 31 | No | No | 1.5 |
| `kind` | 23 | 12 | 31 | 10 | 12.1 | 6 | 4.4 | 25 | 31 | No | No | 1.5 |
| `label` | 23 | 12 | 31 | 10 | 12.1 | 6 | 4.4 | 25 | 31 | No | No | 1.5 |
| `src` | 23 | 12 | 31 | 10 | 12.1 | 6 | 4.4 | 25 | 31 | No | No | 1.5 |
| `srclang` | 23 | 12 | 31 | 10 | 12.1 | 6 | 4.4 | 25 | 31 | No | No | 1.5 |
See also
--------
* [WebVTT text track format](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API)
* [`HTMLMediaElement.textTracks`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/textTracks)
html <kbd>: The Keyboard Input element <kbd>: The Keyboard Input element
=================================
The `<kbd>` [HTML](../index) element represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) defaults to rendering the contents of a `<kbd>` element using its default monospace font, although this is not mandated by the HTML standard.
Try it
------
`<kbd>` may be nested in various combinations with the [`<samp>`](samp) (Sample Output) element to represent various forms of input or output based on visual cues.
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
Other elements can be used in tandem with `<kbd>` to represent more specific scenarios:
* Nesting a `<kbd>` element within another `<kbd>` element represents an actual key or other unit of input as a portion of a larger input. See [Representing keystrokes within an input](#representing_keystrokes_within_an_input) below.
* Nesting a `<kbd>` element inside a [`<samp>`](samp) element represents input that has been echoed back to the user by the system. See [Echoed input](#echoed_input), below, for an example.
* Nesting a `<samp>` element inside a `<kbd>` element, on the other hand, represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen. See the example under [Representing onscreen input options](#representing_onscreen_input_options) below.
**Note:** You can define a custom style to override the browser's default font selection for the `<kbd>` element, although the user's preferences may potentially override your CSS.
Examples
--------
### Basic example
```
<p>
Use the command <kbd>help mycommand</kbd> to view documentation for the
command "mycommand".
</p>
```
### Representing keystrokes within an input
To describe an input comprised of multiple keystrokes, you can nest multiple `<kbd>` elements, with an outer `<kbd>` element representing the overall input and each individual keystroke or component of the input enclosed within its own `<kbd>`.
#### Unstyled
First, let's look at what this looks like as just plain HTML.
##### HTML
```
<p>
You can also create a new document using the keyboard shortcut
<kbd><kbd>Ctrl</kbd>+<kbd>N</kbd></kbd>.
</p>
```
This wraps the entire key sequence in an outer `<kbd>` element, then each individual key within its own, in order to denote the components of the sequence.
**Note:** You don't need to do all this wrapping; you can choose to simplify it by leaving out the external `<kbd>` element. In other words, simplifying this to just `<kbd>Ctrl</kbd>+<kbd>N</kbd>` would be perfectly valid.
**Note:** Depending on your style sheet, though, you may find it useful to do this kind of nesting.
##### Result
The output looks like this without a style sheet applied:
#### With custom styles
We can make more sense of this by adding some CSS:
##### CSS
We add a new selector for nested `<kbd>` elements, `kbd>kbd`, which we can apply when rendering keyboard keys:
```
kbd>kbd {
border-radius: 3px;
padding: 1px 2px 0;
border: 1px solid black;
}
```
##### HTML
Then we update the HTML to use this class on the keys in the output to be presented:
```
<p>
You can also create a new document by pressing
<kbd><kbd>Ctrl</kbd>+<kbd>N</kbd></kbd>.
</p>
```
##### Result
The result is just what we want!
### Echoed input
Nesting a `<kbd>` element inside a [`<samp>`](samp) element represents input that has been echoed back to the user by the system.
```
<p>
If a syntax error occurs, the tool will output the initial command you typed
for your review:
</p>
<blockquote>
<samp><kbd>custom-git ad my-new-file.cpp</kbd></samp>
</blockquote>
```
### Representing onscreen input options
Nesting a `<samp>` element inside a `<kbd>` element represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen.
For example, you can explain how to choose the "New Document" option in the "File" menu using HTML that looks like this:
```
<p>
To create a new file, choose the menu option
<kbd
><kbd><samp>File</samp></kbd>⇒<kbd><samp>New Document</samp></kbd></kbd>.
</p>
<p>
Don't forget to click the <kbd><samp>OK</samp></kbd> button to confirm once
you've entered the name of the new file.
</p>
```
This does some interesting nesting. For the menu option description, the entire input is enclosed in a `<kbd>` element. Then, inside that, both the menu and menu item names are contained within both `<kbd>` and `<samp>`, indicating an input which is selected from a screen widget.
#### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-kbd-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-kbd-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `kbd` | Yes | 12 | 1
Before Firefox 4, creating a <kbd> element incorrectly resulted in an `HTMLSpanElement` object, instead of the expected `HTMLElement`. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<code>`](code)
| programming_docs |
html <audio>: The Embed Audio element <audio>: The Embed Audio element
================================
The `<audio>` [HTML](../index) element is used to embed sound content in documents. It may contain one or more audio sources, represented using the `src` attribute or the [`<source>`](source) element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a [`MediaStream`](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream).
Try it
------
The above example shows simple usage of the `<audio>` element. In a similar manner to the [`<img>`](img) element, we include a path to the media we want to embed inside the `src` attribute; we can include other attributes to specify information such as whether we want it to autoplay and loop, whether we want to show the browser's default audio controls, etc.
The content inside the opening and closing `<audio></audio>` tags is shown as a fallback in browsers that don't support the element.
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`autoplay`**](#attr-autoplay) A Boolean attribute: if specified, the audio will automatically begin playback as soon as it can do so, without waiting for the entire audio file to finish downloading.
**Note:** Sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. If you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). However, this can be useful when creating media elements whose source will be set at a later time, under user control. See our [autoplay guide](https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide) for additional information about how to properly use autoplay.
[**`controls`**](#attr-controls) If this attribute is present, the browser will offer controls to allow the user to control audio playback, including volume, seeking, and pause/resume playback.
[**`controlslist`**](#attr-controlslist) Experimental Non-standard
The [`controlslist`](https://wicg.github.io/controls-list/explainer.html) attribute, when specified, helps the browser select what controls to show for the `audio` element whenever the browser shows its own set of controls (that is, when the `controls` attribute is specified).
The allowed values are `nodownload`, `nofullscreen` and `noremoteplayback`.
[**`crossorigin`**](#attr-crossorigin) This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute indicates whether to use CORS to fetch the related audio file. [CORS-enabled resources](../cors_enabled_image) can be reused in the [`<canvas>`](canvas) element without being *tainted*. The allowed values are:
`anonymous` Sends a cross-origin request without a credential. In other words, it sends the `Origin:` HTTP header without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (by not setting the `Access-Control-Allow-Origin:` HTTP header), the resource will be *tainted*, and its usage restricted.
`use-credentials` Sends a cross-origin request with a credential. In other words, it sends the `Origin:` HTTP header with a cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (through `Access-Control-Allow-Credentials:` HTTP header), the resource will be *tainted* and its usage restricted.
When not present, the resource is fetched without a CORS request (i.e. without sending the `Origin:` HTTP header), preventing its non-tainted use in [`<canvas>`](canvas) elements. If invalid, it is handled as if the enumerated keyword **anonymous** was used. See [CORS settings attributes](../attributes/crossorigin) for additional information.
[**`disableremoteplayback`**](#attr-disableremoteplayback) Experimental
A Boolean attribute used to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc.). See [this proposed specification](https://www.w3.org/TR/remote-playback/#the-disableremoteplayback-attribute) for more information.
**Note:** In Safari, you can use [`x-webkit-airplay="deny"`](https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/AirPlayGuide/OptingInorOutofAirPlay/OptingInorOutofAirPlay.html) as a fallback.
[**`loop`**](#attr-loop) A Boolean attribute: if specified, the audio player will automatically seek back to the start upon reaching the end of the audio.
[**`muted`**](#attr-muted) A Boolean attribute that indicates whether the audio will be initially silenced. Its default value is `false`.
[**`preload`**](#attr-preload) This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience. It may have one of the following values:
* `none`: Indicates that the audio should not be preloaded.
* `metadata`: Indicates that only audio metadata (e.g. length) is fetched.
* `auto`: Indicates that the whole audio file can be downloaded, even if the user is not expected to use it.
* *empty string*: A synonym of the `auto` value.
The default value is different for each browser. The spec advises it to be set to `metadata`.
**Note:**
* The `autoplay` attribute has precedence over `preload`. If `autoplay` is specified, the browser would obviously need to start downloading the audio for playback.
* The browser is not forced by the specification to follow the value of this attribute; it is a mere hint.
[**`src`**](#attr-src) The URL of the audio to embed. This is subject to [HTTP access controls](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). This is optional; you may instead use the [`<source>`](source) element within the audio block to specify the audio to embed.
Events
------
| Event name | Fired when |
| --- | --- |
| [`audioprocess`](https://developer.mozilla.org/en-US/docs/Web/API/ScriptProcessorNode/audioprocess_event) | The input buffer of a [`ScriptProcessorNode`](https://developer.mozilla.org/en-US/docs/Web/API/ScriptProcessorNode) is ready to be processed. |
| [`canplay`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplay_event) | The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. |
| [`canplaythrough`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event) | The browser estimates it can play the media up to its end without stopping for content buffering. |
| [`complete`](https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext/complete_event) | The rendering of an [`OfflineAudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext) is terminated. |
| [`durationchange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/durationchange_event) | The `duration` attribute has been updated. |
| [`emptied`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/emptied_event) | The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the [`HTMLMediaElement.load`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/load) method is called to reload it. |
| [`ended`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended_event) | Playback has stopped because the end of the media was reached. |
| [`loadeddata`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadeddata_event) | The first frame of the media has finished loading. |
| [`loadedmetadata`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadedmetadata_event) | The metadata has been loaded. |
| [`pause`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause_event) | Playback has been paused. |
| [`play`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play_event) | Playback has begun. |
| [`playing`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playing_event) | Playback is ready to start after having been paused or delayed due to lack of data. |
| [`ratechange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ratechange_event) | The playback rate has changed. |
| [`seeked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeked_event) | A *seek* operation completed. |
| [`seeking`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeking_event) | A *seek* operation began. |
| [`stalled`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/stalled_event) | The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. |
| [`suspend`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/suspend_event) | Media data loading has been suspended. |
| [`timeupdate`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event) | The time indicated by the `currentTime` attribute has been updated. |
| [`volumechange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/volumechange_event) | The volume has changed. |
| [`waiting`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/waiting_event) | Playback has stopped because of a temporary lack of data |
Usage notes
-----------
Browsers don't all support the same [file types](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers) and [audio codecs](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs); you can provide multiple sources inside nested [`<source>`](source) elements, and the browser will then use the first one it understands:
```
<audio controls>
<source src="myAudio.mp3" type="audio/mpeg" />
<source src="myAudio.ogg" type="audio/ogg" />
<p>
Download <a href="myAudio.mp3">MP3</a> or
<a href="myAudio.ogg">OGG</a> audio.
</p>
</audio>
```
We offer a substantive and thorough [guide to media file types](https://developer.mozilla.org/en-US/docs/Web/Media/Formats) and the [audio codecs that can be used within them](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs). Also available is [a guide to the codecs supported for video](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs).
Other usage notes:
* If you don't specify the `controls` attribute, the audio player won't include the browser's default controls. You can, however, create your own custom controls using JavaScript and the [`HTMLMediaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) API.
* To allow precise control over your audio content, `HTMLMediaElement`s fire many different [events](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#events). This also provides a way to monitor the audio's fetching process so you can watch for errors or detect when enough is available to begin to play or manipulate it.
* You can also use the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API) to directly generate and manipulate audio streams from JavaScript code rather than streaming pre-existing audio files.
* `<audio>` elements can't have subtitles or captions associated with them in the same way that `<video>` elements can. See [WebVTT and Audio](https://www.iandevlin.com/blog/2015/12/html5/webvtt-and-audio/) by Ian Devlin for some useful information and workarounds.
A good general source of information on using HTML `<audio>` is the [Video and audio content](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) beginner's tutorial.
### Styling with CSS
The `<audio>` element has no intrinsic visual output of its own unless the `controls` attribute is specified, in which case the browser's default controls are shown.
The default controls have a [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) value of `inline` by default, and it is often a good idea to set the value to `block` to improve control over positioning and layout, unless you want it to sit within a text block or similar.
You can style the default controls with properties that affect the block as a single unit, so for example you can give it a [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) and [`border-radius`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius), [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding), [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin), etc. You can't however style the individual components inside the audio player (e.g. change the button size or icons, change the font, etc.), and the controls are different across the different browsers.
To get a consistent look and feel across browsers, you'll need to create custom controls; these can be marked up and styled in whatever way you want, and then JavaScript can be used along with the [`HTMLMediaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) API to wire up their functionality.
[Video player styling basics](https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/Video_player_styling_basics) provides some useful styling techniques — it is written in the context of `<video>`, but much of it is equally applicable to `<audio>`.
### Detecting addition and removal of tracks
You can detect when tracks are added to and removed from an `<audio>` element using the [`addtrack`](https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList/addtrack_event) and [`removetrack`](https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList/removetrack_event) events. However, these events aren't sent directly to the `<audio>` element itself. Instead, they're sent to the track list object within the `<audio>` element's [`HTMLMediaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) that corresponds to the type of track that was added to the element:
[`HTMLMediaElement.audioTracks`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/audioTracks) An [`AudioTrackList`](https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList) containing all of the media element's audio tracks. You can add a listener for `addtrack` to this object to be alerted when new audio tracks are added to the element.
[`HTMLMediaElement.videoTracks`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/videoTracks) Add an `addtrack` listener to this [`VideoTrackList`](https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList) object to be informed when video tracks are added to the element.
[`HTMLMediaElement.textTracks`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/textTracks) Add an `addtrack` event listener to this [`TextTrackList`](https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList) to be notified when new text tracks are added to the element.
**Note:** Even though it's an `<audio>` element, it still has video and text track lists, and can in fact be used to present video, although the user interface implications can be odd.
For example, to detect when audio tracks are added to or removed from an `<audio>` element, you can use code like this:
```
const elem = document.querySelector("audio");
elem.audioTrackList.onaddtrack = (event) => {
trackEditor.addTrack(event.track);
};
elem.audioTrackList.onremovetrack = (event) => {
trackEditor.removeTrack(event.track);
};
```
This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks.
You can also use [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) to listen for the [`addtrack`](https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList/addtrack_event) and [`removetrack`](https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList/removetrack_event) events.
Examples
--------
### Basic usage
The following example shows simple usage of the `<audio>` element to play an OGG file. It will autoplay due to the `autoplay` attribute—if the page has permission to do so—and also includes fallback content.
```
<!-- Simple audio playback -->
<audio src="AudioTest.ogg" autoplay>
<a href="AudioTest.ogg">Download OGG audio</a>.
</audio>
```
For details on when autoplay works, how to get permission to use autoplay, and how and when it's appropriate to use autoplay, see our [autoplay guide](https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide).
### <audio> element with <source> element
This example specifies which audio track to embed using the `src` attribute on a nested `<source>` element rather than directly on the `<audio>` element. It is always useful to include the file's MIME type inside the `type` attribute, as the browser is able to instantly tell if it can play that file, and not waste time on it if not.
```
<audio controls>
<source src="foo.wav" type="audio/wav" />
<a href="foo.wav">Download WAV audio</a>.
</audio>
```
### <audio> with multiple <source> elements
This example includes multiple `<source>` elements. The browser tries to load the first source element (Opus) if it is able to play it; if not it falls back to the second (Vorbis) and finally back to MP3:
```
<audio controls>
<source src="foo.opus" type="audio/ogg; codecs=opus" />
<source src="foo.ogg" type="audio/ogg; codecs=vorbis" />
<source src="foo.mp3" type="audio/mpeg" />
</audio>
```
Accessibility concerns
----------------------
Audio with spoken dialog should provide both captions and transcripts that accurately describe its content. Captions, which are specified using [WebVTT](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API), allow people who are experiencing hearing loss to understand an audio recording's content as the recording is being played, while transcripts allow people who need additional time to be able to review the recording's content at a pace and format that is comfortable for them.
If automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source audio.
The `<audio>` element doesn't directly support WebVTT. You will have to find a library or framework that provides the capability for you, or write the code to display captions yourself. One option is to play your audio using a [`<video>`](video) element, which does support WebVTT.
In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone. For example, in the WebVTT below, note the use of square brackets to provide tone and emotional insight to the viewer; this can help establish the mood otherwise provided using music, nonverbal sounds and crucial sound effects, and so forth.
```
1
00:00:00 --> 00:00:45
[Energetic techno music]
2
00:00:46 --> 00:00:51
Welcome to the Time Keeper's podcast! In this episode we're discussing which Swisswatch is a wrist switchwatch?
16
00:00:52 --> 00:01:02
[Laughing] Sorry! I mean, which wristwatch is a Swiss wristwatch?
```
Also it's a good practice to provide some content (such as the direct download link) as a fallback for viewers who use a browser in which the `<audio>` element is not supported:
```
<audio controls>
<source src="myAudio.mp3" type="audio/mpeg" />
<source src="myAudio.ogg" type="audio/ogg" />
<p>
Download <a href="myAudio.mp3">MP3</a> or
<a href="myAudio.ogg">OGG</a> audio.
</p>
</audio>
```
* [Web Video Text Tracks Format (WebVTT)](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API)
* [WebAIM: Captions, Transcripts, and Audio Descriptions](https://webaim.org/techniques/captions/)
* [MDN Understanding WCAG, Guideline 1.2 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.2_%E2%80%94_providing_text_alternatives_for_time-based_media)
* [Understanding Success Criterion 1.2.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-av-only-alt.html)
* [Understanding Success Criterion 1.2.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-captions.html)
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), phrasing content, embedded content. If it has a [`controls`](audio#attr-controls) attribute: interactive content and palpable content. |
| Permitted content | If the element has a [`src`](audio#attr-src) attribute: zero or more [`<track>`](track) elements followed by transparent content that contains no [`<audio>`](audio) or [`<video>`](video) media elements.Else: zero or more [`<source>`](source) elements followed by zero or more [`<track>`](track) elements followed by transparent content that contains no [`<audio>`](audio) or [`<video>`](video) media elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts embedded content. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[application](https://w3c.github.io/aria/#application)` |
| DOM interface | [`HTMLAudioElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-audio-element](https://html.spec.whatwg.org/multipage/media.html#the-audio-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `audio` | 3 | 12 | 3.5
For Firefox to play audio, the server must serve the file using the correct MIME type. | 9 | 10.5 | 3.1 | 3 | 18 | 4
For Firefox to play audio, the server must serve the file using the correct MIME type. | Yes | 3 | 1.0 |
| `autoplay` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | 3 | 18 | 4 | Yes | 3 | 1.0 |
| `controls` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | 3 | 18 | 4 | Yes | 3 | 1.0 |
| `loop` | 3 | 12 | 11 | 9 | 10.5 | 3.1 | 3 | 18 | 14 | Yes | 3 | 1.0 |
| `muted` | No | ≤18 | 11 | No | No | No | No | No | 14 | No | No | No |
| `preload` | 3
Defaults to `metadata` in Chrome 64. | 12 | 4
3.5-4 | 9 | 15
Defaults to `metadata` in Opera 51.
10.5-15 | 3.1 | 3
Defaults to `metadata` in Chrome 64. | 18
Defaults to `metadata` in Chrome 64. | 4 | 14
Defaults to `metadata` in Opera 51.
Yes-14 | 3 | 1.0
Defaults to `metadata` in Samsung Internet 9.0. |
| `src` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | 3 | 18 | 4 | Yes | 3 | 1.0 |
See also
--------
* [Web media technologies](https://developer.mozilla.org/en-US/docs/Web/Media)
+ [Media container formats (file types)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers)
+ [Guide to audio codecs used on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs)
* [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API)
* [`HTMLAudioElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement)
* [`<source>`](source)
* [`<video>`](video)
* [Learning area: Video and audio content](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content)
* [Cross-browser audio basics](https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/Cross-browser_audio_basics)
| programming_docs |
html <html>: The HTML Document / Root element <html>: The HTML Document / Root element
========================================
The `<html>` [HTML](../index) element represents the root (top-level element) of an HTML document, so it is also referred to as the *root element*. All other elements must be descendants of this element.
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | One [`<head>`](head) element, followed by one [`<body>`](body) element. |
| Tag omission | The start tag may be omitted if the first thing inside the `<html>` element is not a comment.The end tag may be omitted if the `<html>` element is not immediately followed by a comment. |
| Permitted parents | None. This is the root element of a document. |
| Implicit ARIA role | [document](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/document_role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLHtmlElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHtmlElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`manifest`**](#attr-manifest) Deprecated Non-standard
Specifies the [URI](https://developer.mozilla.org/en-US/docs/Glossary/URI) of a resource manifest indicating resources that should be cached locally.
[**`version`**](#attr-version) Deprecated
Specifies the version of the HTML [Document Type Definition](https://developer.mozilla.org/en-US/docs/Glossary/Doctype) that governs the current document. This attribute is not needed, because it is redundant with the version information in the document type declaration.
[**`xmlns`**](#attr-xmlns) Specifies the [XML](https://developer.mozilla.org/en-US/docs/Glossary/XML) [Namespace](https://developer.mozilla.org/en-US/docs/Glossary/Namespace) of the document. Default value is `"http://www.w3.org/1999/xhtml"`. This is required in documents parsed with XML [parsers](https://developer.mozilla.org/en-US/docs/Glossary/Parser), and optional in text/html documents.
Example
-------
```
<!DOCTYPE html>
<html lang="en">
<head>
<!-- … -->
</head>
<body>
<!-- … -->
</body>
</html>
```
Accessibility concerns
----------------------
While HTML does not require authors to specify `<html>` element start and ending tags, it is important for authors to do so as it will allow them to specify the [`lang`](../global_attributes#lang) for the webpage. Providing a `lang` attribute with a valid language tag according to [RFC 5646: Tags for Identifying Languages (also known as BCP 47)](https://datatracker.ietf.org/doc/html/rfc5646) on the `<html>` element will help screen reading technology determine the proper language to announce. The identifying language tag should describe the language used by the majority of the content of the page. Without it, screen readers will typically default to the operating system's set language, which may cause mispronunciations.
Including a valid `lang` declaration on the `<html>` element also ensures that important metadata contained in the page's [`<head>`](head), such as the page's [`<title>`](title), are also announced properly.
* [MDN Understanding WCAG, Guideline 3.1 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.1_%e2%80%94_readable_make_text_content_readable_and_understandable)
* [Understanding Success Criterion 3.1.1 | W3C Understanding WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/language-of-page.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-html-element](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `html` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `manifest` | 4 | 12 | 3.5-84
3
Before version 3.5, Firefox ignores the `NETWORK` and `FALLBACK` sections of the cache manifest file. | 10 | 10.6 | 4 | 4 | 18 | 4-84 | 11 | 3.2 | 1.0 |
| `version` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `xmlns` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* MathML top-level element: `[<math>](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math)`
* SVG top-level element: [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg)
html <base>: The Document Base URL element <base>: The Document Base URL element
=====================================
The `<base>` [HTML](../index) element specifies the base URL to use for all *relative* URLs in a document. There can be only one `<base>` element in a document.
A document's used base URL can be accessed by scripts with [`Node.baseURI`](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI). If the document has no `<base>` elements, then `baseURI` defaults to [`location.href`](https://developer.mozilla.org/en-US/docs/Web/API/Location/href).
| | |
| --- | --- |
| [Content categories](../content_categories) | Metadata content. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | There must be no closing tag. |
| Permitted parents | A [`<head>`](head) that doesn't contain another [`<base>`](base) element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLBaseElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseElement) |
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
**Warning:** If either of the following attributes are specified, this element **must** come before other elements with attribute values of URLs, such as [`<link>`](link)'s `href` attribute.
[**`href`**](#attr-href) The base URL to be used throughout the document for relative URLs. Absolute and relative URLs are allowed.
[**`target`**](#attr-target) A **keyword** or **author-defined name** of the default [browsing context](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context) to show the results of navigation from [`<a>`](a), [`<area>`](area), or [`<form>`](form) elements without explicit `target` attributes. The following keywords have special meanings:
* `_self` (default): Show the result in the current browsing context.
* `_blank`: Show the result in a new, unnamed browsing context.
* `_parent`: Show the result in the parent browsing context of the current one, if the current page is inside a frame. If there is no parent, acts the same as `_self`.
* `_top`: Show the result in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). If there is no parent, acts the same as `_self`.
Usage notes
-----------
### Multiple <base> elements
If multiple `<base>` elements are used, only the first `href` and first `target` are obeyed — all others are ignored.
### In-page anchors
Links pointing to a fragment in the document — e.g. `<a href="#some-id">` — are resolved with the `<base>`, triggering an HTTP request to the base URL with the fragment attached.
For example, given `<base href="https://example.com">` and this link: `<a href="#anchor">To anchor</a>`. The link points to `https://example.com/#anchor`.
### Open Graph
[Open Graph](https://ogp.me/) tags do not acknowledge `<base>`, and should always have full absolute URLs. For example:
```
<meta property="og:image" content="https://example.com/thumbnail.jpg" />
```
Examples
--------
```
<base href="https://www.example.com/" />
<base target="\_blank" />
<base target="\_top" href="https://example.com/" />
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-base-element](https://html.spec.whatwg.org/multipage/semantics.html#the-base-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `base` | Yes | 12 | 1 | Yes
Before Internet Explorer 7, `<base>` can be positioned anywhere in the document and the nearest value of `<base>` is used. | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `href` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `target` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
html <ins> <ins>
=====
The `<ins>` [HTML](../index) element represents a range of text that has been added to a document. You can use the [`<del>`](del) element to similarly represent a range of text that has been deleted from the document.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Phrasing content](../content_categories#phrasing_content), [flow content](../content_categories#flow_content). |
| Permitted content | [Transparent](../content_categories#transparent_content_model). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLModElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLModElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`cite`**](#attr-cite) This attribute defines the URI of a resource that explains the change, such as a link to meeting minutes or a ticket in a troubleshooting system.
[**`datetime`**](#attr-datetime) This attribute indicates the time and date of the change and must be a valid date with an optional time string. If the value cannot be parsed as a date with an optional time string, the element does not have an associated timestamp. For the format of the string without a time, see [Format of a valid date string](../date_and_time_formats#date_strings). The format of the string if it includes both date and time is covered in [Format of a valid local date and time string](../date_and_time_formats#local_date_and_time_strings).
Examples
--------
```
<ins>This text has been inserted</ins>
```
### Result
Accessibility concerns
----------------------
The presence of the `<ins>` element is not announced by most screen reading technology in its default configuration. It can be made to be announced by using the CSS [`content`](https://developer.mozilla.org/en-US/docs/Web/CSS/content) property, along with the [`::before`](https://developer.mozilla.org/en-US/docs/Web/CSS/::before) and [`::after`](https://developer.mozilla.org/en-US/docs/Web/CSS/::after) pseudo-elements.
```
ins::before,
ins::after {
clip-path: inset(100%);
clip: rect(1px, 1px, 1px, 1px);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
ins::before {
content: " [insertion start] ";
}
ins::after {
content: " [insertion end] ";
}
```
Some people who use screen readers deliberately disable announcing content that creates extra verbosity. Because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has been inserted would adversely affect understanding.
* [Short note on making your mark (more accessible) | The Paciello Group](https://www.tpgi.com/short-note-on-making-your-mark-more-accessible/)
* [Tweaking Text Level Styles | Adrian Roselli](https://adrianroselli.com/2017/12/tweaking-text-level-styles.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-ins-element](https://html.spec.whatwg.org/multipage/edits.html#the-ins-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ins` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `cite` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `datetime` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<del>`](del) element for marking deletion into a document
html <picture>: The Picture element <picture>: The Picture element
==============================
The `<picture>` [HTML](../index) element contains zero or more [`<source>`](source) elements and one [`<img>`](img) element to offer alternative versions of an image for different display/device scenarios.
The browser will consider each child `<source>` element and choose the best match among them. If no matches are found—or the browser doesn't support the `<picture>` element—the URL of the `<img>` element's [`src`](img#attr-src) attribute is selected. The selected image is then presented in the space occupied by the `<img>` element.
Try it
------
To decide which URL to load, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) examines each `<source>`'s [`srcset`](source#attr-srcset), [`media`](source#attr-media), and [`type`](source#attr-type) attributes to select a compatible image that best matches the current layout and capabilities of the display device.
The `<img>` element serves two purposes:
1. It describes the size and other attributes of the image and its presentation.
2. It provides a fallback in case none of the offered `<source>` elements are able to provide a usable image.
Common use cases for `<picture>`:
* **Art direction.** Cropping or modifying images for different `media` conditions (for example, loading a simpler version of an image which has too many details, on smaller displays).
* **Offering alternative image formats**, for cases where certain formats are not supported. **Note:** For example, newer formats like [AVIF](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#avif_image) or [WEBP](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#webp_image) have many advantages, but might not be supported by the browser. A list of supported image formats can be found in: [Image file type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types).
* **Saving bandwidth and speeding page load times** by loading the most appropriate image for the viewer's display.
If providing higher-density versions of an image for high-DPI (Retina) display, use [`srcset`](img#attr-srcset) on the `<img>` element instead. This lets browsers opt for lower-density versions in data-saving modes, and you don't have to write explicit `media` conditions.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), phrasing content, embedded content |
| Permitted content | Zero or more [`<source>`](source) elements, followed by one [`<img>`](img) element, optionally intermixed with script-supporting elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that allows embedded content. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLPictureElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLPictureElement) |
Attributes
----------
This element includes only [global attributes](../global_attributes).
Usage notes
-----------
You can use the [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) property to adjust the positioning of the image within the element's frame, and the [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) property to control how the image is resized to fit within the frame.
**Note:** Use these properties on the child `<img>` element, **not** the `<picture>` element.
Examples
--------
These examples demonstrate how different attributes of the [`<source>`](source) element change the selection of the image inside `<picture>`.
### The media attribute
The `media` attribute specifies a media condition (similar to a media query) that the user agent will evaluate for each [`<source>`](source) element.
If the [`<source>`](source)'s media condition evaluates to `false`, the browser skips it and evaluates the next element inside `<picture>`.
```
<picture>
<source srcset="mdn-logo-wide.png" media="(min-width: 600px)" />
<img src="mdn-logo-narrow.png" alt="MDN" />
</picture>
```
### The srcset attribute
The [**`srcset`**](#attr-srcset) attribute is used to offer list of possible images *based on size*.
It is composed of a comma-separated list of image descriptors. Each image descriptor is composed of a URL of the image, and *either*:
* a *width descriptor*, followed by a `w` (such as `300w`); *OR*
* a *pixel density descriptor*, followed by an `x` (such as `2x`) to serve a high-res image for high-DPI screens.
```
<picture>
<source srcset="logo-768.png, logo-768-1.5x.png 1.5x" />
<img src="logo-320.png" alt="logo" />
</picture>
```
### The type attribute
The `type` attribute specifies a [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) for the resource URL(s) in the [`<source>`](source) element's `srcset` attribute. If the user agent does not support the given type, the [`<source>`](source) element is skipped.
```
<picture>
<source srcset="photo.avif" type="image/avif" />
<source srcset="photo.webp" type="image/webp" />
<img src="photo.jpg" alt="photo" />
</picture>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-picture-element](https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `picture` | 38 | 13 | 38 | No | 25 | 9.1 | 38 | 38 | 38 | 25 | 9.3 | 3.0 |
See also
--------
* [`<img>`](img) element
* [`<source>`](source) element
* Positioning and sizing the picture within its frame: [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) and [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
* [Image file type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types)
html <img>: The Image Embed element <img>: The Image Embed element
==============================
The `<img>` [HTML](../index) element embeds an image into the document.
Try it
------
The above example shows usage of the `<img>` element:
* The `src` attribute is **required**, and contains the path to the image you want to embed.
* The `alt` attribute holds a text description of the image, which isn't mandatory but is **incredibly useful** for accessibility — screen readers read this description out to their users so they know what the image means. Alt text is also displayed on the page if the image can't be loaded for some reason: for example, network errors, content blocking, or linkrot.
There are many other attributes to achieve various purposes:
* [Referrer](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy)/[CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) control for security and privacy: see [`crossorigin`](img#attr-crossorigin) and [`referrerpolicy`](img#attr-referrerpolicy).
* Use both [`width`](img#attr-width) and [`height`](img#attr-height) to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts.
* Responsive image hints with [`sizes`](img#attr-sizes) and [`srcset`](img#attr-srcset) (see also the [`<picture>`](picture) element and our [Responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) tutorial).
Supported image formats
-----------------------
The HTML standard doesn't list what image formats to support, so [user agents](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may support different formats.
**Note:** The [Image file type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types) provides comprehensive information about image formats and their web browser support. This section is just a summary!
The image file formats that are most commonly used on the web are:
* [APNG (Animated Portable Network Graphics)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#apng_animated_portable_network_graphics) — Good choice for lossless animation sequences (GIF is less performant)
* [AVIF (AV1 Image File Format)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#avif_image) — Good choice for both images and animated images due to high performance.
* [GIF (Graphics Interchange Format)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#gif_graphics_interchange_format) — Good choice for *simple* images and animations.
* [JPEG (Joint Photographic Expert Group image)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#jpeg_joint_photographic_experts_group_image) — Good choice for lossy compression of still images (currently the most popular).
* [PNG (Portable Network Graphics)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#png_portable_network_graphics) — Good choice for lossless compression of still images (slightly better quality than JPEG).
* [SVG (Scalable Vector Graphics)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#svg_scalable_vector_graphics) — Vector image format. Use for images that must be drawn accurately at different sizes.
* [WebP (Web Picture format)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#webp_image) — Excellent choice for both images and animated images
Formats like [WebP](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#webp_image) and [AVIF](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#avif_image) are recommended as they perform much better than PNG, JPEG, GIF for both still and animated images. WebP is widely supported while AVIF lacks support in Safari.
SVG remains the recommended format for images that must be drawn accurately at different sizes.
Image loading errors
--------------------
If an error occurs while loading or rendering an image, and an [`onerror`](../global_attributes#onerror) event handler has been set on the [`error`](https://developer.mozilla.org/en-US/docs/Web/API/Element/error_event) event, that event handler will get called. This can happen in a number of situations, including:
* The `src` attribute is empty (`""`) or `null`.
* The `src` [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL) is the same as the URL of the page the user is currently on.
* The image is corrupted in some way that prevents it from being loaded.
* The image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the `<img>` element's attributes.
* The image is in a format not supported by the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent).
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`alt`**](#attr-alt) Defines an alternative text description of the image.
**Note:** Browsers do not always display images. There are a number of situations in which a browser might not display images, such as:
* Non-visual browsers (such as those used by people with visual impairments)
* The user chooses not to display images (saving bandwidth, privacy reasons)
* The image is invalid or an [unsupported type](#supported_image_formats)
In these cases, the browser may replace the image with the text in the element's `alt` attribute. For these reasons and others, provide a useful value for `alt` whenever possible.
Setting this attribute to an empty string (`alt=""`) indicates that this image is *not* a key part of the content (it's decoration or a tracking pixel), and that non-visual browsers may omit it from [rendering](https://developer.mozilla.org/en-US/docs/Glossary/Rendering_engine). Visual browsers will also hide the broken image icon if the `alt` is empty and the image failed to display.
This attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark.
[**`crossorigin`**](#attr-crossorigin) Indicates if the fetching of the image must be done using a [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) request. Image data from a [CORS-enabled image](../cors_enabled_image) returned from a CORS request can be reused in the [`<canvas>`](canvas) element without being marked "[tainted](../cors_enabled_image#what_is_a_tainted_canvas)".
If the `crossorigin` attribute is *not* specified, then a non-CORS request is sent (without the [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in [`<canvas>`](canvas) elements.
If the `crossorigin` attribute *is* specified, then a CORS request is sent (with the [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) request header); but if the server does not opt into allowing cross-origin access to the image data by the origin site (by not sending any [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) response header, or by not including the site's origin in any [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) response header it does send), then the browser blocks the image from loading, and logs a CORS error to the devtools console.
Allowed values:
`anonymous` A CORS request is sent with credentials omitted (that is, no [cookies](https://developer.mozilla.org/en-US/docs/Glossary/Cookie), [X.509 certificates](https://datatracker.ietf.org/doc/html/rfc5280), or [`Authorization`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) request header).
`use-credentials` The CORS request is sent with any credentials included (that is, cookies, X.509 certificates, and the `Authorization` request header). If the server does not opt into sharing credentials with the origin site (by sending back the `Access-Control-Allow-Credentials: true` response header), then the browser marks the image as tainted and restricts access to its image data.
If the attribute has an invalid value, browsers handle it as if the `anonymous` value was used. See [CORS settings attributes](../attributes/crossorigin) for additional information.
[**`decoding`**](#attr-decoding) Provides an image decoding hint to the browser. Allowed values:
`sync` Decode the image synchronously, for atomic presentation with other content.
`async` Decode the image asynchronously, to reduce delay in presenting other content.
`auto` Default: no preference for the decoding mode. The browser decides what is best for the user.
[**`elementtiming`**](#attr-elementtiming) Marks the image for observation by the [`PerformanceElementTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming) API. The value given becomes an identifier for the observed image element. See also the [`elementtiming`](../attributes/elementtiming) attribute page.
[**`fetchpriority`**](#attr-fetchpriority) Experimental
Provides a hint of the relative priority to use when fetching the image. Allowed values:
`high` Signals a high-priority fetch relative to other images.
`low` Signals a low-priority fetch relative to other images.
`auto` Default: Signals automatic determination of fetch priority relative to other images.
[**`height`**](#attr-height) The intrinsic height of the image, in pixels. Must be an integer without a unit.
**Note:** Including `height` and [`width`](#attr-width) enables the aspect ratio of the image to be calculated by the browser prior to the image being loaded. This aspect ratio is used to reserve the space needed to display the image, reducing or even preventing a layout shift when the image is downloaded and painted to the screen. Reducing layout shift is a major component of good user experience and web performance.
[**`ismap`**](#attr-ismap) This Boolean attribute indicates that the image is part of a [server-side map](https://en.wikipedia.org/wiki/Image_map#Server-side). If so, the coordinates where the user clicked on the image are sent to the server.
**Note:** This attribute is allowed only if the `<img>` element is a descendant of an [`<a>`](a) element with a valid [`href`](a#attr-href) attribute. This gives users without pointing devices a fallback destination.
[**`loading`**](#attr-loading) Indicates how the browser should load the image:
`eager` Loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value).
`lazy` Defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. The intent is to avoid the network and storage bandwidth needed to handle the image until it's reasonably certain that it will be needed. This generally improves the performance of the content in most typical use cases.
**Note:** Loading is only deferred when JavaScript is enabled. This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when.
[**`referrerpolicy`**](#attr-referrerpolicy) A string indicating which referrer to use when fetching the resource:
* `no-referrer`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent.
* `no-referrer-when-downgrade`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent to [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)s without [TLS](https://developer.mozilla.org/en-US/docs/Glossary/TLS) ([HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS)).
* `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL), [host](https://developer.mozilla.org/en-US/docs/Glossary/Host), and [port](https://developer.mozilla.org/en-US/docs/Glossary/Port).
* `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
* `same-origin`: A referrer will be sent for [same origin](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy), but cross-origin requests will contain no referrer information.
* `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
* `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
* `unsafe-url`: The referrer will include the origin *and* the path (but not the [fragment](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins.
[**`sizes`**](#attr-sizes) One or more strings separated by commas, indicating a set of source sizes. Each source size consists of:
1. A [media condition](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#syntax). This must be omitted for the last item in the list.
2. A source size value.
Media Conditions describe properties of the *viewport*, not of the *image*. For example, `(max-height: 500px) 1000px` proposes to use a source of 1000px width, if the *viewport* is not higher than 500px.
Source size values specify the intended display size of the image. [User agents](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) use the current source size to select one of the sources supplied by the `srcset` attribute, when those sources are described using width (`w`) descriptors. The selected source size affects the [intrinsic size](https://developer.mozilla.org/en-US/docs/Glossary/Intrinsic_Size) of the image (the image's display size if no [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS) styling is applied). If the `srcset` attribute is absent, or contains no values with a width descriptor, then the `sizes` attribute has no effect.
[**`src`**](#attr-src) The image [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL). Mandatory for the `<img>` element. On [browsers](https://developer.mozilla.org/en-US/docs/Glossary/Browser) supporting `srcset`, `src` is treated like a candidate image with a pixel density descriptor `1x`, unless an image with this pixel density descriptor is already defined in `srcset`, or unless `srcset` contains `w` descriptors.
[**`srcset`**](#attr-srcset) One or more strings separated by commas, indicating possible image sources for the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) to use. Each string is composed of:
1. A [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL) to an image
2. Optionally, whitespace followed by one of:
* A width descriptor (a positive integer directly followed by `w`). The width descriptor is divided by the source size given in the `sizes` attribute to calculate the effective pixel density.
* A pixel density descriptor (a positive floating point number directly followed by `x`).
If no descriptor is specified, the source is assigned the default descriptor of `1x`.
It is incorrect to mix width descriptors and pixel density descriptors in the same `srcset` attribute. Duplicate descriptors (for instance, two sources in the same `srcset` which are both described with `2x`) are also invalid.
If the `srcset` attribute uses width descriptors, the `sizes` attribute must also be present, or the `srcset` itself will be ignored.
The user agent selects any of the available sources at its discretion. This provides them with significant leeway to tailor their selection based on things like user preferences or [bandwidth](https://developer.mozilla.org/en-US/docs/Glossary/Bandwidth) conditions. See our [Responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) tutorial for an example.
[**`width`**](#attr-width) The intrinsic width of the image in pixels. Must be an integer without a unit.
[**`usemap`**](#attr-usemap) The partial [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL) (starting with `#`) of an [image map](map) associated with the element.
**Note:** You cannot use this attribute if the `<img>` element is inside an [`<a>`](a) or [`<button>`](button) element.
### Deprecated attributes
[**`align`**](#attr-align) Deprecated
Aligns the image with its surrounding context. Use the [`float`](https://developer.mozilla.org/en-US/docs/Web/CSS/float) and/or [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS) properties instead of this attribute. Allowed values:
`top` Equivalent to `vertical-align: top` or `vertical-align: text-top`
`middle` Equivalent to `vertical-align: -moz-middle-with-baseline`
`bottom` The default, equivalent to `vertical-align: unset` or `vertical-align: initial`
`left` Equivalent to `float: left`
`right` Equivalent to `float: right`
[**`border`**](#attr-border) Deprecated
The width of a border around the image. Use the [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS) property instead.
[**`hspace`**](#attr-hspace) Deprecated
The number of pixels of white space on the left and right of the image. Use the [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) CSS property instead.
[**`longdesc`**](#attr-longdesc) Deprecated
A link to a more detailed description of the image. Possible values are a [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL) or an element [`id`](../global_attributes#id).
**Note:** This attribute is mentioned in the latest [W3C](https://developer.mozilla.org/en-US/docs/Glossary/W3C) version, [HTML 5.2](https://html.spec.whatwg.org/multipage/obsolete.html#element-attrdef-img-longdesc), but has been removed from the [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG)'s [HTML Living Standard](https://html.spec.whatwg.org/multipage/embedded-content.html#the-img-element). It has an uncertain future; authors should use a [WAI](https://developer.mozilla.org/en-US/docs/Glossary/WAI)-[ARIA](https://developer.mozilla.org/en-US/docs/Glossary/ARIA) alternative such as [`aria-describedby`](https://www.w3.org/TR/wai-aria-1.1/#aria-describedby) or [`aria-details`](https://www.w3.org/TR/wai-aria-1.1/#aria-details).
[**`name`**](#attr-name) Deprecated
A name for the element. Use the [`id`](../global_attributes#id) attribute instead.
[**`vspace`**](#attr-vspace) Deprecated
The number of pixels of white space above and below the image. Use the [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) CSS property instead.
Styling with CSS
----------------
`<img>` is a [replaced element](https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element); it has a [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) value of `inline` by default, but its default dimensions are defined by the embedded image's intrinsic values, like it were `inline-block`. You can set properties like [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border)/[`border-radius`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius), [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding)/[`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin), [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width), [`height`](https://developer.mozilla.org/en-US/docs/Web/CSS/height), etc. on an image.
`<img>` has no baseline, so when images are used in an inline formatting context with [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align)`: baseline`, the bottom of the image will be placed on the text baseline.
You can use the [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) property to position the image within the element's box, and the [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) property to adjust the sizing of the image within the box (for example, whether the image should fit the box or fill it even if clipping is required).
Depending on its type, an image may have an intrinsic width and height. For some image types, however, intrinsic dimensions are unnecessary. [SVG](https://developer.mozilla.org/en-US/docs/Glossary/SVG) images, for instance, have no intrinsic dimensions if their root [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg) element doesn't have a `width` or `height` set on it.
Examples
--------
### Alternative text
The following example embeds an image into the page and includes alternative text for accessibility.
```
<img src="favicon144.png" alt="MDN logo" />
```
### Image link
This example builds upon the previous one, showing how to turn the image into a link. To do so, nest the `<img>` tag inside the [`<a>`](a). You should make the alternative text describe the resource the link is pointing to, as if you were using a text link instead.
```
<a href="https://developer.mozilla.org">
<img src="favicon144.png" alt="Visit the MDN site" />
</a>
```
### Using the srcset attribute
In this example we include a `srcset` attribute with a reference to a high-resolution version of the logo; this will be loaded instead of the `src` image on high-resolution devices. The image referenced in the `src` attribute is counted as a `1x` candidate in [user agents](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) that support `srcset`.
```
<img src="favicon72.png" alt="MDN logo" srcset="favicon144.png 2x" />
```
### Using the srcset and sizes attributes
The `src` attribute is ignored in [user agents](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) that support `srcset` when `w` descriptors are included. When the `(max-width: 600px)` media condition matches, the 200 pixel-wide image will load (it is the one that matches `200px` most closely), otherwise the other image will load.
```
<img
src="clock-demo-200px.png"
alt="Clock"
srcset="clock-demo-200px.png 200w, clock-demo-400px.png 400w"
sizes="(max-width: 600px) 200px, 50vw" />
```
**Note:** To see the resizing in action, [view the example on a separate page](https://yari-demos.prod.mdn.mozit.cloud/en-US/docs/Web/HTML/Element/img/_sample_.Using_the_srcset_and_sizes_attributes.html), so you can actually resize the content area.
Security and privacy concerns
-----------------------------
Although `<img>` elements have innocent uses, they can have undesirable consequences for user security and privacy. See [Referer header: privacy and security concerns](https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) for more information and mitigations.
Accessibility concerns
----------------------
### Authoring meaningful alternate descriptions
An `alt` attribute's value should clearly and concisely describe the image's content. It should not describe the presence of the image itself or the file name of the image. If the `alt` attribute is purposefully left off because the image has no textual equivalent, consider alternate methods to present what the image is trying to communicate.
#### Don't
```
<img alt="image" src="penguin.jpg" />
```
#### Do
```
<img alt="A Rockhopper Penguin standing on a beach." src="penguin.jpg" />
```
When an `alt` attribute is not present on an image, some screen readers may announce the image's file name instead. This can be a confusing experience if the file name isn't representative of the image's contents.
* [An alt Decision Tree • Images • WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/images/decision-tree/)
* [Alt-texts: The Ultimate Guide — Axess Lab](https://axesslab.com/alt-texts/)
* [How to Design Great Alt Text: An Introduction | Deque](https://www.deque.com/blog/great-alt-text-introduction/)
* [MDN Understanding WCAG, Guideline 1.1 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.1_%E2%80%94_providing_text_alternatives_for_non-text_content)
* [Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/text-equiv-all.html)
### Identifying SVG as an image
Due to a [VoiceOver bug](https://bugs.webkit.org/show_bug.cgi?id=216364), VoiceOver does not correctly announce SVG images as images. Include [`role="img"`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/img_role) to all `<img>` elements with SVG source files to ensure assistive technologies correctly announce the SVG as image content.
```
<img src="mdn.svg" alt="MDN logo" role="img" />
```
### The title attribute
The [`title`](../global_attributes#title) attribute is not an acceptable substitute for the `alt` attribute. Additionally, avoid duplicating the `alt` attribute's value in a `title` attribute declared on the same image. Doing so may cause some screen readers to announce the description twice, creating a confusing experience.
The `title` attribute should also not be used as supplemental captioning information to accompany an image's `alt` description. If an image needs a caption, use the [`figure`](figure) and [`figcaption`](figcaption) elements.
The value of the `title` attribute is usually presented to the user as a tooltip, which appears shortly after the cursor stops moving over the image. While this *can* provide additional information to the user, you should not assume that the user will ever see it: the user may only have keyboard or touchscreen. If you have information that's particularly important or valuable for the user, present it inline using one of the methods mentioned above instead of using `title`.
* [Using the HTML title attribute – updated | The Paciello Group](https://www.tpgi.com/using-the-html-title-attribute-updated/)
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [embedded content](../content_categories#embedded_content), [palpable content](../content_categories#palpable_content). If the element has a `usemap` attribute, it also is a part of the interactive content category. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | Must have a start tag and must not have an end tag. |
| Permitted parents | Any element that accepts embedded content. |
| Implicit ARIA role | * with non-empty `alt` attribute or no `alt` attribute: `[`img`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/img_role)`
* with empty `alt` attribute: [`presentation`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role)
|
| Permitted ARIA roles | * with non-empty `alt` attribute:
+ `[button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)`
+ `[checkbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role)`
+ `[link](https://w3c.github.io/aria/#link)`
+ `[menuitem](https://w3c.github.io/aria/#menuitem)`
+ `[menuitemcheckbox](https://w3c.github.io/aria/#menuitemcheckbox)`
+ `[menuitemradio](https://w3c.github.io/aria/#menuitemradio)`
+ `[option](https://w3c.github.io/aria/#option)`
+ `[progressbar](https://w3c.github.io/aria/#progressbar)`
+ `[scrollbar](https://w3c.github.io/aria/#scrollbar)`
+ `[separator](https://w3c.github.io/aria/#separator)`
+ `[slider](https://w3c.github.io/aria/#slider)`
+ `[switch](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role)`
+ `[tab](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role)`
+ `[treeitem](https://w3c.github.io/aria/#treeitem)`
* with empty `alt` attribute, `[none](https://w3c.github.io/aria/#none)` or `[presentation](https://w3c.github.io/aria/#presentation)`
* with no `alt` attribute, no `role` permitted
|
| DOM interface | [`HTMLImageElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-img-element](https://html.spec.whatwg.org/multipage/embedded-content.html#the-img-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `img` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `align` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `alt` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `aspect_ratio_computed_from_attributes` | 79 | 79 | 71 | No | 66 | 15
14-15
Safari doesn't preserve space for images without a valid `src`, which may disrupt layouts that rely on lazy loading (see [bug 224197](https://webkit.org/b/224197)). | 79 | 79 | 79 | 57 | 15
14-15
Safari doesn't preserve space for images without a valid `src`, which may disrupt layouts that rely on lazy loading (see [bug 224197](https://webkit.org/b/224197)). | 12.0 |
| `border` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `crossorigin` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `decoding` | Yes | ≤79 | 63 | No | Yes | 11.1 | Yes | Yes | 63 | Yes | 11.3 | Yes |
| `fetchpriority` | 101 | 101 | No | No | No | No | 101 | 101 | No | 70 | No | 19.0 |
| `height` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `hspace` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `ismap` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `loading` | 77 | 79 | 75 | No | 64 | 15.4 | 77 | 77 | 79 | 55 | 15.4 | 12.0 |
| `longdesc` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `name` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `onerror` | Yes | ≤79 | 51 | No | Yes | Yes | Yes | Yes | 51 | Yes | Yes | Yes |
| `referrerpolicy` | 51 | 79 | 50 | No | 38 | 14 | 51 | 51 | 50 | 41 | 14 | 7.2 |
| `sizes` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `src` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `srcset` | 34 | ≤18 | 38 | No | 21 | 8 | 37 | 34 | 38 | 21 | 8 | 2.0 |
| `usemap` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `vspace` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `width` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* [Images in HTML](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML)
* [Image file type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types)
* [Responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images)
* [`<picture>`](picture), [`<object>`](object) and [`<embed>`](embed) elements
* Other image-related CSS properties: [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit), [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position), [`image-orientation`](https://developer.mozilla.org/en-US/docs/Web/CSS/image-orientation), [`image-rendering`](https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering), and [`image-resolution`](https://developer.mozilla.org/en-US/docs/Web/CSS/image-resolution).
| programming_docs |
html <frame> <frame>
=======
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<frame>` [HTML](../index) element defines a particular area in which another HTML document can be displayed. A frame should be used within a [`<frameset>`](frameset).
Using the `<frame>` element is not encouraged because of certain disadvantages such as performance problems and lack of accessibility for users with screen readers. Instead of the `<frame>` element, [`<iframe>`](iframe) may be preferred.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes).
[**`src`**](#attr-src) Deprecated
This attribute specifies the document that will be displayed by the frame.
[**`name`**](#attr-name) Deprecated
This attribute is used for labeling frames. Without labeling, every link will open in the frame that it's in – the closest parent frame. See the [`target`](a#attr-target) attribute for more information.
[**`noresize`**](#attr-noresize) Deprecated
This attribute prevents resizing of frames by users.
[**`scrolling`**](#attr-scrolling) Deprecated
This attribute defines the existence of a scrollbar. If this attribute is not used, the browser adds a scrollbar when necessary. There are two choices: "yes" for forcing a scrollbar even when it is not necessary and "no" for forcing no scrollbar even when it *is* necessary.
[**`marginheight`**](#attr-marginheight) Deprecated
This attribute defines the height of the margin between frames.
[**`marginwidth`**](#attr-marginwidth) Deprecated
This attribute defines the width of the margin between frames.
[**`frameborder`**](#attr-frameborder) Deprecated
This attribute allows you to specify a frame's border.
Example
-------
```
<frameset cols="50%,50%">
<frame src="https://developer.mozilla.org/en/HTML/Element/iframe" />
<frame src="https://developer.mozilla.org/en/HTML/Element/frame" />
</frameset>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # frame](https://html.spec.whatwg.org/multipage/obsolete.html#frame) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `frame` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `frameborder` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `marginheight` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `marginwidth` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `name` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `noresize` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `scrolling` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `src` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* [`<frameset>`](frameset)
* [`<iframe>`](iframe)
html <video>: The Video Embed element <video>: The Video Embed element
================================
The `<video>` [HTML](../index) element embeds a media player which supports video playback into the document. You can use `<video>` for audio content as well, but the [`<audio>`](audio) element may provide a more appropriate user experience.
Try it
------
The above example shows simple usage of the `<video>` element. In a similar manner to the [`<img>`](img) element, we include a path to the media we want to display inside the `src` attribute; we can include other attributes to specify information such as video width and height, whether we want it to autoplay and loop, whether we want to show the browser's default video controls, etc.
The content inside the opening and closing `<video></video>` tags is shown as a fallback in browsers that don't support the element.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes).
[**`autoplay`**](#attr-autoplay) A Boolean attribute; if specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data.
**Note:** Sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. If you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). However, this can be useful when creating media elements whose source will be set at a later time, under user control. See our [autoplay guide](https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide) for additional information about how to properly use autoplay.
To disable video autoplay, `autoplay="false"` will not work; the video will autoplay if the attribute is there in the `<video>` tag at all. To remove autoplay, the attribute needs to be removed altogether.
In some browsers (e.g. Chrome 70.0) autoplay doesn't work if no `muted` attribute is present.
[**`autopictureinpicture`**](#attr-autopictureinpicture) Experimental
A Boolean attribute which if `true` indicates that the element should automatically toggle picture-in-picture mode when the user switches back and forth between this document and another document or application.
[**`controls`**](#attr-controls) If this attribute is present, the browser will offer controls to allow the user to control video playback, including volume, seeking, and pause/resume playback.
[**`controlslist`**](#attr-controlslist) Experimental Non-standard
The [`controlslist`](https://wicg.github.io/controls-list/explainer.html) attribute, when specified, helps the browser select what controls to show for the `video` element whenever the browser shows its own set of controls (that is, when the `controls` attribute is specified).
The allowed values are `nodownload`, `nofullscreen` and `noremoteplayback`.
Use the [`disablepictureinpicture`](#attr-disablepictureinpicture) attribute if you want to disable the Picture-In-Picture mode (and the control).
[**`crossorigin`**](#attr-crossorigin) This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute indicates whether to use CORS to fetch the related video. [CORS-enabled resources](../cors_enabled_image) can be reused in the [`<canvas>`](canvas) element without being *tainted*. The allowed values are:
`anonymous` Sends a cross-origin request without a credential. In other words, it sends the `Origin:` HTTP header without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (by not setting the `Access-Control-Allow-Origin:` HTTP header), the resource will be *tainted*, and its usage restricted.
`use-credentials` Sends a cross-origin request with a credential. In other words, it sends the `Origin:` HTTP header with a cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (through `Access-Control-Allow-Credentials:` HTTP header), the resource will be *tainted* and its usage restricted.
When not present, the resource is fetched without a CORS request (i.e. without sending the `Origin:` HTTP header), preventing its non-tainted use in [`<canvas>`](canvas) elements. If invalid, it is handled as if the enumerated keyword `anonymous` was used. See [CORS settings attributes](../attributes/crossorigin) for additional information.
[**`disablepictureinpicture`**](#attr-disablepictureinpicture) Experimental
Prevents the browser from suggesting a Picture-in-Picture context menu or to request Picture-in-Picture automatically in some cases.
[**`disableremoteplayback`**](#attr-disableremoteplayback) Experimental
A Boolean attribute used to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc.).
In Safari, you can use [`x-webkit-airplay="deny"`](https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/AirPlayGuide/OptingInorOutofAirPlay/OptingInorOutofAirPlay.html) as a fallback.
[**`height`**](#attr-height) The height of the video's display area, in [CSS pixels](https://drafts.csswg.org/css-values/#px) (absolute values only; [no percentages](https://html.spec.whatwg.org/multipage/embedded-content.html#dimension-attributes)).
[**`loop`**](#attr-loop) A Boolean attribute; if specified, the browser will automatically seek back to the start upon reaching the end of the video.
[**`muted`**](#attr-muted) A Boolean attribute that indicates the default setting of the audio contained in the video. If set, the audio will be initially silenced. Its default value is `false`, meaning that the audio will be played when the video is played.
[**`playsinline`**](#attr-playsinline) A Boolean attribute indicating that the video is to be played "inline", that is within the element's playback area. Note that the absence of this attribute *does not* imply that the video will always be played in fullscreen.
[**`poster`**](#attr-poster) A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
[**`preload`**](#attr-preload) This enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience regarding what content is loaded before the video is played. It may have one of the following values:
* `none`: Indicates that the video should not be preloaded.
* `metadata`: Indicates that only video metadata (e.g. length) is fetched.
* `auto`: Indicates that the whole video file can be downloaded, even if the user is not expected to use it.
* *empty string*: Synonym of the `auto` value.
The default value is different for each browser. The spec advises it to be set to `metadata`.
**Note:**
* The `autoplay` attribute has precedence over `preload`. If `autoplay` is specified, the browser would obviously need to start downloading the video for playback.
* The specification does not force the browser to follow the value of this attribute; it is a mere hint.
[**`src`**](#attr-src) The URL of the video to embed. This is optional; you may instead use the [`<source>`](source) element within the video block to specify the video to embed.
[**`width`**](#attr-width) The width of the video's display area, in [CSS pixels](https://drafts.csswg.org/css-values/#px) (absolute values only; [no percentages](https://html.spec.whatwg.org/multipage/embedded-content.html#dimension-attributes)).
Events
------
| Event Name | Fired When |
| --- | --- |
| [`audioprocess`](https://developer.mozilla.org/en-US/docs/Web/API/ScriptProcessorNode/audioprocess_event) Deprecated | The input buffer of a [`ScriptProcessorNode`](https://developer.mozilla.org/en-US/docs/Web/API/ScriptProcessorNode) is ready to be processed. |
| [`canplay`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplay_event) | The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. |
| [`canplaythrough`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event) | The browser estimates it can play the media up to its end without stopping for content buffering. |
| [`complete`](https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext/complete_event) | The rendering of an [`OfflineAudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext) is terminated. |
| [`durationchange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/durationchange_event) | The `duration` attribute has been updated. |
| [`emptied`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/emptied_event) | The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the [`load()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/load) method is called to reload it. |
| [`ended`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended_event) | Playback has stopped because the end of the media was reached. |
| [`error`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error_event) | An error occurred while fetching the media data, or the type of the resource is not a supported media format. |
| [`loadeddata`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadeddata_event) | The first frame of the media has finished loading. |
| [`loadedmetadata`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadedmetadata_event) | The metadata has been loaded. |
| [`pause`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause_event) | Playback has been paused. |
| [`play`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play_event) | Playback has begun. |
| [`playing`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playing_event) | Playback is ready to start after having been paused or delayed due to lack of data. |
| [`progress`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/progress_event) | Fired periodically as the browser loads a resource. |
| [`ratechange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ratechange_event) | The playback rate has changed. |
| [`seeked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeked_event) | A *seek* operation completed. |
| [`seeking`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeking_event) | A *seek* operation began. |
| [`stalled`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/stalled_event) | The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. |
| [`suspend`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/suspend_event) | Media data loading has been suspended. |
| [`timeupdate`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event) | The time indicated by the `currentTime` attribute has been updated. |
| [`volumechange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/volumechange_event) | The volume has changed. |
| [`waiting`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/waiting_event) | Playback has stopped because of a temporary lack of data. |
Usage notes
-----------
Browsers don't all support the same video formats; you can provide multiple sources inside nested [`<source>`](source) elements, and the browser will then use the first one it understands.
```
<video controls>
<source src="myVideo.webm" type="video/webm" />
<source src="myVideo.mp4" type="video/mp4" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="myVideo.mp4">link to the video</a> instead.
</p>
</video>
```
We offer a substantive and thorough [guide to media file types](https://developer.mozilla.org/en-US/docs/Web/Media/Formats) and the [guide to the codecs supported for video](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs). Also available is a guide to [audio codecs that can be used with them](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs).
Other usage notes:
* If you don't specify the `controls` attribute, the video won't include the browser's default controls; you can create your own custom controls using JavaScript and the [`HTMLMediaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) API. See [Creating a cross-browser video player](https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/cross_browser_video_player) for more details.
* To allow precise control over your video (and audio) content, `HTMLMediaElement`s fire many different [events](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#events). In addition to providing controllability, these events let you monitor the progress of both download and playback of the media, as well as the playback state and position.
* You can use the [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) property to adjust the positioning of the video within the element's frame, and the [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) property to control how the video's size is adjusted to fit within the frame.
* To show subtitles/captions along with your video, you can use some JavaScript along with the [`<track>`](track) element and the [WebVTT](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API) format. See [Adding captions and subtitles to HTML video](https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video) for more information.
* You can play audio files using a `<video>` element. This can be useful if, for example, you need to perform audio with a [WebVTT](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API) transcript, since the [`<audio>`](audio) element doesn't allow captions using WebVTT.
* To test the fallback content on browsers that support the element, you can replace `<video>` with a non-existing element like `<notavideo>`.
A good general source of information on using HTML `<video>` is the [Video and audio content](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) beginner's tutorial.
### Styling with CSS
The `<video>` element is a replaced element — its [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) value is `inline` by default, but its default width and height in the viewport is defined by the video being embedded.
There are no special considerations for styling `<video>`; a common strategy is to give it a `display` value of `block` to make it easier to position, size, etc., and then provide styling and layout information as required. [Video player styling basics](https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/Video_player_styling_basics) provides some useful styling techniques.
### Detecting track addition and removal
You can detect when tracks are added to and removed from a `<video>` element using the [`addtrack`](https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList/addtrack_event) and [`removetrack`](https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList/removetrack_event) events. However, these events aren't sent directly to the `<video>` element itself. Instead, they're sent to the track list object within the `<video>` element's [`HTMLMediaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) that corresponds to the type of track that was added to the element:
[`HTMLMediaElement.audioTracks`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/audioTracks) An [`AudioTrackList`](https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList) containing all of the media element's audio tracks. You can add a listener for `addtrack` to this object to be alerted when new audio tracks are added to the element.
[`HTMLMediaElement.videoTracks`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/videoTracks) Add an `addtrack` listener to this [`VideoTrackList`](https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList) object to be informed when video tracks are added to the element.
[`HTMLMediaElement.textTracks`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/textTracks) Add an `addtrack` event listener to this [`TextTrackList`](https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList) to be notified when new text tracks are added to the element.
For example, to detect when audio tracks are added to or removed from a `<video>` element, you can use code like this:
```
const elem = document.querySelector("video");
elem.audioTracks.onaddtrack = (event) => {
trackEditor.addTrack(event.track);
};
elem.audioTracks.onremovetrack = (event) => {
trackEditor.removeTrack(event.track);
};
```
This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks.
You can also use [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) to listen for the [`addtrack`](https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList/addtrack_event) and [`removetrack`](https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList/removetrack_event) events.
### Server support for video
If the MIME type for the video is not set correctly on the server, the video may not show or show a gray box containing an X (if JavaScript is enabled).
If you use Apache Web Server to serve Ogg Theora videos, you can fix this problem by adding the video file type extensions to "video/ogg" MIME type. The most common video file type extensions are ".ogm", ".ogv", or ".ogg". To do this, edit the "mime.types" file in "/etc/apache" or use the `"AddType"` configuration directive in `httpd.conf`.
```
AddType video/ogg .ogm
AddType video/ogg .ogv
AddType video/ogg .ogg
```
If you serve your videos as WebM, you can fix this problem for the Apache Web Server by adding the extension used by your video files (".webm" is the most common one) to the MIME type "video/webm" via the "mime.types" file in "/etc/apache" or via the "AddType" configuration directive in `httpd.conf`.
```
AddType video/webm .webm
```
Your web host may provide an easy interface to MIME type configuration changes for new technologies until a global update naturally occurs.
Examples
--------
### Single source
This example plays a video when activated, providing the user with the browser's default video controls to control playback.
#### HTML
```
<!-- Simple video example -->
<!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org -->
<!-- Poster from peach.blender.org -->
<video
controls
src="https://archive.org/download/BigBuckBunny\_124/Content/big\_buck\_bunny\_720p\_surround.mp4"
poster="https://peach.blender.org/wp-content/uploads/title\_anouncement.jpg?x11217"
width="620">
Sorry, your browser doesn't support embedded videos, but don't worry, you can
<a href="https://archive.org/details/BigBuckBunny\_124">download it</a>
and watch it with your favorite video player!
</video>
```
#### Result
Until the video starts playing, the image provided in the `poster` attribute is displayed in its place. If the browser doesn't support video playback, the fallback text is displayed.
### Multiple sources
This example builds on the last one, offering three different sources for the media; this allows the video to be watched regardless of which video codecs are supported by the browser.
#### HTML
```
<!-- Using multiple sources as fallbacks for a video tag -->
<!-- 'Elephants Dream' by Orange Open Movie Project Studio, licensed under CC-3.0, hosted by archive.org -->
<!-- Poster hosted by Wikimedia -->
<video
width="620"
controls
poster="https://upload.wikimedia.org/wikipedia/commons/e/e8/Elephants\_Dream\_s5\_both.jpg">
<source
src="https://archive.org/download/ElephantsDream/ed\_hd.ogv"
type="video/ogg" />
<source
src="https://archive.org/download/ElephantsDream/ed\_hd.avi"
type="video/avi" />
<source
src="https://archive.org/download/ElephantsDream/ed\_1024\_512kb.mp4"
type="video/mp4" />
Sorry, your browser doesn't support embedded videos, but don't worry, you can
<a href="https://archive.org/download/ElephantsDream/ed\_1024\_512kb.mp4">
download the MP4
</a>
and watch it with your favorite video player!
</video>
```
#### Result
First [Ogg](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#ogg) is tried. If that can't be played, then AVI is tried. Finally, [MP4](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#mpeg-4_mp4) is tried. A fallback message is displayed if the video element isn't supported, but not if all sources fail.
Some media file types let you provide more specific information using the [`codecs`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter) parameter as part of the file's type string. A relatively simple example is `video/webm; codecs="vp8, vorbis"`, which says that the file is a [WebM](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#webm) video using [VP8](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs#vp8) for its video and [Vorbis](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs#vorbis) for audio.
Accessibility concerns
----------------------
Videos should provide both captions and transcripts that accurately describe its content (see [Adding captions and subtitles to HTML video](https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video) for more information on how to implement these). Captions allow people who are experiencing hearing loss to understand a video's audio content as the video is being played, while transcripts allow people who need additional time to be able to review audio content at a pace and format that is comfortable for them.
It's worth noting that while you can caption audio-only media, you can only do so when playing audio in a [`<video>`](video) element, since the video region of the element is used to present the captions. This is one of the special scenarios in which it's useful to play audio in a video element.
If automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source video.
In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone:
```
14
00:03:14 --> 00:03:18
[Dramatic rock music]
15
00:03:19 --> 00:03:21
[whispering] What's that off in the distance?
16
00:03:22 --> 00:03:24
It's… it's a…
16 00:03:25 --> 00:03:32
[Loud thumping]
[Dishes clattering]
```
Captions should not obstruct the main subject of the video. They can be positioned using [the `align` VTT cue setting](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API#cue_settings).
* [Web Video Text Tracks Format (WebVTT)](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API)
* [WebAIM: Captions, Transcripts, and Audio Descriptions](https://webaim.org/techniques/captions/)
* [MDN Understanding WCAG, Guideline 1.2 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.2_%E2%80%94_providing_text_alternatives_for_time-based_media)
* [Understanding Success Criterion 1.2.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-av-only-alt.html)
* [Understanding Success Criterion 1.2.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-captions.html)
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), phrasing content, embedded content. If it has a [`controls`](video#attr-controls) attribute: interactive content and palpable content. |
| Permitted content | If the element has a [`src`](video#attr-src) attribute: zero or more [`<track>`](track) elements, followed by transparent content that contains no media elements–that is no [`<audio>`](audio) or [`<video>`](video). Else: zero or more [`<source>`](source) elements, followed by zero or more [`<track>`](track) elements, followed by transparent content that contains no media elements–that is no [`<audio>`](audio) or [`<video>`](video). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts embedded content. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[application](https://w3c.github.io/aria/#application)` |
| DOM interface | [`HTMLVideoElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-video-element](https://html.spec.whatwg.org/multipage/media.html#the-video-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `video` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | Yes | Yes | 4 | Yes | 3 | Yes |
| `aspect_ratio_computed_from_attributes` | 79 | 79 | 71 | No | 66 | 14 | 79 | 79 | 79 | 57 | 14 | 12.0 |
| `autoplay` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | Yes | Yes | 4 | Yes | 10
Only available for videos that have [no sound or have the audio track disabled](https://developer.apple.com/library/content/releasenotes/General/WhatsNewInSafari/Articles/Safari_10_0.html). | Yes |
| `controls` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | Yes | Yes | 4 | Yes | 3 | Yes |
| `crossorigin` | No | ≤18 | 74
12-74
With `crossorigin="use-credentials"`, cookies aren't sent during seek. See [bug 1532722](https://bugzil.la/1532722). | No | No | No | No | No | 79
14-79
With `crossorigin="use-credentials"`, cookies aren't sent during seek. See [bug 1532722](https://bugzil.la/1532722). | No | No | No |
| `height` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | Yes | Yes | 4 | Yes | 3 | Yes |
| `loop` | 3 | 12 | 11 | 9 | 10.5 | 3.1 | Yes | Yes | 14 | Yes | 6 | Yes |
| `muted` | 30 | 12 | 11 | 10 | Yes | 5 | Yes | Yes | 14 | Yes | No | Yes |
| `poster` | 3 | 12 | 3.6 | 9 | 10.5 | 3.1 | Yes | Yes | 4 | Yes | 3 | Yes |
| `preload` | 3
Defaults to `metadata` in Chrome 64. | 12 | 4 | 9 | Yes
Defaults to `metadata` in Opera 51. | 3.1 | Yes
Defaults to `metadata` in Chrome 64. | Yes
Defaults to `metadata` in Chrome 64. | 4 | Yes
Defaults to `metadata` in Opera 51. | 3 | Yes
Defaults to `metadata` in Samsung Internet 9.0. |
| `src` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | Yes | Yes | 4 | Yes | 3 | Yes |
| `width` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | Yes | Yes | 4 | Yes | 3 | Yes |
See also
--------
* [Guide to media types and formats on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats)
+ [Media container formats (file types)](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers)
+ [Web video codec guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs)
+ [Web audio codec guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs)
* Positioning and sizing the picture within its frame: [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) and [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
* [`<audio>`](audio)
* [Using HTML audio and video](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content)
* [Manipulating video using canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Manipulating_video_using_canvas)
* [Configuring servers for Ogg media](https://developer.mozilla.org/en-US/docs/Web/HTTP/Configuring_servers_for_Ogg_media)
| programming_docs |
html <title>: The Document Title element <title>: The Document Title element
===================================
The `<title>` [HTML](../index) element defines the document's title that is shown in a [browser](https://developer.mozilla.org/en-US/docs/Glossary/Browser)'s title bar or a page's tab. It only contains text; tags within the element are ignored.
```
<title>Grandma's Heavy Metal Festival Journal</title>
```
| | |
| --- | --- |
| [Content categories](../content_categories) | [Metadata content](../content_categories#metadata_content). |
| Permitted content | Text that is not inter-element [whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace). |
| Tag omission | Both opening and closing tags are required. Note that leaving off `</title>` should cause the browser to ignore the rest of the page. |
| Permitted parents | A [`<head>`](head) element that contains no other [`<title>`](title) element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted. |
| DOM interface | [`HTMLTitleElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTitleElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
The `<title>` element is always used within a page's [`<head>`](head) block.
### Page titles and SEO
The contents of a page title can have significant implications for search engine optimization ([SEO](https://developer.mozilla.org/en-US/docs/Glossary/SEO)). In general, a longer, descriptive title performs better than short or generic titles. The content of the title is one of the components used by search engine algorithms to decide the order in which to list pages in search results. Also, the title is the initial "hook" by which you grab the attention of readers glancing at the search results page.
A few guidelines and tips for composing good titles:
* Avoid one- or two-word titles. Use a descriptive phrase, or a term-definition pairing for glossary or reference-style pages.
* Search engines typically display about the first 55–60 characters of a page title. Text beyond that may be lost, so try not to have titles longer than that. If you must use a longer title, make sure the important parts come earlier and that nothing critical is in the part of the title that is likely to be dropped.
* Don't use "keyword blobs." If your title is just a list of words, algorithms often reduce your page's position in the search results.
* Try to make sure your titles are as unique as possible within your own site. Duplicate—or near-duplicate—titles can contribute to inaccurate search results.
Example
-------
```
<title>Awesome interesting stuff</title>
```
This example establishes a page whose title (as displayed at the top of the window or in the window's tab) as "Awesome interesting stuff".
Accessibility concerns
----------------------
It is important to provide an accurate and concise title to describe the page's purpose.
A common navigation technique for users of assistive technology is to read the page title and infer the content the page contains. This is because navigating into a page to determine its content can be a time-consuming and potentially confusing process. Titles should be unique to every page of a website, ideally surfacing the primary purpose of the page first, followed by the name of the website. Following this pattern will help ensure that the primary purpose of the page is announced by a screen reader first. This provides a far better experience than having to listen to the name of a website before the unique page title, for every page a user navigates to in the same website.
### Example
```
<title>Menu - Blue House Chinese Food - FoodYum: Online takeout today!</title>
```
If a form submission contains errors and the submission re-renders the current page, the title can be used to help make users aware of any errors with their submission. For instance, update the page `title` value to reflect significant page state changes (such as form validation problems).
```
<title>
2 errors - Your order - Sea Food Store - Food: Online takeout today!
</title>
```
**Note:** Presently, dynamically updating a page's title will not be automatically announced by screen readers. If you are going to update the page title to reflect significant changes to a page's state, then the use of [ARIA Live Regions](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) may be necessary, as well.
* [MDN Understanding WCAG, Guideline 2.4 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.4_%E2%80%94_navigable_provide_ways_to_help_users_navigate_find_content_and_determine_where_they_are)
* [Understanding Success Criterion 2.4.2 | W3C Understanding WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/page-titled.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-title-element](https://html.spec.whatwg.org/multipage/semantics.html#the-title-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `title` | 1 | 12 | 1 | 1 | Yes | 1 | Yes | Yes | 4 | Yes | Yes | Yes |
html <progress>: The Progress Indicator element <progress>: The Progress Indicator element
==========================================
The `<progress>` [HTML](../index) element displays an indicator showing the completion progress of a task, typically displayed as a progress bar.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), labelable content, palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content), but there must be no `<progress>` element among its descendants. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | `[progressbar](https://w3c.github.io/aria/#progressbar)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLProgressElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLProgressElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`max`**](#attr-max) This attribute describes how much work the task indicated by the `progress` element requires. The `max` attribute, if present, must have a value greater than `0` and be a valid floating point number. The default value is `1`.
[**`value`**](#attr-value) This attribute specifies how much of the task that has been completed. It must be a valid floating point number between `0` and `max`, or between `0` and `1` if `max` is omitted. If there is no `value` attribute, the progress bar is indeterminate; this indicates that an activity is ongoing with no indication of how long it is expected to take.
**Note:** Unlike the [`<meter>`](meter) element, the minimum value is always 0, and the `min` attribute is not allowed for the `<progress>` element.
**Note:** The [`:indeterminate`](https://developer.mozilla.org/en-US/docs/Web/CSS/:indeterminate) pseudo-class can be used to match against indeterminate progress bars. To change the progress bar to indeterminate after giving it a value you must remove the value attribute with [`element.removeAttribute('value')`](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute).
Examples
--------
```
<progress value="70" max="100">70 %</progress>
```
### Result
Accessibility Concerns
----------------------
### Labelling
In most cases you should provide an accessible label when using `<progress>`. While you can use the standard ARIA labelling attributes [`aria-labelledby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) as you would for any element with `role="progressbar"`, when using `<progress>` you can alternatively use the [`<label>`](label) element.
**Note:** Text placed between the element's tags is not an accessible label, it is only recommended as a fallback for old browsers that do not support this element.
#### Example
```
<label>Uploading Document: <progress value="70" max="100">70 %</progress></label>
<!-- OR -->
<label for="progress-bar">Uploading Document</label>
<progress id="progress-bar" value="70" max="100">70 %</progress>
```
### Describing a particular region
If the `<progress>` element is describing the loading progress of a section of a page, use [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) to point to the status, and set [`aria-busy="true"`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy) on the section that is being updated, removing the `aria-busy` attribute when it has finished loading.
#### Example
```
<div aria-busy="true" aria-describedby="progress-bar">
<!-- content is for this region is loading -->
</div>
<!-- ... -->
<progress id="progress-bar" aria-label="Content loading…"></progress>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-progress-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-progress-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `progress` | 6 | 12 | 6
["Before Firefox 14, the `<progress>` element was incorrectly classified as a form element, and therefore had a `form` attribute. This has been fixed.", "Firefox provides the `::-moz-progress-bar` pseudo-element, which lets you style the part of the interior of the progress bar representing the amount of work completed so far."] | 10 | 11 | 6 | Yes | Yes | 6
["Before Firefox 14, the `<progress>` element was incorrectly classified as a form element, and therefore had a `form` attribute. This has been fixed.", "Firefox provides the `::-moz-progress-bar` pseudo-element, which lets you style the part of the interior of the progress bar representing the amount of work completed so far."] | 11 | 7
Safari on iOS does not support indeterminate progress bars (they are rendered like 0%-completed progress bars). | Yes |
| `max` | 6 | 12 | 6 | 10 | 11 | 6 | Yes | Yes | 6 | 11 | 7 | Yes |
| `value` | 6 | 12 | 6 | 10 | 11 | 6 | Yes | Yes | 6 | 11 | 7 | Yes |
See also
--------
* [`<meter>`](meter)
* [`:indeterminate`](https://developer.mozilla.org/en-US/docs/Web/CSS/:indeterminate)
* [`-moz-orient`](https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-orient)
* [`::-moz-progress-bar`](https://developer.mozilla.org/en-US/docs/Web/CSS/::-moz-progress-bar)
* [`::-webkit-progress-bar`](https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-progress-bar)
* [`::-webkit-progress-value`](https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-progress-value)
* [`::-webkit-progress-inner-element`](https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-progress-inner-element)
html <textarea>: The Textarea element <textarea>: The Textarea element
================================
The `<textarea>` [HTML](../index) element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form.
Try it
------
The above example demonstrates a number of features of `<textarea>`:
* An `id` attribute to allow the `<textarea>` to be associated with a [`<label>`](label) element for accessibility purposes
* A `name` attribute to set the name of the associated data point submitted to the server when the form is submitted.
* `rows` and `cols` attributes to allow you to specify an exact size for the `<textarea>` to take. Setting these is a good idea for consistency, as browser defaults can differ.
* Default content entered between the opening and closing tags. `<textarea>` does not support the `value` attribute.
The `<textarea>` element also accepts several attributes common to form `<input>`s, such as `autocomplete`, `autofocus`, `disabled`, `placeholder`, `readonly`, and `required`.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`autocomplete`**](#attr-autocomplete) This attribute indicates whether the value of the control can be automatically completed by the browser. Possible values are:
* `off`: The user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically complete the entry.
* `on`: The browser can automatically complete the value based on values that the user has entered during previous uses.
If the `autocomplete` attribute is not specified on a `<textarea>` element, then the browser uses the `autocomplete` attribute value of the `<textarea>` element's form owner. The form owner is either the [`<form>`](form) element that this `<textarea>` element is a descendant of or the form element whose `id` is specified by the `form` attribute of the input element. For more information, see the [`autocomplete`](form#attr-autocomplete) attribute in [`<form>`](form).
[**`autocorrect`**](#attr-autocorrect) Non-standard
A string which indicates whether to activate automatic spelling correction and processing of text substitutions (if any are configured) while the user is editing this `textarea`. Permitted values are:
`on` Enable automatic spelling correction and text substitutions.
`off` Disable automatic spelling correction and text substitutions.
[**`autofocus`**](#attr-autofocus) This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form-associated element in a document can have this attribute specified.
[**`cols`**](#attr-cols) The visible width of the text control, in average character widths. If it is specified, it must be a positive integer. If it is not specified, the default value is `20`.
[**`disabled`**](#attr-disabled) This Boolean attribute indicates that the user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example [`<fieldset>`](fieldset); if there is no containing element when the `disabled` attribute is set, the control is enabled.
[**`form`**](#attr-form) The form element that the `<textarea>` element is associated with (its "form owner"). The value of the attribute must be the `id` of a form element in the same document. If this attribute is not specified, the `<textarea>` element must be a descendant of a form element. This attribute enables you to place `<textarea>` elements anywhere within a document, not just as descendants of form elements.
[**`maxlength`**](#attr-maxlength) The maximum number of characters (UTF-16 code units) that the user can enter. If this value isn't specified, the user can enter an unlimited number of characters.
[**`minlength`**](#attr-minlength) The minimum number of characters (UTF-16 code units) required that the user should enter.
[**`name`**](#attr-name) The name of the control.
[**`placeholder`**](#attr-placeholder) A hint to the user of what can be entered in the control. Carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint.
**Note:** Placeholders should only be used to show an example of the type of data that should be entered into a form; they are *not* a substitute for a proper [`<label>`](label) element tied to the input. See [Labels and placeholders](input#labels_and_placeholders) in [<input>: The Input (Form Input) element](input) for a full explanation.
[**`readonly`**](#attr-readonly) This Boolean attribute indicates that the user cannot modify the value of the control. Unlike the `disabled` attribute, the `readonly` attribute does not prevent the user from clicking or selecting in the control. The value of a read-only control is still submitted with the form.
[**`required`**](#attr-required) This attribute specifies that the user must fill in a value before submitting a form.
[**`rows`**](#attr-rows) The number of visible text lines for the control. If it is specified, it must be a positive integer. If it is not specified, the default value is 2.
[**`spellcheck`**](#attr-spellcheck) Specifies whether the `<textarea>` is subject to spell checking by the underlying browser/OS. The value can be:
* `true`: Indicates that the element needs to have its spelling and grammar checked.
* `default` : Indicates that the element is to act according to a default behavior, possibly based on the parent element's own `spellcheck` value.
* `false` : Indicates that the element should not be spell checked.
[**`wrap`**](#attr-wrap) Indicates how the control should wrap the value for form submission. Possible values are:
* `hard`: The browser automatically inserts line breaks (CR+LF) so that each line is no longer than the width of the control; the [`cols`](#attr-cols) attribute must be specified for this to take effect
* `soft`: The browser ensures that all line breaks in the entered value are a `CR+LF` pair, but no additional line breaks are added to the value.
* `off` Non-standard : Like `soft` but changes appearance to `white-space: pre` so line segments exceeding `cols` are not wrapped and the `<textarea>` becomes horizontally scrollable.
If this attribute is not specified, `soft` is its default value.
Styling with CSS
----------------
`<textarea>` is a [replaced element](https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element) — it has intrinsic dimensions, like a raster image. By default, its [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) value is `inline-block`. Compared to other form elements it is relatively easy to style, with its box model, fonts, color scheme, etc. being easily manipulable using regular CSS.
[Styling HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms/Styling_web_forms) provides some useful tips on styling `<textarea>`s.
### Baseline inconsistency
The HTML specification doesn't define where the baseline of a `<textarea>` is, so different browsers set it to different positions. For Gecko, the `<textarea>` baseline is set on the baseline of the first line of the textarea, on another browser it may be set on the bottom of the `<textarea>` box. Don't use [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align)`: baseline` on it; the behavior is unpredictable.
### Controlling whether a textarea is resizable
In most browsers, `<textarea>`s are resizable — you'll notice the drag handle in the right-hand corner, which can be used to alter the size of the element on the page. This is controlled by the [`resize`](https://developer.mozilla.org/en-US/docs/Web/CSS/resize) CSS property — resizing is enabled by default, but you can explicitly disable it using a `resize` value of `none`:
```
textarea {
resize: none;
}
```
### Styling valid and invalid values
Valid and invalid values of a `<textarea>` element (e.g. those within, and outside the bounds set by `minlength`, `maxlength`, or `required`) can be highlighted using the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) pseudo-classes. For example, to give your textarea a different border depending on whether it is valid or invalid:
```
textarea:invalid {
border: 2px dashed red;
}
textarea:valid {
border: 2px solid lime;
}
```
Examples
--------
### Basic example
The following example shows a very simple textarea, with a set numbers of rows and columns and some default content.
```
<textarea name="textarea" rows="10" cols="50">Write something here</textarea>
```
### Example using "minlength" and "maxlength"
This example has a minimum and maximum number of characters — of 10 and 20 respectively. Try it and see.
```
<textarea name="textarea" rows="5" cols="30" minlength="10" maxlength="20">
Write something here…
</textarea>
```
Note that `minlength` doesn't stop the user from removing characters so that the number entered goes past the minimum, but it does make the value entered into the `<textarea>` invalid. Also note that even if you have a `minlength` value set (3, for example), an empty `<textarea>` is still considered valid unless you also have the `required` attribute set.
### Example using "placeholder"
This example has a placeholder set. Notice how it disappears when you start typing into the box.
```
<textarea
name="textarea"
rows="5"
cols="30"
placeholder="Comment text."></textarea>
```
**Note:** Placeholders should only be used to show an example of the type of data that should be entered into a form; they are *not* a substitute for a proper [`<label>`](label) element tied to the input. See [Labels and placeholders](input#labels_and_placeholders) in [<input>: The Input (Form Input) element](input) for a full explanation.
### Disabled and readonly
This example shows two `<textarea>`s — one of which is `disabled`, and one of which is `readonly`. Have a play with both and you'll see the difference in behavior — the `disabled` element is not selectable in any way (and its value is not submitted), whereas the `readonly` element is selectable and its contents copyable (and its value is submitted); you just can't edit the contents.
**Note:** In browsers other than Firefox, such as chrome, the `disabled` textarea content may be selectable and copyable.
```
<textarea name="textarea" rows="5" cols="30" disabled>
I am a disabled textarea.
</textarea>
<textarea name="textarea" rows="5" cols="30" readonly>
I am a read-only textarea.
</textarea>
```
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [Interactive content](../content_categories#interactive_content), [listed](../content_categories#form_listed), [labelable](../content_categories#form_labelable), [resettable](../content_categories#form_resettable), and [submittable](../content_categories#form_submittable) [form-associated](../content_categories#form-associated_) element. |
| Permitted content | Text |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | `[textbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLTextAreaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-textarea-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-textarea-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `textarea` | Yes | 12 | Yes
["Before Firefox 6, when a `<textarea>` was focused, the insertion point was placed at the end of the text by default. Other major browsers place the insertion point at the beginning of the text.", "A default background-image gradient is applied to all `<textarea>` elements, which can be disabled using `background-image: none`.", "Before Firefox 89, manipulating the content of `<textarea>` elements using `Document.execCommand()` commands requires workarounds (see [bug 1220696](https://bugzil.la/1220696))."] | Yes | Yes | Yes | Yes | Yes | Yes
["Before Firefox 6, when a `<textarea>` was focused, the insertion point was placed at the end of the text by default. Other major browsers place the insertion point at the beginning of the text.", "A default background-image gradient is applied to all `<textarea>` elements, which can be disabled using `background-image: none`.", "Before Firefox 89, manipulating the content of `<textarea>` elements using `Document.execCommand()` commands requires workarounds (see [bug 1220696](https://bugzil.la/1220696))."] | Yes | Yes
Unlike other major browsers, a default style of `opacity: 0.4` is applied to disabled `<textarea>` elements. | Yes |
| `autocomplete` | 66 | No
See [issue 758078](https://crbug.com/758078). | 59 | No | No | Yes
See [bug 150731](https://webkit.org/b/150731). | 66 | 66 | 59 | No | No | 9.0 |
| `cols` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `dirname` | 17 | 79 | No | No | ≤12.1 | 6 | ≤37 | 18 | No | ≤12.1 | 6 | 1.0 |
| `disabled` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `form` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `maxlength` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `minlength` | 40 | 17 | 51 | No | 27 | 10.1 | 40 | 40 | 51 | 27 | 10.3 | 4.0 |
| `name` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `placeholder` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `readonly` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `required` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `rows` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `spellcheck` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `wrap` | 16 | 12 | 4 | ≤6 | ≤12.1 | 6 | ≤37 | 18 | 4 | ≤12.1 | 6 | 1.0 |
See also
--------
Other form-related elements:
* [`<form>`](form)
* [`<button>`](button)
* [`<datalist>`](datalist)
* [`<legend>`](legend)
* [`<label>`](label)
* [`<select>`](select)
* [`<optgroup>`](optgroup)
* [`<option>`](option)
* [`<input>`](input)
* [`<keygen>`](keygen)
* [`<fieldset>`](fieldset)
* [`<output>`](output)
* [`<progress>`](progress)
* [`<meter>`](meter)
| programming_docs |
html <body>: The Document Body element <body>: The Document Body element
=================================
The `<body>` [HTML](../index) element represents the content of an HTML document. There can be only one `<body>` element in a document.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Sectioning root](heading_elements#sectioning_roots). |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | The start tag may be omitted if the first thing inside it is not a space character, comment, [`<script>`](script) element or [`<style>`](style) element. The end tag may be omitted if the `<body>` element has contents or has a start tag, and is not immediately followed by a comment. |
| Permitted parents | It must be the second element of an [`<html>`](html) element. |
| Implicit ARIA role | `[generic](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/generic_role)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLBodyElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement)* The `<body>` element exposes the [`HTMLBodyElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement) interface.
* You can access the `<body>` element through the [`document.body`](https://developer.mozilla.org/en-US/docs/Web/API/Document/body) property.
|
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`alink`**](#attr-alink) Deprecated
Color of text for hyperlinks when selected. **Do not use this attribute! Use the CSS [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) property in conjunction with the [`:active`](https://developer.mozilla.org/en-US/docs/Web/CSS/:active) pseudo-class instead.**
[**`background`**](#attr-background) Deprecated
URI of an image to use as a background. **Do not use this attribute! Use the CSS [`background`](https://developer.mozilla.org/en-US/docs/Web/CSS/background) property on the element instead.**
[**`bgcolor`**](#attr-bgcolor) Deprecated
Background color for the document. **Do not use this attribute! Use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property on the element instead.**
[**`bottommargin`**](#attr-bottommargin) Deprecated
The margin of the bottom of the body. **Do not use this attribute! Use the CSS [`margin-bottom`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom) property on the element instead.**
[**`leftmargin`**](#attr-leftmargin) Deprecated
The margin of the left of the body. **Do not use this attribute! Use the CSS [`margin-left`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left) property on the element instead.**
[**`link`**](#attr-link) Deprecated
Color of text for unvisited hypertext links. **Do not use this attribute! Use the CSS [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) property in conjunction with the [`:link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:link) pseudo-class instead.**
[**`onafterprint`**](#attr-onafterprint) Function to call after the user has printed the document.
[**`onbeforeprint`**](#attr-onbeforeprint) Function to call when the user requests printing of the document.
[**`onbeforeunload`**](#attr-onbeforeunload) Function to call when the document is about to be unloaded.
[**`onblur`**](#attr-onblur) Function to call when the document loses focus.
[**`onerror`**](#attr-onerror) Function to call when the document fails to load properly.
[**`onfocus`**](#attr-onfocus) Function to call when the document receives focus.
[**`onhashchange`**](#attr-onhashchange) Function to call when the fragment identifier part (starting with the hash (`'#'`) character) of the document's current address has changed.
[**`onlanguagechange`**](#attr-onlanguagechange) Function to call when the preferred languages changed.
[**`onload`**](#attr-onload) Function to call when the document has finished loading.
[**`onmessage`**](#attr-onmessage) Function to call when the document has received a message.
[**`onoffline`**](#attr-onoffline) Function to call when network communication has failed.
[**`ononline`**](#attr-ononline) Function to call when network communication has been restored.
[**`onpopstate`**](#attr-onpopstate) Function to call when the user has navigated session history.
[**`onredo`**](#attr-onredo) Function to call when the user has moved forward in undo transaction history.
[**`onresize`**](#attr-onresize) Function to call when the document has been resized.
[**`onstorage`**](#attr-onstorage) Function to call when the storage area has changed.
[**`onundo`**](#attr-onundo) Function to call when the user has moved backward in undo transaction history.
[**`onunload`**](#attr-onunload) Function to call when the document is going away.
[**`rightmargin`**](#attr-rightmargin) Deprecated
The margin of the right of the body. **Do not use this attribute! Use the CSS [`margin-right`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right) property on the element instead.**
[**`text`**](#attr-text) Deprecated
Foreground color of text. **Do not use this attribute! Use CSS [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) property on the element instead.**
[**`topmargin`**](#attr-topmargin) Deprecated
The margin of the top of the body. **Do not use this attribute! Use the CSS [`margin-top`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top) property on the element instead.**
[**`vlink`**](#attr-vlink) Deprecated
Color of text for visited hypertext links. **Do not use this attribute! Use the CSS [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) property in conjunction with the [`:visited`](https://developer.mozilla.org/en-US/docs/Web/CSS/:visited) pseudo-class instead.**
Example
-------
```
<html lang="en">
<head>
<title>Document title</title>
</head>
<body>
<p>This is a paragraph</p>
</body>
</html>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-body-element](https://html.spec.whatwg.org/multipage/sections.html#the-body-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `body` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | 18 | 4 | Yes | Yes | 1.0 |
| `alink` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | 18 | 4 | Yes | Yes | 1.0 |
| `background` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | 18 | 4 | Yes | Yes | 1.0 |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `bottommargin` | Yes | 79 | 35
Before Firefox 35, it was supported in Quirks Mode only. | No | Yes | No | Yes | Yes | 35
Before Firefox 35, it was supported in Quirks Mode only. | Yes | No | Yes |
| `leftmargin` | Yes | 79 | 35
Before Firefox 35, it was supported in Quirks Mode only. | No | Yes | No | Yes | Yes | 35
Before Firefox 35, it was supported in Quirks Mode only. | Yes | No | Yes |
| `link` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | 18 | 4 | Yes | Yes | 1.0 |
| `rightmargin` | Yes | 79 | 35
Before Firefox 35, it was supported in Quirks Mode only. | No | Yes | No | Yes | Yes | 35
Before Firefox 35, it was supported in Quirks Mode only. | Yes | No | Yes |
| `text` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | 18 | 4 | Yes | Yes | 1.0 |
| `topmargin` | Yes | 79 | 35
Before Firefox 35, it was supported in Quirks Mode only. | No | Yes | No | Yes | Yes | 35
Before Firefox 35, it was supported in Quirks Mode only. | Yes | No | Yes |
| `vlink` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | 18 | 4 | Yes | Yes | 1.0 |
See also
--------
* [`<html>`](html)
* [`<head>`](head)
html <h1>–<h6>: The HTML Section Heading elements <h1>–<h6>: The HTML Section Heading elements
============================================
The `<h1>` to `<h6>` [HTML](../index) elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), heading content, palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [heading](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/heading_role) |
| Permitted ARIA roles | `[tab](https://w3c.github.io/aria/#tab)`, `[presentation](https://w3c.github.io/aria/#presentation)` or `[none](https://w3c.github.io/aria/#none)` |
| DOM interface | [`HTMLHeadingElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement) |
Attributes
----------
These elements only include the [global attributes](../global_attributes).
Usage notes
-----------
* Heading information can be used by user agents to construct a table of contents for a document automatically.
* Do not use heading elements to resize text. Instead, use the [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS) [`font-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) property.
* Do not skip heading levels: always start from `<h1>`, followed by `<h2>` and so on.
### Avoid using multiple `<h1>` elements on one page
While using multiple `<h1>` elements on one page is allowed by the HTML standard (as long as they are not [nested](#nesting)), this is not considered a best practice. A page should generally have a single `<h1>` element that describes the content of the page (similar to the document's [`<title> element`](title)).
**Note:** Nesting multiple `<h1>` elements in nested [sectioning elements](../element#content_sectioning) was allowed in older versions of the HTML standard. However, this was never considered a best practice and is now non-conforming. Read more in [There Is No Document Outline Algorithm](https://adrianroselli.com/2016/08/there-is-no-document-outline-algorithm.html).
Prefer using only one `<h1>` per page and [nest headings](#nesting) without skipping levels.
Examples
--------
### All headings
The following code shows all the heading levels, in use.
```
<h1>Heading level 1</h1>
<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>
```
Here is the result of this code:
### Example page
The following code shows a few headings with some content under them.
```
<h1>Heading elements</h1>
<h2>Summary</h2>
<p>Some text here…</p>
<h2>Examples</h2>
<h3>Example 1</h3>
<p>Some text here…</p>
<h3>Example 2</h3>
<p>Some text here…</p>
<h2>See also</h2>
<p>Some text here…</p>
```
Here is the result of this code:
Accessibility concerns
----------------------
### Navigation
A common navigation technique for users of screen reading software is jumping from heading to quickly determine the content of the page. Because of this, it is important to not skip one or more heading levels. Doing so may create confusion, as the person navigating this way may be left wondering where the missing heading is.
#### Don't
```
<h1>Heading level 1</h1>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
```
#### Do
```
<h1>Heading level 1</h1>
<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
```
#### Nesting
Headings may be nested as subsections to reflect the organization of the content of the page. Most screen readers can also generate an ordered list of all the headings on a page, which can help a person quickly determine the hierarchy of the content:
1. `h1` Beetles
1. `h2` Etymology
2. `h2` Distribution and Diversity
3. `h2` Evolution
1. `h3` Late Paleozoic
2. `h3` Jurassic
3. `h3` Cretaceous
4. `h3` Cenozoic
4. `h2` External Morphology
1. `h3` Head
1. `h4` Mouthparts
2. `h3` Thorax
1. `h4` Prothorax
2. `h4` Pterothorax
3. `h3` Legs
4. `h3` Wings
5. `h3` Abdomen
When headings are nested, heading levels may be "skipped" when closing a subsection.
* [Headings • Page Structure • WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/page-structure/headings/)
* [MDN Understanding WCAG, Guideline 1.3 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.3_%E2%80%94_create_content_that_can_be_presented_in_different_ways)
* [Understanding Success Criterion 1.3.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/content-structure-separation-programmatic.html)
* [MDN Understanding WCAG, Guideline 2.4 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.4_%E2%80%94_navigable_provide_ways_to_help_users_navigate_find_content_and_determine_where_they_are)
* [Understanding Success Criterion 2.4.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-skip.html)
* [Understanding Success Criterion 2.4.6 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-descriptive.html)
* [Understanding Success Criterion 2.4.10 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-headings.html)
### Labeling section content
Another common navigation technique for users of screen reading software is to generate a list of [sectioning content](../element#content_sectioning) and use it to determine the page's layout.
Sectioning content can be labeled using a combination of the [`aria-labelledby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) and [`id`](../global_attributes#id) attributes, with the label concisely describing the purpose of the section. This technique is useful for situations where there is more than one sectioning element on the same page.
#### Example
```
<header>
<nav aria-labelledby="primary-navigation">
<h2 id="primary-navigation">Primary navigation</h2>
<!-- navigation items -->
</nav>
</header>
<!-- page content -->
<footer>
<nav aria-labelledby="footer-navigation">
<h2 id="footer-navigation">Footer navigation</h2>
<!-- navigation items -->
</nav>
</footer>
```
In this example, screen reading technology would announce that there are two [`<nav>`](nav) sections, one called "Primary navigation" and one called "Footer navigation". If labels were not provided, the person using screen reading software may have to investigate each `nav` element's contents to determine their purpose.
* [Using the aria-labelledby attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby)
* [Labeling Regions • Page Structure • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/page-structure/labels/#using-aria-labelledby)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-h1,-h2,-h3,-h4,-h5,-and-h6-elements](https://html.spec.whatwg.org/multipage/sections.html#the-h1,-h2,-h3,-h4,-h5,-and-h6-elements) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Heading_Elements` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<p>`](p)
* [`<div>`](div)
* [`<section>`](section)
html <iframe>: The Inline Frame element <iframe>: The Inline Frame element
==================================
The `<iframe>` [HTML](../index) element represents a nested [browsing context](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context), embedding another HTML page into the current one.
Try it
------
Each embedded browsing context has its own [session history](https://developer.mozilla.org/en-US/docs/Web/API/History) and [document](https://developer.mozilla.org/en-US/docs/Web/API/Document). The browsing context that embeds the others is called the *parent browsing context*. The *topmost* browsing context — the one with no parent — is usually the browser window, represented by the [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object.
**Warning:** Because each browsing context is a complete document environment, every `<iframe>` in a page requires increased memory and other computing resources. While theoretically you can use as many `<iframe>`s as you like, check for performance problems.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`allow`**](#attr-allow) Specifies a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) for the `<iframe>`. The policy defines what features are available to the `<iframe>` (for example, access to the microphone, camera, battery, web-share, etc.) based on the origin of the request.
**Note:** A Permissions Policy specified by the `allow` attribute implements a further restriction on top of the policy specified in the [`Permissions-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy) header. It doesn't replace it.
[**`allowfullscreen`**](#attr-allowfullscreen) Set to `true` if the `<iframe>` can activate fullscreen mode by calling the [`requestFullscreen()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) method.
**Note:** This attribute is considered a legacy attribute and redefined as `allow="fullscreen"`.
[**`allowpaymentrequest`**](#attr-allowpaymentrequest) Experimental
Set to `true` if a cross-origin `<iframe>` should be allowed to invoke the [Payment Request API](https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API).
**Note:** This attribute is considered a legacy attribute and redefined as `allow="payment"`.
[**`credentialless`**](#attr-credentialless) Experimental Non-standard
Set to `true` to make the `<iframe>` credentialless, meaning that its content will be loaded in a new, ephemeral context. It doesn't have access to the network, cookies, and storage data associated with its origin. It uses a new context local to the top-level document lifetime. In return, the [`Cross-Origin-Embedder-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not. See [IFrame credentialless](https://developer.mozilla.org/en-US/docs/Web/Security/IFrame_credentialless) for more details.
[**`csp`**](#attr-csp) Experimental
A [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) enforced for the embedded resource. See [`HTMLIFrameElement.csp`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/csp) for details.
[**`fetchpriority`**](#attr-fetchpriority) Experimental
Provides a hint of the relative priority to use when fetching the iframe document. Allowed values:
`high` Signals a high-priority fetch relative to other iframe documents.
`low` Signals a low-priority fetch relative to other iframe documents.
`auto` Default: Signals automatic determination of fetch priority relative to other iframe documents.
[**`height`**](#attr-height) The height of the frame in CSS pixels. Default is `150`.
[**`loading`**](#attr-loading) Experimental
Indicates how the browser should load the iframe:
* `eager`: Load the iframe immediately, regardless if it is outside the visible viewport (this is the default value).
* `lazy`: Defer loading of the iframe until it reaches a calculated distance from the viewport, as defined by the browser.
[**`name`**](#attr-name) A targetable name for the embedded browsing context. This can be used in the `target` attribute of the [`<a>`](a), [`<form>`](form), or [`<base>`](base) elements; the `formtarget` attribute of the [`<input>`](input) or [`<button>`](button) elements; or the `windowName` parameter in the [`window.open()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) method.
[**`referrerpolicy`**](#attr-referrerpolicy) Indicates which [referrer](https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer) to send when fetching the frame's resource:
* `no-referrer`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent.
* `no-referrer-when-downgrade`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent to [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)s without [TLS](https://developer.mozilla.org/en-US/docs/Glossary/TLS) ([HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS)).
* `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL), [host](https://developer.mozilla.org/en-US/docs/Glossary/Host), and [port](https://developer.mozilla.org/en-US/docs/Glossary/Port).
* `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
* `same-origin`: A referrer will be sent for [same origin](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy), but cross-origin requests will contain no referrer information.
* `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
* `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
* `unsafe-url`: The referrer will include the origin *and* the path (but not the [fragment](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins.
[**`sandbox`**](#attr-sandbox) Applies extra restrictions to the content in the frame. The value of the attribute can either be empty to apply all restrictions, or space-separated tokens to lift particular restrictions:
* `allow-downloads-without-user-activation` Experimental : Allows for downloads to occur without a gesture from the user.
* `allow-downloads`: Allows for downloads to occur with a gesture from the user.
* `allow-forms`: Allows the resource to submit forms. If this keyword is not used, form submission is blocked.
* `allow-modals`: Lets the resource [open modal windows](https://html.spec.whatwg.org/multipage/origin.html#sandboxed-modals-flag).
* `allow-orientation-lock`: Lets the resource [lock the screen orientation](https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation).
* `allow-pointer-lock`: Lets the resource use the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API).
* `allow-popups`: Allows popups (such as `window.open()`, `target="_blank"`, or `showModalDialog()`). If this keyword is not used, the popup will silently fail to open.
* `allow-popups-to-escape-sandbox`: Lets the sandboxed document open new windows without those windows inheriting the sandboxing. For example, this can safely sandbox an advertisement without forcing the same restrictions upon the page the ad links to.
* `allow-presentation`: Lets the resource start a [presentation session](https://developer.mozilla.org/en-US/docs/Web/API/PresentationRequest).
* `allow-same-origin`: If this token is not used, the resource is treated as being from a special origin that always fails the [same-origin policy](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy) (potentially preventing access to [data storage/cookies](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#cross-origin_data_storage_access) and some JavaScript APIs).
* `allow-scripts`: Lets the resource run scripts (but not create popup windows).
* `allow-storage-access-by-user-activation` Experimental : Lets the resource request access to the parent's storage capabilities with the [Storage Access API](https://developer.mozilla.org/en-US/docs/Web/API/Storage_Access_API).
* `allow-top-navigation`: Lets the resource navigate the top-level browsing context (the one named `_top`).
* `allow-top-navigation-by-user-activation`: Lets the resource navigate the top-level browsing context, but only if initiated by a user gesture.
**Note:**
* When the embedded document has the same origin as the embedding page, it is **strongly discouraged** to use both `allow-scripts` and `allow-same-origin`, as that lets the embedded document remove the `sandbox` attribute — making it no more secure than not using the `sandbox` attribute at all.
* Sandboxing is useless if the attacker can display content outside a sandboxed `iframe` — such as if the viewer opens the frame in a new tab. Such content should be also served from a *separate origin* to limit potential damage.
* The `sandbox` attribute is unsupported in Internet Explorer 9 and earlier.
[**`src`**](#attr-src) The URL of the page to embed. Use a value of `about:blank` to embed an empty page that conforms to the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#inherited_origins). Also note that programmatically removing an `<iframe>`'s src attribute (e.g. via [`Element.removeAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute)) causes `about:blank` to be loaded in the frame in Firefox (from version 65), Chromium-based browsers, and Safari/iOS.
[**`srcdoc`**](#attr-srcdoc) Inline HTML to embed, overriding the `src` attribute. If a browser does not support the `srcdoc` attribute, it will fall back to the URL in the `src` attribute.
[**`width`**](#attr-width) The width of the frame in CSS pixels. Default is `300`.
### Deprecated attributes
These attributes are deprecated and may no longer be supported by all user agents. You should not use them in new content, and try to remove them from existing content.
[**`align`**](#attr-align) Deprecated
The alignment of this element with respect to the surrounding context.
[**`frameborder`**](#attr-frameborder) Deprecated
The value `1` (the default) draws a border around this frame. The value `0` removes the border around this frame, but you should instead use the CSS property [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) to control `<iframe>` borders.
[**`longdesc`**](#attr-longdesc) Deprecated
A URL of a long description of the frame's content. Due to widespread misuse, this is not helpful for non-visual browsers.
[**`marginheight`**](#attr-marginheight) Deprecated
The amount of space in pixels between the frame's content and its top and bottom borders.
[**`marginwidth`**](#attr-marginwidth) Deprecated
The amount of space in pixels between the frame's content and its left and right borders.
[**`scrolling`**](#attr-scrolling) Deprecated
Indicates when the browser should provide a scrollbar for the frame:
* `auto`: Only when the frame's content is larger than its dimensions.
* `yes`: Always show a scrollbar.
* `no`: Never show a scrollbar.
Scripting
---------
Inline frames, like [`<frame>`](frame) elements, are included in the [`window.frames`](https://developer.mozilla.org/en-US/docs/Web/API/Window/frames) pseudo-array.
With the DOM [`HTMLIFrameElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement) object, scripts can access the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object of the framed resource via the [`contentWindow`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentWindow) property. The [`contentDocument`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentDocument) property refers to the `document` inside the `<iframe>`, same as `contentWindow.document`.
From the inside of a frame, a script can get a reference to its parent window with [`window.parent`](https://developer.mozilla.org/en-US/docs/Web/API/Window/parent).
Script access to a frame's content is subject to the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). Scripts cannot access most properties in other `window` objects if the script was loaded from a different origin, including scripts inside a frame accessing the frame's parent. Cross-origin communication can be achieved using [`Window.postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).
Positioning and scaling
-----------------------
As a [replaced element](https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element), the position, alignment, and scaling of the embedded document within the `<iframe>` element's box, can be adjusted with the [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) and [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) properties.
Examples
--------
### A simple <iframe>
This example embeds the page at <https://example.org> in an iframe.
#### HTML
```
<iframe
src="https://example.org"
title="iframe Example 1"
width="400"
height="300">
</iframe>
```
#### Result
Accessibility concerns
----------------------
People navigating with assistive technology such as a screen reader can use the [`title` attribute](../global_attributes/title) on an `<iframe>` to label its content. The title's value should concisely describe the embedded content:
```
<iframe
title="Wikipedia page for Avocados"
src="https://en.wikipedia.org/wiki/Avocado"></iframe>
```
Without this title, they have to navigate into the `<iframe>` to determine what its embedded content is. This context shift can be confusing and time-consuming, especially for pages with multiple `<iframe>`s and/or if embeds contain interactive content like video or audio.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), embedded content, interactive content, palpable content. |
| Permitted content | None. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts embedded content. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[application](https://w3c.github.io/aria/#application)`, `[document](https://w3c.github.io/aria/#document)`, `[img](https://w3c.github.io/aria/#img)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)` |
| DOM interface | [`HTMLIFrameElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-iframe-element](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-iframe-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `iframe` | 1 | 12 | Yes
The `resize` CSS property doesn't have any effect on this element due to [bug 680823](https://bugzil.la/680823). | Yes | Yes | Yes
Safari has a [bug](https://www.quirksmode.org/bugreports/archives/2005/02/hidden_iframes.html) that prevents iframes from loading if the `iframe` element was hidden when added to the page. `iframeElement.src = iframeElement.src` should cause it to load the iframe. | Yes | Yes | Yes
The `resize` CSS property doesn't have any effect on this element due to [bug 680823](https://bugzil.la/680823). | Yes | Yes
Safari has a [bug](https://www.quirksmode.org/bugreports/archives/2005/02/hidden_iframes.html) that prevents iframes from loading if the `iframe` element was hidden when added to the page. `iframeElement.src = iframeElement.src` should cause it to load the iframe. | Yes |
| `align` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `allow` | 60 | 79 | 74 | No | 47 | 11.1 | 60 | 60 | No | 44 | 11.3 | 8.0 |
| `allowfullscreen` | 27
17-38 | ≤79
12-79 | 18
9 | 11 | ≤15
15-25 | 7
Yes | 37
37-38 | 27
18-38 | 18
9 | ≤14
14-25 | 7
Yes | 1.5
1.0-3.0 |
| `allowpaymentrequest` | No | No | 56-83 | No | No | No | No | No | 56-83 | No | No | No |
| `credentialless` | 110 | 110 | No | No | No | No | 110 | 110 | No | No | No | No |
| `external_protocol_urls_blocked` | No | No | 67 | No | No | No | No | No | 67 | No | No | No |
| `fetchpriority` | No
See [bug 1345601](https://crbug.com/1345601). | No
See [bug 1345601](https://crbug.com/1345601). | No | No | No
See [bug 1345601](https://crbug.com/1345601). | No | No
See [bug 1345601](https://crbug.com/1345601). | No
See [bug 1345601](https://crbug.com/1345601). | No | No
See [bug 1345601](https://crbug.com/1345601). | No | No
See [bug 1345601](https://crbug.com/1345601). |
| `frameborder` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `height` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `loading` | 77 | 79 | No
See [bug 1622090](https://bugzil.la/1622090). | No | 64 | No
See [bug 196698](https://webkit.org/b/196698). | 77 | 77 | No
See [bug 1622090](https://bugzil.la/1622090). | 55 | No
See [bug 196698](https://webkit.org/b/196698). | 12.0 |
| `longdesc` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `marginheight` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `marginwidth` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `name` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `referrerpolicy` | 51 | 79 | 50 | No | 38 | 13 | 51 | 51 | 50 | 41 | 13 | 7.2 |
| `sandbox` | 4 | 12 | 17 | 10 | 15 | 5 | Yes | Yes | 17 | No | 4.2 | Yes |
| `sandbox-allow-downloads` | 83 | 83 | 82 | No | No | No | 83 | 83 | 82 | No | No | 13.0 |
| `sandbox-allow-modals` | 46 | 79 | 49 | No | 33 | No | 46 | 46 | 49 | 33 | No | 5.0 |
| `sandbox-allow-popups` | Yes | ≤18 | 28 | No | Yes | No | Yes | Yes | 27 | No | No | Yes |
| `sandbox-allow-popups-to-escape-sandbox` | 46 | 79 | 49 | No | 32 | No | 46 | 46 | 49 | 32 | No | 5.0 |
| `sandbox-allow-presentation` | 53 | 79 | 50 | No | 40 | No | No | 53 | 50 | 41 | No | 6.0 |
| `sandbox-allow-same-origin` | Yes
Chrome 70 and earlier block script execution without `allow-scripts`, even if `allow-same-origin` is set. For example, any bound handlers for click events of nodes inside an iframe throw an error for blocked script execution. | Yes | Yes | Yes | Yes | Yes
Safari blocks script execution without `allow-scripts` even if `allow-same-origin` is set. For example, any bound handlers for click events of nodes inside an iframe throw an error for blocked script execution. | Yes | Yes | Yes | Yes | Yes | Yes |
| `sandbox-allow-storage-access-by-user-activation` | No | No | 65 | No | No | 11.1 | No | No | No | No | 11.3 | No |
| `sandbox-allow-top-navigation-by-user-activation` | 58 | 79 | 79 | No | 45 | 11.1
Not initially available in 11.1, but added in sub-version 13605.1.33.1.2. | 58 | 58 | 79 | 43 | No | 7.0 |
| `scrolling` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `src` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `srcdoc` | 20 | 79 | 25 | No | 15 | 6 | 37 | 25 | 25 | No | No | 1.5 |
| `width` | 1 | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* [Privacy, permissions, and information security](https://developer.mozilla.org/en-US/docs/Web/Privacy)
| programming_docs |
html <article>: The Article Contents element <article>: The Article Contents element
=======================================
The `<article>` [HTML](../index) element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include: a forum post, a magazine or newspaper article, or a blog entry, a product card, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
Try it
------
A given document can have multiple articles in it; for example, on a blog that shows the text of each article one after another as the reader scrolls, each post would be contained in an `<article>` element, possibly with one or more `<section>`s within.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [sectioning content](../content_categories#sectioning_content), [palpable content](../content_categories#palpable_content) |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). Note that an `<article>` element must not be a descendant of an [`<address>`](address) element. |
| Implicit ARIA role | `[article](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/article_role)` |
| Permitted ARIA roles | `[application](https://w3c.github.io/aria/#application)`, `[document](https://w3c.github.io/aria/#document)`, `[feed](https://w3c.github.io/aria/#feed)`, `[main](https://w3c.github.io/aria/#main)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[region](https://w3c.github.io/aria/#region)` |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Each `<article>` should be identified, typically by including a heading ([`<h1>` - `<h6>`](heading_elements) element) as a child of the `<article>` element.
* When an `<article>` element is nested, the inner element represents an article related to the outer element. For example, the comments of a blog post can be `<article>` elements nested in the `<article>` representing the blog post.
* Author information of an `<article>` element can be provided through the [`<address>`](address) element, but it doesn't apply to nested `<article>` elements.
* The publication date and time of an `<article>` element can be described using the [`datetime`](time#attr-datetime) attribute of a [`<time>`](time) element.
Examples
--------
```
<article class="film\_review">
<h2>Jurassic Park</h2>
<section class="main\_review">
<h3>Review</h3>
<p>Dinos were great!</p>
</section>
<section class="user\_reviews">
<h3>User reviews</h3>
<article class="user\_review">
<h4>Too scary!</h4>
<p>Way too scary for me.</p>
<footer>
<p>
Posted on
<time datetime="2015-05-16 19:00">May 16</time>
by Lisa.
</p>
</footer>
</article>
<article class="user\_review">
<h4>Love the dinos!</h4>
<p>I agree, dinos are my favorite.</p>
<footer>
<p>
Posted on
<time datetime="2015-05-17 19:00">May 17</time>
by Tom.
</p>
</footer>
</article>
</section>
<footer>
<p>
Posted on
<time datetime="2015-05-15 19:00">May 15</time>
by Staff.
</p>
</footer>
</article>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-article-element](https://html.spec.whatwg.org/multipage/sections.html#the-article-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `article` | 5 | 12 | 4 | 9 | 11.1 | 5 | Yes | Yes | 4 | 11.1 | 4.2 | Yes |
See also
--------
* Other section-related elements: [`<body>`](body), [`<nav>`](nav), [`<section>`](section), [`<aside>`](aside), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<hgroup>`](hgroup), [`<header>`](header), [`<footer>`](footer), [`<address>`](address)
* [Using HTML sections and outlines](heading_elements)
html <q>: The Inline Quotation element <q>: The Inline Quotation element
=================================
The `<q>` [HTML](../index) element indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the [`<blockquote>`](blockquote) element.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`cite`**](#attr-cite) The value of this attribute is a URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote.
Example
-------
```
<p>
According to Mozilla's website,
<q cite="https://www.mozilla.org/en-US/about/history/details/">Firefox 1.0 was released in 2004 and became a big success.</q>
</p>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLQuoteElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLQuoteElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-q-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-q-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `q` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The [`<blockquote>`](blockquote) element for long quotations.
* The [`<cite>`](cite) element for source citations.
html <optgroup>: The Option Group element <optgroup>: The Option Group element
====================================
The `<optgroup>` [HTML](../index) element creates a grouping of options within a [`<select>`](select) element.
Try it
------
**Note:** Optgroup elements may not be nested.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`disabled`**](#attr-disabled) If this Boolean attribute is set, none of the items in this option group is selectable. Often browsers grey out such control and it won't receive any browsing events, like mouse clicks or focus-related ones.
[**`label`**](#attr-label) The name of the group of options, which the browser can use when labeling the options in the user interface. This attribute is mandatory if this element is used.
Examples
--------
```
<select>
<optgroup label="Group 1">
<option>Option 1.1</option>
</optgroup>
<optgroup label="Group 2">
<option>Option 2.1</option>
<option>Option 2.2</option>
</optgroup>
<optgroup label="Group 3" disabled>
<option>Option 3.1</option>
<option>Option 3.2</option>
<option>Option 3.3</option>
</optgroup>
</select>
```
### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | Zero or more [`<option>`](option) elements. |
| Tag omission | The start tag is mandatory. The end tag is optional if this element is immediately followed by another `<optgroup>` element, or if the parent element has no more content. |
| Permitted parents | A [`<select>`](select) element. |
| Implicit ARIA role | `[group](https://w3c.github.io/aria/#group)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLOptGroupElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptGroupElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-optgroup-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-optgroup-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `optgroup` | 1 | 12 | 1 | 5.5 | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `disabled` | 1 | 12 | 1 | 8 | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `label` | 1 | 12 | 1 | 5.5 | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Other form-related elements: [`<form>`](form), [`<legend>`](legend), [`<label>`](label), [`<button>`](button), [`<select>`](select), [`<datalist>`](datalist), [`<option>`](option), [`<fieldset>`](fieldset), [`<textarea>`](textarea), [`<keygen>`](keygen), [`<input>`](input), [`<output>`](output), [`<progress>`](progress) and [`<meter>`](meter).
html <option>: The HTML Option element <option>: The HTML Option element
=================================
The `<option>` [HTML](../index) element is used to define an item contained in a [`<select>`](select), an [`<optgroup>`](optgroup), or a [`<datalist>`](datalist) element. As such, `<option>` can represent menu items in popups and other lists of items in an HTML document.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`disabled`**](#attr-disabled) If this Boolean attribute is set, this option is not checkable. Often browsers grey out such control and it won't receive any browsing event, like mouse clicks or focus-related ones. If this attribute is not set, the element can still be disabled if one of its ancestors is a disabled [`<optgroup>`](optgroup) element.
[**`label`**](#attr-label) This attribute is text for the label indicating the meaning of the option. If the `label` attribute isn't defined, its value is that of the element text content.
[**`selected`**](#attr-selected) If present, this Boolean attribute indicates that the option is initially selected. If the `<option>` element is the descendant of a [`<select>`](select) element whose [`multiple`](select#attr-multiple) attribute is not set, only one single `<option>` of this [`<select>`](select) element may have the `selected` attribute.
[**`value`**](#attr-value) The content of this attribute represents the value to be submitted with the form, should this option be selected. If this attribute is omitted, the value is taken from the text content of the option element.
Styling with CSS
----------------
Styling the `<option>` element is highly limited. Options don't inherit the font set on the parent. In Firefox, only [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) and [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) can be set however in Chrome or Safari it's not possible to set any properties. You can find more details about styling in [our guide to advanced form styling](https://developer.mozilla.org/en-US/docs/Learn/Forms/Advanced_form_styling).
Examples
--------
See [`<select>`](select) for examples.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | Text, possibly with escaped characters (like `é`). |
| Tag omission | The start tag is mandatory. The end tag is optional if this element is immediately followed by another `<option>` element or an [`<optgroup>`](optgroup), or if the parent element has no more content. |
| Permitted parents | A [`<select>`](select), an [`<optgroup>`](optgroup) or a [`<datalist>`](datalist) element. |
| Implicit ARIA role | `[option](https://w3c.github.io/aria/#option)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLOptionElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-option-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-option-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `option` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `disabled` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `label` | 1 | 12 | 1
["Before 77, Firefox didn't display the value of the `label` attribute as option text if element's content was empty. See [bug 40545](https://bugzil.la/40545).", "Historically, Firefox has allowed keyboard and mouse events to bubble up from the `<option>` element to the parent `<select>` element, although this behavior is inconsistent across many browsers. For better Web compatibility (and for technical reasons), they will not bubble up when Firefox is in multi-process mode and the `<select>` element is displayed as a drop-down list. The behavior is unchanged if the `<select>` is presented inline and it has either the `multiple` attribute defined or a `size` attribute set to more than `1`. Rather than watching `<option>` elements for events, you should watch for [change](https://developer.mozilla.org/docs/Web/Events/change) events on `<select>`. See [bug 1090602](https://bugzil.la/1090602) for details.", "When Mozilla introduced dedicated content threads to Firefox (through the Electrolysis, or e10s, project), support for styling `<option>` elements was removed temporarily. Starting in Firefox 54, you can apply foreground and background colors to `<option>` elements again, using the `color` and `background-color` CSS properties. See [bug 910022](https://bugzil.la/910022) for more information. Note that this is still disabled in Linux due to lack of contrast (see [bug 1338283](https://bugzil.la/1338283) for progress on this)."] | Yes | Yes | Yes | Yes | Yes | 4
Before 77, Firefox didn't display the value of the `label` attribute as option text if element's content was empty. See [bug 40545](https://bugzil.la/40545). | Yes | Yes | Yes |
| `selected` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `value` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Other form-related elements: [`<form>`](form), [`<legend>`](legend), [`<label>`](label), [`<button>`](button), [`<select>`](select), [`<datalist>`](datalist), [`<optgroup>`](optgroup), [`<fieldset>`](fieldset), [`<textarea>`](textarea), [`<keygen>`](keygen), [`<input>`](input), [`<output>`](output), [`<progress>`](progress) and [`<meter>`](meter).
html <noscript>: The Noscript element <noscript>: The Noscript element
================================
The `<noscript>` [HTML](../index) element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Metadata content](../content_categories#metadata_content), [flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content). |
| Permitted content | When scripting is disabled and when it is a descendant of the [`<head>`](head) element: in any order, zero or more [`<link>`](link) elements, zero or more [`<style>`](style) elements, and zero or more [`<meta>`](meta) elements.When scripting is disabled and when it isn't a descendant of the [`<head>`](head) element: any [transparent content](../content_categories#transparent_content_model), but no `<noscript>` element must be among its descendants.Otherwise: flow content or phrasing content. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content), if there are no ancestor `<noscript>` element, or in a [`<head>`](head) element (but only for an HTML document), here again if there are no ancestor `<noscript>` element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
```
<noscript>
<!-- anchor linking to external file -->
<a href="https://www.mozilla.org/">External Link</a>
</noscript>
<p>Rocks!</p>
```
### Result with scripting enabled
Rocks!
### Result with scripting disabled
[External Link](https://www.mozilla.org/)
Rocks!
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-noscript-element](https://html.spec.whatwg.org/multipage/scripting.html#the-noscript-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `noscript` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
html <br>: The Line Break element <br>: The Line Break element
============================
The `<br>` [HTML](../index) element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.
Try it
------
As you can see from the above example, a `<br>` element is included at each point where we want the text to break. The text after the `<br>` begins again at the start of the next line of the text block.
**Note:** Do not use `<br>` to create margins between paragraphs; wrap them in [`<p>`](p) elements and use the [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) property to control their size.
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
### Deprecated attributes
[**`clear`**](#attr-clear) Deprecated
Indicates where to begin the next line after the break.
Styling with CSS
----------------
The `<br>` element has a single, well-defined purpose — to create a line break in a block of text. As such, it has no dimensions or visual output of its own, and there is very little you can do to style it.
You can set a [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) on `<br>` elements themselves to increase the spacing between the lines of text in the block, but this is a bad practice — you should use the [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) property that was designed for that purpose.
Examples
--------
### Simple br
In the following example we use `<br>` elements to create line breaks between the different lines of a postal address:
```
Mozilla<br />
331 E. Evelyn Avenue<br />
Mountain View, CA<br />
94041<br />
USA<br />
```
The result looks like so:
Accessibility concerns
----------------------
Creating separate paragraphs of text using `<br>` is not only bad practice, it is problematic for people who navigate with the aid of screen reading technology. Screen readers may announce the presence of the element, but not any content contained within `<br>`s. This can be a confusing and frustrating experience for the person using the screen reader.
Use `<p>` elements, and use CSS properties like [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) to control their spacing.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content). |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | Must have a start tag, and must not have an end tag. In XHTML documents, write this element as `<br />`. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)` |
| DOM interface | [`HTMLBRElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBRElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-br-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-br-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `br` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `clear` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<address>`](address) element
* [`<p>`](p) element
* [`<wbr>`](wbr) element
| programming_docs |
html <table>: The Table element <table>: The Table element
==========================
The `<table>` [HTML](../index) element represents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content) |
| Permitted content | In this order: 1. an optional [`<caption>`](caption) element,
2. zero or more [`<colgroup>`](colgroup) elements,
3. an optional [`<thead>`](thead) element,
4. either one of the following:
* zero or more [`<tbody>`](tbody) elements
* one or more [`<tr>`](tr) elements
5. an optional [`<tfoot>`](tfoot) element
|
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts flow content |
| Implicit ARIA role | `[table](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/table_role)` |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLTableElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
### Deprecated attributes
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute indicates how the table must be aligned inside the containing document. It may have the following values:
* `left`: the table is displayed on the left side of the document;
* `center`: the table is displayed in the center of the document;
* `right`: the table is displayed on the right side of the document.
Set [`margin-left`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left) and [`margin-right`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right) to `auto` or [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) to `0 auto` to achieve an effect that is similar to the align attribute.
[**`bgcolor`**](#attr-bgcolor) Deprecated
The background color of the table. It is a [6-digit hexadecimal RGB code](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors), prefixed by a '`#`'. One of the predefined [color keywords](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) can also be used.
To achieve a similar effect, use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property.
[**`border`**](#attr-border) Deprecated
This integer attribute defines, in pixels, the size of the frame surrounding the table. If set to 0, the [`frame`](table#attr-frame) attribute is set to void.
To achieve a similar effect, use the CSS [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) shorthand property.
[**`cellpadding`**](#attr-cellpadding) Deprecated
This attribute defines the space between the content of a cell and its border, displayed or not. If the cellpadding's length is defined in pixels, this pixel-sized space will be applied to all four sides of the cell's content. If the length is defined using a percentage value, the content will be centered and the total vertical space (top and bottom) will represent this value. The same is true for the total horizontal space (left and right).
To achieve a similar effect, apply the [`border-collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) property to the `<table>` element, with its value set to collapse, and the [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) property to the [`<td>`](td) elements.
[**`cellspacing`**](#attr-cellspacing) Deprecated
This attribute defines the size of the space between two cells in a percentage value or pixels. The attribute is applied both horizontally and vertically, to the space between the top of the table and the cells of the first row, the left of the table and the first column, the right of the table and the last column and the bottom of the table and the last row.
To achieve a similar effect, apply the [`border-spacing`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing) property to the `<table>` element. `border-spacing` does not have any effect if [`border-collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) is set to collapse.
[**`frame`**](#attr-frame) Deprecated
This enumerated attribute defines which side of the frame surrounding the table must be displayed.
To achieve a similar effect, use the [`border-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-style) and [`border-width`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-width) properties.
[**`rules`**](#attr-rules) Deprecated
This enumerated attribute defines where rules, i.e. lines, should appear in a table. It can have the following values:
* `none`, which indicates that no rules will be displayed; it is the default value;
* `groups`, which will cause the rules to be displayed between row groups (defined by the [`<thead>`](thead), [`<tbody>`](tbody) and [`<tfoot>`](tfoot) elements) and between column groups (defined by the [`<col>`](col) and [`<colgroup>`](colgroup) elements) only;
* `rows`, which will cause the rules to be displayed between rows;
* `columns`, which will cause the rules to be displayed between columns;
* `all`, which will cause the rules to be displayed between rows and columns.
To achieve a similar effect, apply the [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) property to the appropriate [`<thead>`](thead), [`<tbody>`](tbody), [`<tfoot>`](tfoot), [`<col>`](col), or [`<colgroup>`](colgroup) elements.
[**`summary`**](#attr-summary) Deprecated
This attribute defines an alternative text that summarizes the content of the table. Use the [`<caption>`](caption) element instead.
[**`width`**](#attr-width) Deprecated
This attribute defines the width of the table. Use the CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property instead.
Examples
--------
### Simple table
```
<table>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</table>
```
### Further simple examples
```
<p>Simple table with header</p>
<table>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</table>
<p>Table with thead, tfoot, and tbody</p>
<table>
<thead>
<tr>
<th>Header content 1</th>
<th>Header content 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Body content 1</td>
<td>Body content 2</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer content 1</td>
<td>Footer content 2</td>
</tr>
</tfoot>
</table>
<p>Table with colgroup</p>
<table>
<colgroup span="4"></colgroup>
<tr>
<th>Countries</th>
<th>Capitals</th>
<th>Population</th>
<th>Language</th>
</tr>
<tr>
<td>USA</td>
<td>Washington, D.C.</td>
<td>309 million</td>
<td>English</td>
</tr>
<tr>
<td>Sweden</td>
<td>Stockholm</td>
<td>9 million</td>
<td>Swedish</td>
</tr>
</table>
<p>Table with colgroup and col</p>
<table>
<colgroup>
<col style="background-color: #0f0" />
<col span="2" />
</colgroup>
<tr>
<th>Lime</th>
<th>Lemon</th>
<th>Orange</th>
</tr>
<tr>
<td>Green</td>
<td>Yellow</td>
<td>Orange</td>
</tr>
</table>
<p>Simple table with caption</p>
<table>
<caption>
Awesome caption
</caption>
<tr>
<td>Awesome data</td>
</tr>
</table>
```
### Table sorting
#### Sorting table rows
There are no native methods for sorting the rows ([`<tr>`](tr) elements) of an HTML table. But using [`Array.prototype.slice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice), [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), [`Node.removeChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild), and [`Node.appendChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild), you can implement your own `sort()` function to sort an [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) of `<tr>` elements.
In the below example, you can see such an example. We are attaching it to the <tbody> element so that it sorts the table cells in order of increasing value, and updates the display to suit.
##### HTML
```
<table>
<tbody>
<tr>
<td>3</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>1</td>
</tr>
</tbody>
</table>
```
##### JavaScript
```
HTMLTableSectionElement.prototype.sort = function (cb) {
Array.from(this.rows)
.sort(cb)
.forEach((e) => this.appendChild(this.removeChild(e)));
};
document
.querySelector("table")
.tBodies[0].sort((a, b) => a.textContent.localeCompare(b.textContent));
```
##### Result
#### Sorting rows with a click on the th element
The following example adds an event handler to every `<th>` element of every `<table>` in the `document`; it sorts all the `<tbody>`'s rows, basing the sorting on the `td` cells contained in the rows.
**Note:** This solution assumes that the `<td>` elements are populated by raw text with no descendant elements.
##### HTML
```
<table>
<thead>
<tr>
<th>Numbers</th>
<th>Letters</th>
</tr>
</thead>
<tbody>
<tr>
<td>3</td>
<td>A</td>
</tr>
<tr>
<td>2</td>
<td>B</td>
</tr>
<tr>
<td>1</td>
<td>C</td>
</tr>
</tbody>
</table>
```
##### JavaScript
```
const allTables = document.querySelectorAll("table");
for (const table of allTables) {
const tBody = table.tBodies[0];
const rows = Array.from(tBody.rows);
const headerCells = table.tHead.rows[0].cells;
for (const th of headerCells) {
const cellIndex = th.cellIndex;
th.addEventListener("click", () => {
rows.sort((tr1, tr2) => {
const tr1Text = tr1.cells[cellIndex].textContent;
const tr2Text = tr2.cells[cellIndex].textContent;
return tr1Text.localeCompare(tr2Text);
});
tBody.append(...rows);
});
}
}
```
##### Result
### Displaying large tables in small spaces
A common issue with tables on the web is that they don't natively work very well on small screens when the amount of content is large, and the way to make them scrollable isn't obvious, especially when the markup may come from a CMS and cannot be modified to have a wrapper.
This example provides one way to display tables in small spaces. We've hidden the HTML content as it is very large, and there is nothing remarkable about it. The CSS is more useful to inspect in this example.
When looking at these styles you'll notice that table's [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) property has been set to `block`. While this allows scrolling, the table loses some of its integrity, and table cells try to become as small as possible. To mitigate this issue we've set [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) to `nowrap` on the `<tbody>`. However, we don't do this for the `<thead>` to avoid long titles forcing columns to be wider than they need to be to display the data.
To keep the table headers on the page while scrolling down we've set [`position`](https://developer.mozilla.org/en-US/docs/Web/CSS/position) to sticky on the `<th>` elements. Note that we have **not** set [`border-collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) to `collapse`, as if we do the header cannot be separated correctly from the rest of the table.
```
table,
th,
td {
border: 1px solid;
}
table {
width: 100%;
max-width: 400px;
height: 240px;
margin: 0 auto;
display: block;
overflow-x: auto;
border-spacing: 0;
}
tbody {
white-space: nowrap;
}
th,
td {
padding: 5px 10px;
border-top-width: 0;
border-left-width: 0;
}
th {
position: sticky;
top: 0;
background: #fff;
vertical-align: bottom;
}
th:last-child,
td:last-child {
border-right-width: 0;
}
tr:last-child td {
border-bottom-width: 0;
}
```
#### Result
Accessibility concerns
----------------------
### Captions
By supplying a [`<caption>`](caption) element whose value clearly and concisely describes the table's purpose, it helps the people decide if they need to read the rest of the table content or skip over it.
This helps people navigating with the aid of assistive technology such as a screen reader, people experiencing low vision conditions, and people with cognitive concerns.
* [MDN Adding a caption to your table with <caption>](https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Advanced#adding_a_caption_to_your_table_with_caption)
* [Caption & Summary • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/caption-summary/)
### Scoping rows and columns
The [`scope`](th#attr-scope) attribute on header elements is redundant in simple contexts, because scope is inferred. However, some assistive technologies may fail to draw correct inferences, so specifying header scope may improve user experiences. In complex tables, scope can be specified to provide necessary information about the cells related to a header.
#### Example
```
<table>
<caption>
Color names and values
</caption>
<tbody>
<tr>
<th scope="col">Name</th>
<th scope="col">HEX</th>
<th scope="col">HSLa</th>
<th scope="col">RGBa</th>
</tr>
<tr>
<th scope="row">Teal</th>
<td><code>#51F6F6</code></td>
<td><code>hsl(180 90% 64% / 1)</code></td>
<td><code>rgb(81 246 246 / 1)</code></td>
</tr>
<tr>
<th scope="row">Goldenrod</th>
<td><code>#F6BC57</code></td>
<td><code>hsl(38 90% 65% / 1)</code></td>
<td><code>rgba(246 188 87 / 1)</code></td>
</tr>
</tbody>
</table>
```
Providing a declaration of `scope="col"` on a [`<th>`](th) element will help describe that the cell is at the top of a column. Providing a declaration of `scope="row"` on a [`<th>`](th) element will help describe that the cell is the first in a row.
* [MDN Tables for visually impaired users](https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Advanced#tables_for_visually_impaired_users)
* [Tables with two headers • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/two-headers/)
* [Tables with irregular headers • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/irregular/)
* [H63: Using the scope attribute to associate header cells and data cells in data tables | W3C Techniques for WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/H63.html)
### Complicated tables
Assistive technology such as screen readers may have difficulty parsing tables that are so complex that header cells can't be associated in a strictly horizontal or vertical way. This is typically indicated by the presence of the [`colspan`](td#attr-colspan) and [`rowspan`](td#attr-rowspan) attributes.
Ideally, consider alternate ways to present the table's content, including breaking it apart into a collection of smaller, related tables that don't have to rely on using the `colspan` and `rowspan` attributes. In addition to helping people who use assistive technology understand the table's content, this may also benefit people with cognitive concerns who may have difficulty understanding the associations the table layout is describing.
If the table cannot be broken apart, use a combination of the [`id`](../global_attributes#id) and [`headers`](td#attr-headers) attributes to programmatically associate each table cell with the header(s) the cell is associated with.
* [MDN Tables for visually impaired users](https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Advanced#tables_for_visually_impaired_users)
* [Tables with multi-level headers • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/multi-level/)
* [H43: Using id and headers attributes to associate data cells with header cells in data tables | Techniques for W3C WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/H43.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-table-element](https://html.spec.whatwg.org/multipage/tables.html#the-table-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `table` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `align` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `border` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `cellpadding` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `cellspacing` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `frame` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `rules` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `summary` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
| `width` | 1 | 12 | 1 | Yes | Yes | Yes | 4.4 | 18 | 4 | Yes | Yes | 1.0 |
See also
--------
* [HTML data table tutorial](https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables)
* CSS properties that may be especially useful to style the `<table>` element:
+ [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) to control the width of the table;
+ [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border), [`border-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-style), [`border-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-color), [`border-width`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-width), [`border-collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse), [`border-spacing`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing) to control the aspect of cell borders, rules and frame;
+ [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) and [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) to style the individual cell content;
+ [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) and [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) to define the alignment of text and cell content.
html <bgsound>: The Background Sound element <bgsound>: The Background Sound element
=======================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<bgsound>` [HTML](../index) element is deprecated. It sets up a sound file to play in the background while the page is used; use [`<audio>`](audio) instead.
**Warning:** Do not use this! In order to embed audio in a Web page, you should be using the [`<audio>`](audio) element.
Attributes
----------
[**`balance`**](#attr-balance) This attribute defines a number between -10,000 and +10,000 that determines how the volume will be divided between the speakers.
[**`loop`**](#attr-loop) This attribute indicates the number of times a sound is to be played and either has a numeric value or the keyword infinite.
[**`src`**](#attr-src) This attribute specifies the URL of the sound file to be played, which must be one of the following types: .wav, .au, or .mid.
[**`volume`**](#attr-volume) This attribute defines a number between -10,000 and 0 that determines the loudness of a page's background sound.
Example
-------
```
<bgsound src="sound1.mid"></bgsound>
<bgsound src="sound2.au" loop="infinite"></bgsound>
```
Usage notes
-----------
Historically, the [`<embed>`](embed) element could be used with audio player plug-ins to play audio in the background in most browsers. However, even this is no longer appropriate, and you should use `<audio>` instead, since it's more capable, more compatible, and doesn't require plug-ins.
You can write `<bgsound>` as a self-closing tag (`<bgsound />`); however, since this element is non-standard, doing so will still not validate.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # bgsound](https://html.spec.whatwg.org/multipage/obsolete.html#bgsound) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `bgsound` | No | No | No
Up to Firefox 22, even if not supporting this element, Firefox was associating it with `HTMLSpanElement`. This was fixed then and now the associated element is an `HTMLUnknownElement` as required by the specification. | Yes | No | No | No | No | No
Up to Firefox 22, even if not supporting this element, Firefox was associating it with `HTMLSpanElement`. This was fixed then and now the associated element is an `HTMLUnknownElement` as required by the specification. | No | No | No |
See also
--------
* The [`<audio>`](audio), which is the standard element to embed audio in a document.
| programming_docs |
html <rtc>: The Ruby Text Container element <rtc>: The Ruby Text Container element
======================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<rtc>` [HTML](../index) element embraces semantic annotations of characters presented in a ruby of [`<rb>`](rb) elements used inside of [`<ruby>`](ruby) element. [`<rb>`](rb) elements can have both pronunciation ([`<rt>`](rt)) and semantic ([`<rtc>`](rtc)) annotations.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
```
<div class="info">
<ruby>
<rtc>
<rb>旧</rb><rt>jiù</rt>
<rb>金</rb><rt>jīn</rt>
<rb>山</rb><rt>shān</rt>
</rtc>
<rtc>San Francisco</rtc>
</ruby>
</div>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content) or [`<rt>`](rt) elements. |
| Tag omission | The closing tag can be omitted if it is immediately followed by a [`<rb>`](rb), [`<rtc>`](rtc) or [`<rt>`](rt) element opening tag or by its parent closing tag. |
| Permitted parents | A [`<ruby>`](ruby) element. |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # rtc](https://html.spec.whatwg.org/multipage/obsolete.html#rtc) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `rtc` | No | No | 33 | No | No | No | No | No | 33 | No | No | No |
See also
--------
* [`<ruby>`](ruby)
* [`<rp>`](rp)
* [`<rb>`](rb)
* [`<rt>`](rt)
html <em>: The Emphasis element <em>: The Emphasis element
==========================
The `<em>` [HTML](../index) element marks text that has stress emphasis. The `<em>` element can be nested, with each level of nesting indicating a greater degree of emphasis.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
The `<em>` element is for words that have a stressed emphasis compared to surrounding text, which is often limited to a word or words of a sentence and affects the meaning of the sentence itself.
Typically this element is displayed in italic type. However, it should not be used to apply italic styling; use the CSS [`font-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) property for that purpose. Use the [`<cite>`](cite) element to mark the title of a work (book, play, song, etc.). Use the [`<i>`](i) element to mark text that is in an alternate tone or mood, which covers many common situations for italics such as scientific names or words in other languages. Use the [`<strong>`](strong) element to mark text that has greater importance than surrounding text.
### <i> vs. <em>
Some developers may be confused by how multiple elements seemingly produce similar visual results. `<em>` and `<i>` are a common example, since they both italicize text. What's the difference? Which should you use?
By default, the visual result is the same. However, the semantic meaning is different. The `<em>` element represents stress emphasis of its contents, while the `<i>` element represents text that is set off from the normal prose, such a foreign word, fictional character thoughts, or when the text refers to the definition of a word instead of representing its semantic meaning. (The title of a work, such as the name of a book or movie, should use `<cite>`.)
This means the right one to use depends on the situation. Neither is for purely decorative purposes, that's what CSS styling is for.
An example for `<em>` could be: "Just *do* it already!", or: "We *had* to do something about it". A person or software reading the text would pronounce the words in italics with an emphasis, using verbal stress.
An example for `<i>` could be: "The *Queen Mary* sailed last night". Here, there is no added emphasis or importance on the word "Queen Mary". It is merely indicated that the object in question is not a queen named Mary, but a ship named *Queen Mary*. Another example for `<i>` could be: "The word *the* is an article".
Example
-------
The `<em>` element is often used to indicate an implicit or explicit contrast.
```
<p>
In HTML 5, what was previously called
<em>block-level</em> content is now called <em>flow</em> content.
</p>
```
### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the [`HTMLSpanElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement) interface for this element. |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-em-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-em-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `em` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<i>`](i)
html <del>: The Deleted Text element <del>: The Deleted Text element
===============================
The `<del>` [HTML](../index) element represents a range of text that has been deleted from a document. This can be used when rendering "track changes" or source code diff information, for example. The [`<ins>`](ins) element can be used for the opposite purpose: to indicate text that has been added to the document.
Try it
------
This element is often (but need not be) rendered by applying a strike-through style to the text.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Phrasing content](../content_categories#phrasing_content), [flow content](../content_categories#flow_content). |
| Permitted content | [Transparent](../content_categories#transparent_content_model). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLModElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLModElement) |
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`cite`**](#attr-cite) A URI for a resource that explains the change (for example, meeting minutes).
[**`datetime`**](#attr-datetime) This attribute indicates the time and date of the change and must be a valid date string with an optional time. If the value cannot be parsed as a date with an optional time string, the element does not have an associated timestamp. For the format of the string without a time, see [Date strings](../date_and_time_formats#date_strings). The format of the string if it includes both date and time is covered in [Local date and time strings](../date_and_time_formats#local_date_and_time_strings).
Examples
--------
```
<p><del>This text has been deleted</del>, here is the rest of the paragraph.</p>
<del><p>This paragraph has been deleted.</p></del>
```
### Result
Accessibility concerns
----------------------
The presence of the `del` element is not announced by most screen reading technology in its default configuration. It can be made to be announced by using the CSS [`content`](https://developer.mozilla.org/en-US/docs/Web/CSS/content) property, along with the [`::before`](https://developer.mozilla.org/en-US/docs/Web/CSS/::before) and [`::after`](https://developer.mozilla.org/en-US/docs/Web/CSS/::after) pseudo-elements.
```
del::before,
del::after {
clip-path: inset(100%);
clip: rect(1px, 1px, 1px, 1px);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
del::before {
content: " [deletion start] ";
}
del::after {
content: " [deletion end] ";
}
```
Some people who use screen readers deliberately disable announcing content that creates extra verbosity. Because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has been deleted would adversely affect understanding.
* [Short note on making your mark (more accessible) | The Paciello Group](https://www.tpgi.com/short-note-on-making-your-mark-more-accessible/)
* [Tweaking Text Level Styles | Adrian Roselli](https://adrianroselli.com/2017/12/tweaking-text-level-styles.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-del-element](https://html.spec.whatwg.org/multipage/edits.html#the-del-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `del` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `cite` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `datetime` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<ins>`](ins) element for insertions into a text
* [`<s>`](s) element for strikethrough separate from representing deletion of text
html <button>: The Button element <button>: The Button element
============================
The `<button>` [HTML](../index) element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs an action, such as submitting a [form](https://developer.mozilla.org/en-US/docs/Learn/Forms) or opening a dialog.
By default, HTML buttons are presented in a style resembling the platform the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) runs on, but you can change buttons' appearance with [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS).
Try it
------
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`autofocus`**](#attr-autofocus) This Boolean attribute specifies that the button should have input [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) when the page loads. **Only one element in a document can have this attribute.**
[**`autocomplete`**](#attr-autocomplete) Non-standard
This attribute on a [`<button>`](button) is nonstandard and Firefox-specific. Unlike other browsers, [Firefox persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a [`<button>`](button) across page loads. Setting `autocomplete="off"` on the button disables this feature; see [bug 654072](https://bugzilla.mozilla.org/show_bug.cgi?id=654072).
[**`disabled`**](#attr-disabled) This Boolean attribute prevents the user from interacting with the button: it cannot be pressed or focused.
Firefox, unlike other browsers, [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a [`<button>`](button) across page loads. Use the [`autocomplete`](button#attr-autocomplete) attribute to control this feature.
[**`form`**](#attr-form) The [`<form>`](form) element to associate the button with (its *form owner*). The value of this attribute must be the `id` of a `<form>` in the same document. (If this attribute is not set, the `<button>` is associated with its ancestor `<form>` element, if any.)
This attribute lets you associate `<button>` elements to `<form>`s anywhere in the document, not just inside a `<form>`. It can also override an ancestor `<form>` element.
[**`formaction`**](#attr-formaction) The URL that processes the information submitted by the button. Overrides the [`action`](form#attr-action) attribute of the button's form owner. Does nothing if there is no form owner.
[**`formenctype`**](#attr-formenctype) If the button is a submit button (it's inside/associated with a `<form>` and doesn't have `type="button"`), specifies how to encode the form data that is submitted. Possible values:
* `application/x-www-form-urlencoded`: The default if the attribute is not used.
* `multipart/form-data`: Used to submit [`<input>`](input) elements with their [`type`](input#attr-type) attributes set to `file`.
* `text/plain`: Specified as a debugging aid; shouldn't be used for real form submission.
If this attribute is specified, it overrides the [`enctype`](form#attr-enctype) attribute of the button's form owner.
[**`formmethod`**](#attr-formmethod) If the button is a submit button (it's inside/associated with a `<form>` and doesn't have `type="button"`), this attribute specifies the [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) used to submit the form. Possible values:
* `post`: The data from the form are included in the body of the HTTP request when sent to the server. Use when the form contains information that shouldn't be public, like login credentials.
* `get`: The form data are appended to the form's `action` URL, with a `?` as a separator, and the resulting URL is sent to the server. Use this method when the form [has no side effects](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent), like search forms.
If specified, this attribute overrides the [`method`](form#attr-method) attribute of the button's form owner.
[**`formnovalidate`**](#attr-formnovalidate) If the button is a submit button, this Boolean attribute specifies that the form is not to be [validated](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) when it is submitted. If this attribute is specified, it overrides the [`novalidate`](form#attr-novalidate) attribute of the button's form owner.
This attribute is also available on [`<input type="image">`](input/image) and [`<input type="submit">`](input/submit) elements.
[**`formtarget`**](#attr-formtarget) If the button is a submit button, this attribute is an author-defined name or standardized, underscore-prefixed keyword indicating where to display the response from submitting the form. This is the `name` of, or keyword for, a *browsing context* (a tab, window, or [`<iframe>`](iframe)). If this attribute is specified, it overrides the [`target`](form#attr-target) attribute of the button's form owner. The following keywords have special meanings:
* `_self`: Load the response into the same browsing context as the current one. This is the default if the attribute is not specified.
* `_blank`: Load the response into a new unnamed browsing context — usually a new tab or window, depending on the user's browser settings.
* `_parent`: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as `_self`.
* `_top`: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as `_self`.
[**`name`**](#attr-name) The name of the button, submitted as a pair with the button's `value` as part of the form data, when that button is used to submit the form.
[**`type`**](#attr-type) The default behavior of the button. Possible values are:
* `submit`: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a `<form>`, or if the attribute is an empty or invalid value.
* `reset`: The button resets all the controls to their initial values, like [<input type="reset">](input/reset). (This behavior tends to annoy users.)
* `button`: The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element's events, which are triggered when the events occur.
[**`value`**](#attr-value) Defines the value associated with the button's `name` when it's submitted with the form data. This value is passed to the server in params when the form is submitted using this button.
Notes
-----
A submit button with the attribute `formaction` set, but without an associated form does nothing. You have to set a form owner, either by wrapping it in a `<form>` or set the attribute `form` to the id of the form.
`<button>` elements are much easier to style than [`<input>`](input) elements. You can add inner HTML content (think `<i>`, `<br>`, or even `<img>`), and use [`::after`](https://developer.mozilla.org/en-US/docs/Web/CSS/::after) and [`::before`](https://developer.mozilla.org/en-US/docs/Web/CSS/::before) pseudo-elements for complex rendering.
If your buttons are not for submitting form data to a server, be sure to set their `type` attribute to `button`. Otherwise they will try to submit form data and to load the (nonexistent) response, possibly destroying the current state of the document.
While `<button type="button">` has no default behavior, event handlers can be scripted to trigger behaviors. An activated button can perform programmable actions using [JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript), such as removing an item from a list.
Example
-------
```
<button name="button">Press me</button>
```
Accessibility concerns
----------------------
### Icon buttons
Buttons that only show an icon to represent do not have an *accessible name*. Accessible names provide information for assistive technology, such as screen readers, to access when they parse the document and generate [an accessibility tree](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility#accessibility_apis). Assistive technology then uses the accessibility tree to navigate and manipulate page content.
To give an icon button an accessible name, put text in the `<button>` element that concisely describes the button's functionality.
#### Example
```
<button name="favorite">
<svg aria-hidden="true" viewBox="0 0 10 10">
<path d="M7 9L5 8 3 9V6L1 4h3l1-3 1 3h3L7 6z" />
</svg>
Add to favorites
</button>
```
If you want to visually hide the button's text, an accessible way to do so is to use [a combination of CSS properties](https://gomakethings.com/hidden-content-for-better-a11y/#hiding-the-link) to remove it visually from the screen, but keep it parsable by assistive technology.
However, it is worth noting that leaving the button text visually apparent can aid people who may not be familiar with the icon's meaning or understand the button's purpose. This is especially relevant for people who are not technologically sophisticated, or who may have different cultural interpretations for the icon the button uses.
* [What is an accessible name? | The Paciello Group](https://www.tpgi.com/what-is-an-accessible-name/)
* [MDN Understanding WCAG, Guideline 4.1 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Robust#guideline_4.1_%E2%80%94_compatible_maximize_compatibility_with_current_and_future_user_agents_including_assistive_technologies)
* [Understanding Success Criterion 4.1.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/ensure-compat-rsv.html)
### Size and Proximity
#### Size
Interactive elements such as buttons should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44×44 [CSS pixels](https://www.w3.org/TR/WCAG21/#dfn-css-pixels) is recommended.
* [Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/target-size.html)
* [Target Size and 2.5.5 | Adrian Roselli](https://adrianroselli.com/2019/06/target-size-and-2-5-5.html)
* [Quick test: Large touch targets - The A11Y Project](https://www.a11yproject.com/posts/large-touch-targets/)
#### Proximity
Large amounts of interactive content — including buttons — placed in close visual proximity to each other should have space separating them. This spacing is beneficial for people who are experiencing motor control issues, who may accidentally activate the wrong interactive content.
Spacing may be created using CSS properties such as [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin).
* [Hand tremors and the giant-button-problem - Axess Lab](https://axesslab.com/hand-tremors/)
### ARIA state information
To describe the state of a button the correct ARIA attribute to use is [`aria-pressed`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) and not [`aria-checked`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) or [`aria-selected`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected). To find out more read the information about the [ARIA button role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role).
### Firefox
Firefox will add a small dotted border on a focused button. This border is declared through CSS in the browser stylesheet, but you can override it to add your own focused style using [`button::-moz-focus-inner { }`](https://developer.mozilla.org/en-US/docs/Web/CSS/::-moz-focus-inner).
If overridden, it is important to **ensure that the state change when focus is moved to the button is high enough** that people experiencing low vision conditions will be able to perceive it.
Color contrast ratio is determined by comparing the luminosity of the button text and background color values compared to the background the button is placed on. In order to meet current [Web Content Accessibility Guidelines (WCAG)](https://www.w3.org/WAI/standards-guidelines/wcag/), a ratio of 4.5:1 is required for text content and 3:1 for large text. (Large text is defined as 18.66px and [`bold`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) or larger, or 24px or larger.)
* [WebAIM: Color Contrast Checker](https://webaim.org/resources/contrastchecker/)
* [MDN Understanding WCAG, Guideline 1.4 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.4_make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background)
* [Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html)
### Clicking and focus
Whether clicking on a [`<button>`](button) or [`<input>`](input) button types causes it to (by default) become focused varies by browser and OS. Most browsers do give focus to a button being clicked, but [Safari does not, by design](https://bugs.webkit.org/show_bug.cgi?id=22261).
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [Interactive content](../content_categories#interactive_content), [listed](../content_categories#form_listed), [labelable](../content_categories#form_labelable), and [submittable](../content_categories#form_submittable) [form-associated](../content_categories#form-associated_content) element, palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content) but there must be no [Interactive content](../content_categories#interactive_content) |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | `[button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)` |
| Permitted ARIA roles | `[checkbox](https://w3c.github.io/aria/#checkbox)`, `[combobox](https://w3c.github.io/aria/#combobox)`, `[link](https://w3c.github.io/aria/#link)`, `[menuitem](https://w3c.github.io/aria/#menuitem)`, `[menuitemcheckbox](https://w3c.github.io/aria/#menuitemcheckbox)`, `[menuitemradio](https://w3c.github.io/aria/#menuitemradio)`, `[option](https://w3c.github.io/aria/#option)`, `[radio](https://w3c.github.io/aria/#radio)`, `[switch](https://w3c.github.io/aria/#switch)`, `[tab](https://w3c.github.io/aria/#tab)` |
| DOM interface | [`HTMLButtonElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-button-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `button` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `autocomplete` | No | No | Yes | No | No | No | No | No | Yes | No | No | No |
| `disabled` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `form` | Yes | 16 | Yes | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `formaction` | 9 | 12 | 4 | 10 | 15 | 5.1 | 37 | 18 | 4 | No | 5 | 1.0 |
| `formenctype` | 9 | 12 | 4 | 10 | 10.6 | No | 37 | 18 | 4 | No | No | 1.0 |
| `formmethod` | 9 | 12 | 4 | 10 | 15 | No | 37 | 18 | 4 | No | No | 1.0 |
| `formnovalidate` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `formtarget` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `name` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `type` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `value` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| programming_docs |
html <p>: The Paragraph element <p>: The Paragraph element
==========================
The `<p>` [HTML](../index) element represents a paragraph. Paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but HTML paragraphs can be any structural grouping of related content, such as images or form fields.
Paragraphs are [block-level elements](../block-level_elements), and notably will automatically close if another block-level element is parsed before the closing `</p>` tag. See "Tag omission" below.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | The start tag is required. The end tag may be omitted if the [`<p>`](p) element is immediately followed by an [`<address>`](address), [`<article>`](article), [`<aside>`](aside), [`<blockquote>`](blockquote), [`<div>`](div), [`<dl>`](dl), [`<fieldset>`](fieldset), [`<footer>`](footer), [`<form>`](form), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<header>`](header), [`<hr>`](hr), [`<menu>`](menu), [`<nav>`](nav), [`<ol>`](ol), [`<pre>`](pre), [`<section>`](section), [`<table>`](table), [`<ul>`](ul) or another [`<p>`](p) element, or if there is no more content in the parent element and the parent element is not an [`<a>`](a) element. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLParagraphElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLParagraphElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
**Note:** The `align` attribute on `<p>` tags is obsolete and shouldn't be used.
Example
-------
### HTML
```
<p>
This is the first paragraph of text. This is the first paragraph of text. This
is the first paragraph of text. This is the first paragraph of text.
</p>
<p>
This is the second paragraph. This is the second paragraph. This is the second
paragraph. This is the second paragraph.
</p>
```
### Result
Styling paragraphs
------------------
By default, browsers separate paragraphs with a single blank line. Alternate separation methods, such as first-line indentation, can be achieved with [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS):
### HTML
```
<p>Separating paragraphs with blank lines is easiest
for readers to scan, but they can also be separated
by indenting their first lines. This is often used
to take up less space, such as to save paper in print.</p>
<p>Writing that is intended to be edited, such as school
papers and rough drafts, uses both blank lines and
indentation for separation. In finished works, combining
both is considered redundant and amateurish.</p>
<p>In very old writing, paragraphs were separated with a
special character: ¶, the <i>pilcrow</i>. Nowadays, this
is considered claustrophobic and hard to read.</p>
<p>How hard to read? See for yourself:
<button data-toggle-text="Oh no! Switch back!">Use pilcrow for paragraphs</button>
</p>
```
### CSS
```
p {
margin: 0;
text-indent: 3ch;
}
p.pilcrow {
text-indent: 0;
display: inline;
}
p.pilcrow + p.pilcrow::before {
content: " ¶ ";
}
```
### JavaScript
```
document.querySelector('button').addEventListener('click', (event) => {
document.querySelectorAll('p').forEach((paragraph) => {
paragraph.classList.toggle('pilcrow');
});
[event.target.innerText, event.target.dataset.toggleText] =
[event.target.dataset.toggleText, event.target.innerText];
});
```
### Result
Accessibility concerns
----------------------
Breaking up content into paragraphs helps make a page more accessible. Screen-readers and other assistive technology provide shortcuts to let their users skip to the next or previous paragraph, letting them skim content like how white space lets visual users skip around.
Using empty `<p>` elements to add space between paragraphs is problematic for people who navigate with screen-reading technology. Screen readers may announce the paragraph's presence, but not any content contained within it — because there is none. This can confuse and frustrate the person using the screen reader.
If extra space is desired, use [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS) properties like [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) to create the effect:
```
p {
margin-bottom: 2em; /\* increase white space after a paragraph \*/
}
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-p-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-p-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `p` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<hr>`](hr)
* [`<br>`](br)
html <details>: The Details disclosure element <details>: The Details disclosure element
=========================================
The `<details>` [HTML](../index) element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the [`<summary>`](summary) element.
A disclosure widget is typically presented onscreen using a small triangle which rotates (or twists) to indicate open/closed status, with a label next to the triangle. The contents of the `<summary>` element are used as the label for the disclosure widget.
Try it
------
A `<details>` widget can be in one of two states. The default *closed* state displays only the triangle and the label inside `<summary>` (or a [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent)-defined default string if no `<summary>`).
When the user clicks on the widget or focuses it then presses the space bar, it "twists" open, revealing its contents. The common use of a triangle which rotates or twists around to represent opening or closing the widget is why these are sometimes called "twisty".
You can use CSS to style the disclosure widget, and you can programmatically open and close the widget by setting/removing its [`open`](details#attr-open) attribute. Unfortunately, at this time there's no built-in way to animate the transition between open and closed.
By default when closed, the widget is only tall enough to display the disclosure triangle and summary. When open, it expands to display the details contained within.
Fully standards-compliant implementations automatically apply the CSS `[`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display): list-item` to the [`<summary>`](summary) element. You can use this to customize its appearance further. See [Customizing the disclosure widget](#customizing_the_disclosure_widget) for further details.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`open`**](#attr-open) This Boolean attribute indicates whether the details — that is, the contents of the `<details>` element — are currently visible. The details are shown when this attribute exists, or hidden when this attribute is absent. By default this attribute is absent which means the details are not visible.
**Note:** You have to remove this attribute entirely to make the details hidden. `open="false"` makes the details visible because this attribute is Boolean.
Events
------
In addition to the usual events supported by HTML elements, the `<details>` element supports the [`toggle`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDetailsElement/toggle_event) event, which is dispatched to the `<details>` element whenever its state changes between open and closed. It is sent *after* the state is changed, although if the state changes multiple times before the browser can dispatch the event, the events are coalesced so that only one is sent.
You can use an event listener for the `toggle` event to detect when the widget changes state:
```
details.addEventListener("toggle", (event) => {
if (details.open) {
/\* the element was toggled open \*/
} else {
/\* the element was toggled closed \*/
}
});
```
Examples
--------
### A simple disclosure example
This example shows a simple `<details>` element with a `<summary>`.
```
<details>
<summary>System Requirements</summary>
<p>
Requires a computer running an operating system. The computer must have some
memory and ideally some kind of long-term storage. An input device as well
as some form of output device is recommended.
</p>
</details>
```
The result of this HTML is:
### Creating an open disclosure box
To start the `<details>` box in its open state, add the Boolean `open` attribute:
```
<details open>
<summary>System Requirements</summary>
<p>
Requires a computer running an operating system. The computer must have some
memory and ideally some kind of long-term storage. An input device as well
as some form of output device is recommended.
</p>
</details>
```
This results in:
### Customizing the appearance
Now let's apply some CSS to customize the appearance of the disclosure box.
#### CSS
```
details {
font: 16px "Open Sans", Calibri, sans-serif;
width: 620px;
}
details > summary {
padding: 2px 6px;
width: 15em;
background-color: #ddd;
border: none;
box-shadow: 3px 3px 4px black;
cursor: pointer;
}
details > p {
border-radius: 0 0 10px 10px;
background-color: #ddd;
padding: 2px 6px;
margin: 0;
box-shadow: 3px 3px 4px black;
}
details[open] > summary {
background-color: #ccf;
}
```
This CSS creates a look similar to a tabbed interface, where clicking the tab opens it to reveal its contents.
The selector `details[open]` can be used to style the element which is open.
#### HTML
```
<details>
<summary>System Requirements</summary>
<p>
Requires a computer running an operating system. The computer must have some
memory and ideally some kind of long-term storage. An input device as well
as some form of output device is recommended.
</p>
</details>
```
#### Result
### Customizing the disclosure widget
The disclosure triangle itself can be customized, although this is not as broadly supported. There are variations in how browsers support this customization due to experimental implementations as the element was standardized, so we'll have to use multiple approaches for a while.
The [`<summary>`](summary) element supports the [`list-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style) shorthand property and its longhand properties, such as [`list-style-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type), to change the disclosure triangle to whatever you choose (usually with [`list-style-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image)). For example, we can remove the disclosure widget icon by setting `list-style: none`.
#### CSS
```
details {
font: 16px "Open Sans", Calibri, sans-serif;
width: 620px;
}
details > summary {
padding: 2px 6px;
width: 15em;
background-color: #ddd;
border: none;
box-shadow: 3px 3px 4px black;
cursor: pointer;
list-style: none;
}
details > p {
border-radius: 0 0 10px 10px;
background-color: #ddd;
padding: 2px 6px;
margin: 0;
box-shadow: 3px 3px 4px black;
}
```
This CSS creates a look similar to a tabbed interface, where activating the tab expands and opens it to reveal its contents.
#### HTML
```
<details>
<summary>System Requirements</summary>
<p>
Requires a computer running an operating system. The computer must have some
memory and ideally some kind of long-term storage. An input device as well
as some form of output device is recommended.
</p>
</details>
```
#### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), sectioning root, interactive content, palpable content. |
| Permitted content | One [`<summary>`](summary) element followed by [flow content](../content_categories#flow_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | `[group](https://w3c.github.io/aria/#group)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLDetailsElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDetailsElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-details-element](https://html.spec.whatwg.org/multipage/interactive-elements.html#the-details-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `details` | 12 | 79 | 49
Before Firefox 57, there was a bug meaning that `<details>` elements can't be made open by default using the `open` attribute if they have a CSS `animation` active on them. | No | 15 | 6 | Yes | Yes | 49
There is a bug meaning that `<details>` elements can't be made open by default using the `open` attribute if they have a CSS `animation` active on them. | 14 | 6 | Yes |
| `open` | 12 | 79 | 49 | No | 15 | 6 | 4 | Yes | 49 | 14 | 6 | Yes |
See also
--------
* [`<summary>`](summary)
html <menu>: The Menu element <menu>: The Menu element
========================
The `<menu>` [HTML](../index) element is described in the HTML specification as a semantic alternative to [`<ul>`](ul), but treated by browsers (and exposed through the accessibility tree) as no different than [`<ul>`](ul). It represents an unordered list of items (which are represented by [`<li>`](li) elements).
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
The `<menu>` and [`<ul>`](ul) elements both represent an unordered list of items. The key difference is that [`<ul>`](ul) primarily contains items for display, while `<menu>` was intended for interactive items. The related [`<menuitem>`](menuitem) element has been deprecated.
**Note:** In early versions of the HTML specification, the `<menu>` element had an additional use case as a context menu. This functionality is considered obsolete and is not in the specification.
Examples
--------
### Toolbar
In this example, a `<menu>` is used to create a toolbar for an editing application.
#### HTML
```
<menu>
<li><button onclick="copy()">Copy</button></li>
<li><button onclick="cut()">Cut</button></li>
<li><button onclick="paste()">Paste</button></li>
</menu>
```
Note that this is functionally no different from:
```
<ul>
<li><button onclick="copy()">Copy</button></li>
<li><button onclick="cut()">Cut</button></li>
<li><button onclick="paste()">Paste</button></li>
</ul>
```
#### CSS
```
menu,
ul {
display: flex;
list-style: none;
padding: 0;
width: 400px;
}
li {
flex-grow: 1;
}
button {
width: 100%;
}
```
#### Result
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content). If the element's children include at least one [`<li>`](li) element: [Palpable content](../content_categories#palpable_content). |
| Permitted content | Zero or more occurrences of [`<li>`](li), [`<script>`](script), and [`<template>`](template). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | `[list](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/list_role)` |
| Permitted ARIA roles | `[directory](https://w3c.github.io/aria/#directory)`, `[group](https://w3c.github.io/aria/#group)`, `[listbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role)`, `[menu](https://w3c.github.io/aria/#menu)`, `[menubar](https://w3c.github.io/aria/#menubar)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[radiogroup](https://w3c.github.io/aria/#radiogroup)`, `[tablist](https://w3c.github.io/aria/#tablist)`, `[toolbar](https://w3c.github.io/aria/#toolbar)` or `[tree](https://w3c.github.io/aria/#tree)` |
| DOM interface | [`HTMLMenuElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMenuElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-menu-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-menu-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `menu` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hr_separator` | No | No | 51-85 | No | No | No | No | No | 51-85 | No | No | No |
| `label` | No | No | 8-85 | No | No | No | No | No | 8-85
Nested menus are not supported. | No | No | No |
| `type_menu` | No | ≤18-79 | 8-85 | No | No | No | No | No | 8-85
Nested menus are not supported. | No | No | No |
See also
--------
* Other list-related HTML Elements: [`<ol>`](ol), [`<ul>`](ul), and [`<li>`](li).
html <portal>: The Portal element <portal>: The Portal element
============================
**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.
The `<portal>` [HTML](../index) element enables the embedding of another HTML page into the current one for the purposes of allowing smoother navigation into new pages.
A `<portal>` is similar to an `<iframe>`. An `<iframe>` allows a separate [browsing context](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context) to be embedded. However, the embedded content of a `<portal>` is more limited than that of an `<iframe>`. It cannot be interacted with, and therefore is not suitable for embedding widgets into a document. Instead, the `<portal>` acts as a preview of the content of another page. It can be navigated into therefore allowing for seamless transition to the embedded content.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`referrerpolicy`**](#attr-referrerpolicy) Sets the [referrer policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) to use when requesting the page at the URL given as the value of the `src` attribute.
[**`src`**](#attr-src) The URL of the page to embed.
Examples
--------
### Basic example
The following example will embed the contents of `https://example.com` as a preview.
```
<portal id="exampleportal" src="https://example.com/"></portal>
```
Accessibility concerns
----------------------
The preview displayed by a `<portal>` is not interactive, therefore does not receive input events or focus. Therefore the embedded contents of the portal are not exposed as elements in the [accessibility tree](https://developer.mozilla.org/en-US/docs/Glossary/Accessibility_tree). The portal can be navigated to and activated like a button, the default behavior when clicking on the portal is to activate it.
Portals are given a default label which is the title of the embedded page. If no title is present the visible text in the preview is concatenated to create a label. The [`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute can be used to override this.
Portals used for prerendering only should be hidden with the hidden HTML attribute or the CSS [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) property with a value of `none`.
When using animations during portal activation the [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) [media feature](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#media_features) should be respected.
Technical summary
-----------------
| | |
| --- | --- |
| Implicit ARIA role | [button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role) |
| DOM interface | `HTMLPortalElement` |
Specifications
--------------
| Specification |
| --- |
| [Portals # the-portal-element](https://wicg.github.io/portals/#the-portal-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `portal` | 85 | 90 | No | No | 73 | No | ? | 85 | No | No | No | No |
| programming_docs |
html <li>: The List Item element <li>: The List Item element
===========================
The `<li>` [HTML](../index) element is used to represent an item in a list. It must be contained in a parent element: an ordered list ([`<ol>`](ol)), an unordered list ([`<ul>`](ul)), or a menu ([`<menu>`](menu)). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`value`**](#attr-value) This integer attribute indicates the current ordinal value of the list item as defined by the [`<ol>`](ol) element. The only allowed value for this attribute is a number, even if the list is displayed with Roman numerals or letters. List items that follow this one continue numbering from the value set. The **value** attribute has no meaning for unordered lists ([`<ul>`](ul)) or for menus ([`<menu>`](menu)).
[**`type`**](#attr-type) Deprecated Non-standard
This character attribute indicates the numbering type:
* `a`: lowercase letters
* `A`: uppercase letters
* `i`: lowercase Roman numerals
* `I`: uppercase Roman numerals
* `1`: numbers
This type overrides the one used by its parent [`<ol>`](ol) element, if any.
**Note:** This attribute has been deprecated; use the CSS [`list-style-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type) property instead.
Examples
--------
For more detailed examples, see the [`<ol>`](ol) and [`<ul>`](ul) pages.
### Ordered list
```
<ol>
<li>first item</li>
<li>second item</li>
<li>third item</li>
</ol>
```
### Ordered list with a custom value
```
<ol type="I">
<li value="3">third item</li>
<li>fourth item</li>
<li>fifth item</li>
</ol>
```
### Unordered list
```
<ul>
<li>first item</li>
<li>second item</li>
<li>third item</li>
</ul>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | The end tag can be omitted if the list item is immediately followed by another [`<li>`](li) element, or if there is no more content in its parent element. |
| Permitted parents | An [`<ul>`](ul), [`<ol>`](ol), or [`<menu>`](menu) element. Though not a conforming usage, the obsolete [`<dir>`](dir) can also be a parent. |
| Implicit ARIA role | `[listitem](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listitem_role)` when child of an `<ol>`, `<ul>` or `<menu>` |
| Permitted ARIA roles | `[menuitem](https://w3c.github.io/aria/#menuitem)`, `[menuitemcheckbox](https://w3c.github.io/aria/#menuitemcheckbox)`, `[menuitemradio](https://w3c.github.io/aria/#menuitemradio)`, `[option](https://w3c.github.io/aria/#option)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[radio](https://w3c.github.io/aria/#radio)`, `[separator](https://w3c.github.io/aria/#separator)`, `[tab](https://w3c.github.io/aria/#tab)`, `[treeitem](https://w3c.github.io/aria/#treeitem)` |
| DOM interface | [`HTMLLIElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLIElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-li-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-li-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `li` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `value` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
See also
--------
* Other list-related HTML Elements: [`<ul>`](ul), [`<ol>`](ol), [`<menu>`](menu), and the obsolete [`<dir>`](dir);
* CSS properties that may be specially useful to style the `<li>` element:
+ the [`list-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style) property, to choose the way the ordinal is displayed,
+ [CSS counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters), to handle complex nested lists,
+ the [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) property, to control the indent of the list item.
html <time>: The (Date) Time element <time>: The (Date) Time element
===============================
The `<time>` [HTML](../index) element represents a specific period in time. It may include the `datetime` attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders.
It may represent one of the following:
* A time on a 24-hour clock.
* A precise date in the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) (with optional time and timezone information).
* [A valid time duration](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-duration-string).
Try it
------
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes).
[**`datetime`**](#attr-datetime) This attribute indicates the time and/or date of the element and must be in one of the formats described below.
Usage notes
-----------
This element is for presenting dates and times in a machine-readable format. For example, this can help a user agent offer to add an event to a user's calendar.
This element should not be used for dates prior to the introduction of the Gregorian calendar (due to complications in calculating those dates).
The *datetime value* (the machine-readable value of the datetime) is the value of the element's `datetime` attribute, which must be in the proper format (see below). If the element does not have a `datetime` attribute, **it must not have any element descendants**, and the *datetime value* is the element's child text content.
### Valid datetime values
a valid year string `2011`
a valid month string `2011-11`
a valid date string `2011-11-18`
a valid yearless date string `11-18`
a valid week string `2011-W47`
a valid time string `14:54`
`14:54:39`
`14:54:39.929`
a valid local date and time string `2011-11-18T14:54:39.929`
`2011-11-18 14:54:39.929`
a valid global date and time string `2011-11-18T14:54:39.929Z`
`2011-11-18T14:54:39.929-0400`
`2011-11-18T14:54:39.929-04:00`
`2011-11-18 14:54:39.929Z`
`2011-11-18 14:54:39.929-0400`
`2011-11-18 14:54:39.929-04:00`
a valid duration string `PT4H18M3S`
Examples
--------
### Simple example
#### HTML
```
<p>The concert starts at <time datetime="2018-07-07T20:00:00">20:00</time>.</p>
```
#### Output
###
`datetime` example
#### HTML
```
<p>
The concert took place on <time datetime="2001-05-15T19:00">May 15</time>.
</p>
```
#### Output
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLTimeElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTimeElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-time-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-time-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `time` | 62 | ≤18 | 22 | No | 49
11.5-12 | 7 | 62 | 62 | 22 | 46
11.5-12 | 4 | 8.0 |
| `datetime` | 62 | ≤18 | 22 | No | 49
11.5-12 | 7 | 62 | 62 | 22 | 46
11.5-12 | 4 | 8.0 |
See also
--------
* The [`<data>`](data) element, allowing to signal other kind of values.
html <object>: The External Object element <object>: The External Object element
=====================================
The `<object>` [HTML](../index) element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`archive`**](#attr-archive) Deprecated
A space-separated list of URIs for archives of resources for the object.
[**`border`**](#attr-border) Deprecated
The width of a border around the control, in pixels.
[**`classid`**](#attr-classid) Deprecated
The URI of the object's implementation. It can be used together with, or in place of, the **data** attribute.
[**`codebase`**](#attr-codebase) Deprecated
The base path used to resolve relative URIs specified by **classid**, **data**, or **archive**. If not specified, the default is the base URI of the current document.
[**`codetype`**](#attr-codetype) Deprecated
The content type of the data specified by **classid**.
[**`data`**](#attr-data) The address of the resource as a valid URL. At least one of **data** and **type** must be defined.
[**`declare`**](#attr-declare) Deprecated
The presence of this Boolean attribute makes this element a declaration only. The object must be instantiated by a subsequent `<object>` element. Repeat the `<object>` element completely each time the resource is reused.
[**`form`**](#attr-form) The form element, if any, that the object element is associated with (its *form owner*). The value of the attribute must be an ID of a [`<form>`](form) element in the same document.
[**`height`**](#attr-height) The height of the displayed resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). — (Absolute values only. [NO percentages](https://html.spec.whatwg.org/multipage/embedded-content.html#dimension-attributes))
[**`name`**](#attr-name) The name of valid browsing context (HTML5), or the name of the control (HTML 4).
[**`standby`**](#attr-standby) Deprecated
A message that the browser can show while loading the object's implementation and data.
[**`type`**](#attr-type) The [content type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the resource specified by **data**. At least one of **data** and **type** must be defined.
[**`usemap`**](#attr-usemap) A hash-name reference to a [`<map>`](map) element; that is a '#' followed by the value of a [`name`](map#attr-name) of a map element.
[**`width`**](#attr-width) The width of the display resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). — (Absolute values only. [NO percentages](https://html.spec.whatwg.org/multipage/embedded-content.html#dimension-attributes))
Examples
--------
### Embed a YouTube Video
```
<object
type="video/mp4"
data="https://www.youtube.com/watch?v=Sp9ZfSvpf7A"
width="1280"
height="720"></object>
```
Note that a `type` field is normally specified, but is not needed for Youtube videos.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content); [phrasing content](../content_categories#phrasing_content); [embedded content](../content_categories#embedded_content), palpable content; if the element has a [`usemap`](object#attr-usemap) attribute, [interactive content](../content_categories#interactive_content); [listed](../content_categories#form_listed), [submittable](../content_categories#form_submittable) [form-associated](../content_categories#form-associated_content) element. |
| Permitted content | zero or more [`<param>`](param) elements, then [transparent](../content_categories#transparent_content_model). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [embedded content](../content_categories#embedded_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[application](https://w3c.github.io/aria/#application)`, `[document](https://w3c.github.io/aria/#document)`, `[image](https://w3c.github.io/aria/#image)` |
| DOM interface | [`HTMLObjectElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-object-element](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `object` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `archive` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `border` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `classid` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `codebase` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `codetype` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `data` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `declare` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `form` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `height` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `name` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `standby` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `tabindex` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `usemap` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `width` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<applet>`](applet) Deprecated
* [`<embed>`](embed)
* [`<param>`](param)
html <font> <font>
======
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<font>` [HTML](../index) element defines the font size, color and face for its content.
**Warning:** Do not use this element. Use the CSS [Fonts](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts) properties to style text.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes).
[**`color`**](#attr-color) Deprecated
This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.
[**`face`**](#attr-face) Deprecated
This attribute contains a comma-separated list of one or more font names. The document text in the default style is rendered in the first font face that the client's browser supports. If no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system.
[**`size`**](#attr-size) Deprecated
This attribute specifies the font size as either a numeric or relative value. Numeric values range from `1` to `7` with `1` being the smallest and `3` the default. It can be defined using a relative value, like `+2` or `-3`, which sets it relative to `3`, the default value.
DOM interface
-------------
This element implements the [`HTMLFontElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFontElement) interface.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # font](https://html.spec.whatwg.org/multipage/obsolete.html#font) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `font` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `color` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `face` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `size` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
html <div>: The Content Division element <div>: The Content Division element
===================================
The `<div>` [HTML](../index) element is the generic container for flow content. It has no effect on the content or layout until styled in some way using [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS) (e.g. styling is directly applied to it, or some kind of layout model like [Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout) is applied to its parent element).
Try it
------
As a "pure" container, the `<div>` element does not inherently represent anything. Instead, it's used to group content so it can be easily styled using the [`class`](../global_attributes#class) or [`id`](../global_attributes#id) attributes, marking a section of a document as being written in a different language (using the [`lang`](../global_attributes#lang) attribute), and so on.
Attributes
----------
This element includes the [global attributes](../global_attributes).
**Note:** The `align` attribute is obsolete; do not use it anymore. Instead, you should use CSS properties or techniques such as [CSS Grid](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) or [CSS Flexbox](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox) to align and position `<div>` elements on the page.
Usage notes
-----------
* The `<div>` element should be used only when no other semantic element (such as [`<article>`](article) or [`<nav>`](nav)) is appropriate.
Accessibility concerns
----------------------
The `<div>` element has [an implicit role of `generic`](https://www.w3.org/TR/wai-aria-1.2/#generic), and not none. This may affect certain ARIA combination declarations that expect a direct descendant element with a certain role to function properly.
Examples
--------
### A simple example
```
<div>
<p>
Any kind of content here. Such as <p>, <table>. You name it!
</p>
</div>
```
The result looks like this:
### A styled example
This example creates a shadowed box by applying a style to the `<div>` using CSS. Note the use of the [`class`](../global_attributes#class) attribute on the `<div>` to apply the style named `"shadowbox"` to the element.
#### HTML
```
<div class="shadowbox">
<p>Here's a very interesting note displayed in a lovely shadowed box.</p>
</div>
```
#### CSS
```
.shadowbox {
width: 15em;
border: 1px solid #333;
box-shadow: 8px 8px 5px #444;
padding: 8px 12px;
background-image: linear-gradient(180deg, #fff, #ddd 40%, #ccc);
}
```
#### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [palpable content](../content_categories#palpable_content). |
| Permitted content | [Flow content](../content_categories#flow_content).Or (in [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG) HTML): If the parent is a [`<dl>`](dl) element: one or more [`<dt>`](dt) elements followed by one or more [`<dd>`](dd) elements, optionally intermixed with [`<script>`](script) and [`<template>`](template) elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content).Or (in [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG) HTML): [`<dl>`](dl) element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLDivElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-div-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-div-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `div` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Semantic sectioning elements: [`<section>`](section), [`<article>`](article), [`<nav>`](nav), [`<header>`](header), [`<footer>`](footer)
* [`<span>`](span) element for styling of phrasing content
| programming_docs |
html <i>: The Idiomatic Text element <i>: The Idiomatic Text element
===============================
The `<i>` [HTML](../index) element represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. Historically, these have been presented using italicized type, which is the original source of the `<i>` naming of this element.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Use the `<i>` element for text that is set off from the normal prose for readability reasons. This would be a range of text with different semantic meaning than the surrounding text. Among the use cases for the `<i>` element are spans of text representing a different quality or mode of text, such as:
+ Alternative voice or mood
+ Taxonomic designations (such as the genus and species "*Homo sapiens*")
+ Idiomatic terms from another language (such as "*et cetera*"); these should include the [`lang`](../global_attributes#lang) attribute to identify the language
+ Technical terms
+ Transliterations
+ Thoughts (such as "She wondered, *What is this writer talking about, anyway?*")
+ Ship or vessel names in Western writing systems (such as "They searched the docks for the *Empress of the Galaxy*, the ship to which they were assigned.")
* In earlier versions of the HTML specification, the `<i>` element was merely a presentational element used to display text in italics, much like the `<b>` element was used to display text in bold letters. This is no longer true, as these tags now define semantics rather than typographic appearance. A browser will typically still display the contents of the `<i>` element in italic type, but is, by definition, no longer required to do so. To display text in italic type, authors should use the CSS [`font-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) property.
* Be sure the text in question is not actually more appropriately marked up with another element.
+ Use [`<em>`](em) to indicate stress emphasis.
+ Use [`<strong>`](strong) to indicate importance, seriousness, or urgency.
+ Use [`<mark>`](mark) to indicate relevance.
+ Use [`<cite>`](cite) to mark up the name of a work, such as a book, play, or song.
+ Use [`<dfn>`](dfn) to mark up the defining instance of a term.
Examples
--------
This example demonstrates using the `<i>` element to mark text that is in another language.
```
<p>The Latin phrase <i lang="la">Veni, vidi, vici</i> is often mentioned in music, art, and literature.</p>
```
### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-i-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-i-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `i` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<em>`](em)
* Other italicized elements: [`<var>`](var), [`<dfn>`](dfn), [`<cite>`](cite), [`<address>`](address)
html <data>: The Data element <data>: The Data element
========================
The `<data>` [HTML](../index) element links a given piece of content with a machine-readable translation. If the content is time- or date-related, the [`<time>`](time) element must be used.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLDataElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDataElement) |
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`value`**](#attr-value) This attribute specifies the machine-readable translation of the content of the element.
Examples
--------
The following example displays product names but also associates each name with a product number.
```
<p>New Products</p>
<ul>
<li><data value="398">Mini Ketchup</data></li>
<li><data value="399">Jumbo Ketchup</data></li>
<li><data value="400">Mega Jumbo Ketchup</data></li>
</ul>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-data-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-data-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `data` | 62 | ≤18 | 22 | No | 49 | 10 | 62 | 62 | 22 | 46 | 10 | 8.0 |
See also
--------
* The HTML [`<time>`](time) element.
html <address>: The Contact Address element <address>: The Contact Address element
======================================
The `<address>` [HTML](../index) element indicates that the enclosed HTML provides contact information for a person or people, or for an organization.
Try it
------
The contact information provided by an `<address>` element's contents can take whatever form is appropriate for the context, and may include any type of contact information that is needed, such as a physical address, URL, email address, phone number, social media handle, geographic coordinates, and so forth. The `<address>` element should include the name of the person, people, or organization to which the contact information refers.
`<address>` can be used in a variety of contexts, such as providing a business's contact information in the page header, or indicating the author of an article by including an `<address>` element within the [`<article>`](article).
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* The `<address>` element can only be used to represent the contact information for its nearest [`<article>`](article) or [`<body>`](body) element ancestor.
* This element should not contain more information than the contact information, like a publication date (which belongs in a [`<time>`](time) element).
* Typically an `<address>` element can be placed inside the [`<footer>`](footer) element of the current section, if any.
Examples
--------
This example demonstrates the use of `<address>` to demarcate the contact information for an article's author.
```
<address>
You can contact author at
<a href="http://www.somedomain.com/contact"> www.somedomain.com</a>.<br />
If you see any bugs, please
<a href="mailto:[email protected]"> contact webmaster</a>.<br />
You may also want to visit us:<br />
Mozilla Foundation<br />
331 E Evelyn Ave<br />
Mountain View, CA 94041<br />
USA
</address>
```
### Result
Although it renders text with the same default styling as the [`<i>`](i) or [`<em>`](em) elements, it is more appropriate to use `<address>` when dealing with contact information, as it conveys additional semantic information.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), palpable content. |
| Permitted content | [Flow content](../content_categories#flow_content), but with no nested `<address>` element, no heading content ([`<hgroup>`](hgroup), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements)), no sectioning content ([`<article>`](article), [`<aside>`](aside), [`<section>`](section), [`<nav>`](nav)), and no [`<header>`](header) or [`<footer>`](footer) element. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content), but always excluding `<address>` elements (according to the logical principle of symmetry, if `<address>` tag, as a parent, can not have nested `<address>` element, then the same `<address>` content can not have `<address>` tag as its parent). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) Prior to Gecko 2.0 (Firefox 4), Gecko implemented this element using the [`HTMLSpanElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement) interface |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-address-element](https://html.spec.whatwg.org/multipage/sections.html#the-address-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `address` | Yes | 12 | 1 | Yes | Yes | 1 | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Others section-related elements: [`<body>`](body), [`<nav>`](nav), [`<article>`](article), [`<aside>`](aside), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<hgroup>`](hgroup), [`<footer>`](footer), [`<section>`](section), [`<header>`](header);
* [Sections and outlines of an HTML document](heading_elements).
html <rb>: The Ruby Base element <rb>: The Ruby Base element
===========================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<rb>` [HTML](../index) element is used to delimit the base text component of a [`<ruby>`](ruby) annotation, i.e. the text that is being annotated. One `<rb>` element should wrap each separate atomic segment of the base text.
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Ruby annotations are for showing pronunciation of East Asian characters, like using Japanese furigana or Taiwanese bopomofo characters. The `<rb>` element is used to separate out each segment of the ruby base text.
* Even though `<rb>` is not a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element), it is common to just include the opening tag of each element in the source code, so that the ruby markup is less complex and easier to read. The browser can then fill in the full element in the rendered version.
* You need to include one [`<rt>`](rt) element for each base segment/`<rb>` element that you want to annotate.
Examples
--------
### Using rb
In this example, we provide an annotation for the original character equivalent of "Kanji":
```
<ruby>
<rb>漢<rb>字
<rp>(</rp><rt>kan<rt>ji<rp>)</rp>
</ruby>
```
Note how we've included two `<rb>` elements, to delimit the two separate parts of the ruby base text. The annotation on the other hand is delimited by two [`<rt>`](rt) elements.
### Separate annotations
Note that we could also write this example with the two base text parts annotated completely separately. In this case we don't need to include `<rb>` elements:
```
<ruby>
漢 <rp>(</rp><rt>Kan</rt><rp>)</rp>
字 <rp>(</rp><rt>ji</rt><rp>)</rp>
</ruby>
```
See the article about the [`<ruby>`](ruby) element for further examples.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | As a child of a [`<ruby>`](ruby) element. |
| Tag omission | The end tag can be omitted if the element is immediately followed by an [`<rt>`](rt), [`<rtc>`](rtc), or [`<rp>`](rp) element or another `<rb>` element, or if there is no more content in the parent element. |
| Permitted parents | A [`<ruby>`](ruby) element. |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # rb](https://html.spec.whatwg.org/multipage/obsolete.html#rb) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `rb` | 5
Blink has support for parsing the `rb` element, but not for rendering `rb` content as expected. | 79
Blink has support for parsing the `rb` element, but not for rendering `rb` content as expected. | 38 | 5 | 15
Blink has support for parsing the `rb` element, but not for rendering `rb` content as expected. | 5
Safari has support for parsing the `rb` element, but not for rendering `rb` content as expected. | 37
Blink has support for parsing the `rb` element, but not for rendering `rb` content as expected. | 18
Blink has support for parsing the `rb` element, but not for rendering `rb` content as expected. | 38 | 14
Blink has support for parsing the `rb` element, but not for rendering `rb` content as expected. | Yes
Safari has support for parsing the `rb` element, but not for rendering `rb` content as expected. | Yes
Blink has support for parsing the `rb` element, but not for rendering `rb` content as expected. |
See also
--------
* [`<ruby>`](ruby)
* [`<rt>`](rt)
* [`<rp>`](rp)
* [`<rtc>`](rtc)
html <var>: The Variable element <var>: The Variable element
===========================
The `<var>` [HTML](../index) element represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
### Related elements
Other elements that are used in contexts in which `<var>` is commonly used include:
* [`<code>`](code): The HTML Code element
* [`<kbd>`](kbd): The HTML Keyboard input element
* [`<samp>`](samp): The HTML Sample Output element
If you encounter code that is mistakenly using `<var>` for style purposes rather than semantic purposes, you should either use a [`<span>`](span) with appropriate CSS or, an appropriate semantic element among the following:
* [`<em>`](em)
* [`<i>`](i)
* [`<q>`](q)
### Default style
Most browsers apply [`font-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) to `"italic"` when rendering `<var>`. This can be overridden in CSS, like this:
```
var {
font-style: normal;
}
```
Examples
--------
### Basic example
Here's a simple example, using `<var>` to denote variable names in a mathematical equation.
```
<p>A simple equation: <var>x</var> = <var>y</var> + 2</p>
```
The output:
### Overriding the default style
Using CSS, you can override the default style for the `<var>` element. In this example, variable names are rendered using bold Courier if it's available, otherwise it falls back to the default monospace font.
#### CSS
```
var {
font: bold 15px "Courier", "Courier New", monospace;
}
```
#### HTML
```
<p>
The variables <var>minSpeed</var> and <var>maxSpeed</var> control the minimum
and maximum speed of the apparatus in revolutions per minute (RPM).
</p>
```
This HTML uses `<var>` to enclose the names of two variables.
#### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-var-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-var-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `var` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
html <xmp> <xmp>
=====
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Summary
-------
The `<xmp>` [HTML](../index) element renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line.
**Note:** Do not use this element.
* It has been deprecated since HTML3.2 and was not implemented in a consistent way. It was completely removed from current HTML.
* Use the [`<pre>`](pre) element or, if semantically adequate, the [`<code>`](code) element instead. Note that you will need to escape the '`<`' character as '`<`' to make sure it is not interpreted as markup.
* A monospaced font can also be obtained on any element, by applying an adequate [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) style using `monospace` as the generic-font value for the [`font-family`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) property.
Attributes
----------
This element has no other attributes than the [global attributes](../global_attributes), common to all elements.
DOM interface
-------------
This element implements the [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # xmp](https://html.spec.whatwg.org/multipage/obsolete.html#xmp) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `xmp` | Yes | 12 | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes |
See also
--------
* The [`<pre>`](pre) and [`<code>`](code) elements to be used instead.
* The [`<plaintext>`](plaintext) and `<listing>` elements, similar to [`<xmp>`](xmp) but also obsolete.
| programming_docs |
html <dialog>: The Dialog element <dialog>: The Dialog element
============================
The `<dialog>` [HTML](../index) element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow.
Attributes
----------
This element includes the [global attributes](../global_attributes).
**Warning:** The `tabindex` attribute must not be used on the `<dialog>` element.
[**`open`**](#attr-open) Indicates that the dialog is active and can be interacted with. When the `open` attribute is not set, the dialog *shouldn't* be shown to the user. It is recommended to use the `.show()` or `.showModal()` methods to render dialogs, rather than the `open` attribute. If a `<dialog>` is opened using the `open` attribute, it will be non-modal.
Accessibility considerations
----------------------------
The native HTML `<dialog>` element should be used in creating modal dialogs as it provides usability and accessibility features that must be replicated if using other elements for a similar purpose. Use the appropriate `.showModal()` or `.show()` method to render dialogs. If creating a custom dialog implementation, ensure all expected default behaviors are supported and proper labeling recommendations are followed.
When implementing a dialog, it is important to consider the most appropriate place to set user focus. Explicitly indicating the initial focus placement by use of the [autofocus](../global_attributes/autofocus) attribute will help ensure initial focus is set to the element deemed the best initial focus placement for any particular dialog. When in doubt, as it may not always be known where initial focus could be set within a dialog, particularly for instances where a dialog's content is dynamically rendered when invoked, then if necessary authors may decide focusing the `<dialog>` element itself would provide the best initial focus placement. When using [`HTMLDialogElement.showModal()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal) to open a `<dialog>`, focus is set on the first nested focusable element.
Ensure a mechanism is provided to allow users to close a dialog. The most robust way to ensure all users can close a dialog is to include an explicit button to do so. For instance, a confirmation, cancel or close button as appropriate. Additionally, for those using a device with a keyboard, the `Escape` key is commonly expected to close modal dialogs as well. By default, a `<dialog>` invoked by the `showModal()` method will allow for its dismissal by the `Escape`. A non-modal dialog does not dismiss via the `Escape` key by default, and depending on what the non-modal dialog represents, it may not be desired for this behavior. If multiple modal dialogs are open, `Escape` should only close the last shown dialog. When using `<dialog>`, this behavior is provided by the browser.
The `<dialog>` element is exposed by browsers similarly to custom dialogs using the ARIA [role="dialog"](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role) attribute. `<dialog>` elements invoked by the `showModal()` method will have an implicit [aria-modal="true"](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-modal), whereas `<dialog>` elements invoked by the `show()` method, or rendered by use of the `open` attribute or changing the default `display` of a `<dialog>` will be exposed as `[aria-modal="false"]`. When implementing modal dialogs, everything other than the `<dialog>` and its contents should be rendered inert using the [`inert`](../global_attributes/inert) attribute. When using `<dialog>` along with the `HTMLDialogElement.showModal()` method, this behavior is provided by the browser.
Usage notes
-----------
* [`<form>`](form) elements can close a `<dialog>` if they have the attribute `method="dialog"` or if the button used to submit the form has `formmethod="dialog"` set. In this case, the state of the form controls are saved, not submitted, the `<dialog>` closes, and the [`returnValue`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/returnValue) property gets set to the `value` of the button that was used to save the form's state.
* The [`::backdrop`](https://developer.mozilla.org/en-US/docs/Web/CSS/::backdrop) CSS pseudo-element can be used to style the backdrop that is displayed behind a `<dialog>` element when the dialog is displayed with [`HTMLDialogElement.showModal()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal). For example, to dim unreachable content behind the modal dialog.
Examples
--------
### Simple example
The following will render a non-modal, or modal-less, dialog. The "OK" button allows the dialog to be closed when activated.
```
<dialog open>
<p>Greetings, one and all!</p>
<form method="dialog">
<button>OK</button>
</form>
</dialog>
```
Because this dialog was opened via the `open` attribute, it is non-modal. In this example, when the dialog is dismissed, no method is provided to re-open it. Opening dialogs via [`HTMLDialogElement.show()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/show) is preferred over the toggling of the boolean `open` attribute.
### Advanced example
This example opens a modal dialog when the "Show the dialog" button is activated. The dialog contains a form. Updating the value of the [`<select>`](select) updates the value of the "confirm" button.
#### HTML
```
<!-- A modal dialog containing a form -->
<dialog id="favDialog">
<form method="dialog">
<p>
<label>Favorite animal:
<select>
<option value="default">Choose…</option>
<option>Brine shrimp</option>
<option>Red panda</option>
<option>Spider monkey</option>
</select>
</label>
</p>
<div>
<button value="cancel">Cancel</button>
<button id="confirmBtn" value="default">Confirm</button>
</div>
</form>
</dialog>
<p>
<button id="showDialog">Show the dialog</button>
</p>
<output></output>
```
#### JavaScript
```
const showButton = document.getElementById('showDialog');
const favDialog = document.getElementById('favDialog');
const outputBox = document.querySelector('output');
const selectEl = favDialog.querySelector('select');
const confirmBtn = favDialog.querySelector('#confirmBtn');
// "Update details" button opens the <dialog> modally
showButton.addEventListener('click', () => {
favDialog.showModal();
});
// "Favorite animal" input sets the value of the submit button
selectEl.addEventListener('change', (e) => {
confirmBtn.value = selectEl.value;
});
// "Confirm" button of form triggers "close" on dialog because of [method="dialog"]
favDialog.addEventListener('close', () => {
outputBox.value = `ReturnValue: ${favDialog.returnValue}.`;
});
```
### Result
Note the JavaScript did not include the [`HTMLDialogElement.close()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/close) method. When a form in a dialog is submitted, if the method is `dialog`, the current state of the form is saved, not submitted, and the dialog gets closed.
It is important to provide a mechanism to close a dialog within the `dialog` element. For instance, the `Esc` key does not close non-modal dialogs by default, nor can one assume that a user will even have access to a physical keyboard (e.g., someone using a touch screen device without access to a keyboard).
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [sectioning root](heading_elements#sectioning_roots) |
| Permitted content | [Flow content](../content_categories#flow_content) |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content) |
| Implicit ARIA role | [dialog](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role) |
| Permitted ARIA roles | `[alertdialog](https://w3c.github.io/aria/#alertdialog)` |
| DOM interface | [`HTMLDialogElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-dialog-element](https://html.spec.whatwg.org/multipage/interactive-elements.html#the-dialog-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `dialog` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |
| `open` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |
See also
--------
* The [`close`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/close_event) event
* The [`cancel`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/cancel_event) event
* [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms).
* The [`::backdrop`](https://developer.mozilla.org/en-US/docs/Web/CSS/::backdrop) pseudo-element
* [dialog-polyfill](https://github.com/GoogleChrome/dialog-polyfill)
html <col>: The Table Column element <col>: The Table Column element
===============================
The `<col>` [HTML](../index) element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a [`<colgroup>`](colgroup) element.
Try it
------
`<col>` allows styling columns using CSS, but only a few properties will have an effect on the column ([see the CSS 2.1 specification](https://www.w3.org/TR/CSS21/tables.html#columns) for a list).
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`span`**](#attr-span) This attribute contains a positive integer indicating the number of consecutive columns the `<col>` element spans. If not present, its default value is `1`.
### Deprecated attributes
The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only.
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute specifies how horizontal alignment of each column cell content will be handled. Possible values are:
* `left`, aligning the content to the left of the cell
* `center`, centering the content in the cell
* `right`, aligning the content to the right of the cell
* `justify`, inserting spaces into the textual content so that the content is justified in the cell
If this attribute is not set, its value is inherited from the [`align`](colgroup#attr-align) of the [`<colgroup>`](colgroup) element this `<col>` element belongs too. If there are none, the `left` value is assumed.
**Note:** To achieve the same effect as the `left`, `center`, `right` or `justify` values, do not try to set the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property on a selector giving a `<col>` element. Because [`<td>`](td) elements are not descendant of the `<col>` element, they won't inherit it.
If the table doesn't use a [`colspan`](td#attr-colspan) attribute, use the `td:nth-child(an+b)` CSS selector. Set `a` to zero and `b` to the position of the column in the table, e.g. `td:nth-child(2) { text-align: right; }` to right-align the second column.
If the table does use a [`colspan`](td#attr-colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial.
[**`bgcolor`**](#attr-bgcolor) Deprecated
The background color of the table. It is a [6-digit hexadecimal RGB code](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors), prefixed by a '`#`'. One of the predefined [color keywords](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) can also be used.
To achieve a similar effect, use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property.
[**`char`**](#attr-char) Deprecated
This attribute is used to set the character to align the cells in a column on. Typical values for this include a period (.) when attempting to align numbers or monetary values. If [`align`](col#attr-align) is not set to `char`, this attribute is ignored.
[**`charoff`**](#attr-charoff) Deprecated
This attribute is used to indicate the number of characters to offset the column data from the alignment characters specified by the `char` attribute.
[**`valign`**](#attr-valign) Deprecated
This attribute specifies the vertical alignment of the text within each cell of the column. Possible values for this attribute are:
* `baseline`, which will put the text as close to the bottom of the cell as it is possible, but align it on the [baseline](https://en.wikipedia.org/wiki/Baseline_%28typography%29) of the characters instead of the bottom of them. If characters are all of the size, this has the same effect as `bottom`.
* `bottom`, which will put the text as close to the bottom of the cell as it is possible;
* `middle`, which will center the text in the cell;
* and `top`, which will put the text as close to the top of the cell as it is possible.
**Note:** Do not try to set the [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property on a selector giving a `<col>` element. Because [`<td>`](td) elements are not descendant of the `<col>` element, they won't inherit it.
If the table doesn't use a [`colspan`](td#attr-colspan) attribute, use the `td:nth-child(an+b)` CSS selector where 'a' is the total number of the columns in the table and 'b' is the ordinal position of the column in the table. Only after this selector the `vertical-align` property can be used.
If the table does use a [`colspan`](td#attr-colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial.
[**`width`**](#attr-width) Deprecated
This attribute specifies a default width for each column in the current column group. In addition to the standard pixel and percentage values, this attribute might take the special form `0*`, which means that the width of each column in the group should be the minimum width necessary to hold the column's contents. Relative widths such as `5*` also can be used.
Examples
--------
Please see the [`<table>`](table) page for examples on `<col>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | It must have start tag, but must not have an end tag. |
| Permitted parents | [`<colgroup>`](colgroup) only, though it can be implicitly defined as its start tag is not mandatory. The [`<colgroup>`](colgroup) must not have a [`span`](colgroup#attr-span) attribute. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLTableColElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-col-element](https://html.spec.whatwg.org/multipage/tables.html#the-col-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `col` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `char` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `charoff` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `span` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `valign` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `width` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* CSS properties and pseudo-classes that may be specially useful to style the `<col>` element:
+ the [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property to control the width of the column;
+ the [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child) pseudo-class to set the alignment on the cells of the column;
+ the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to align all cells content on the same character, like '.'.
html <hgroup> <hgroup>
========
The `<hgroup>` [HTML](../index) element represents a heading and related content. It groups a single [`<h1>–<h6>`](heading_elements) element with one or more [`<p>`](p).
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
The `<hgroup>` element allows the grouping of a heading with any secondary content, such as subheadings, an alternative title, or tagline. Each of these types of content represented as a `<p>` element within the `<hgroup>`.
The `<hgroup>` itself has no impact on the document outline of a web page. Rather, the single allowed heading within the `<hgroup>` contributes to the document outline.
Examples
--------
```
<!DOCTYPE html>
<title>HTML Standard</title>
<body>
<hgroup id="document-title">
<h1>HTML: Living Standard</h1>
<p>Last Updated 12 July 2022</p>
</hgroup>
<p>Some intro to the document.</p>
<h2>Table of contents</h2>
<ol id="toc">
…
</ol>
<h2>First section</h2>
<p>Some intro to the first section.</p>
</body>
```
Accessibility concerns
----------------------
The `<hgroup>` presently has no strong accessibility semantics. The content of the element (a heading and optional paragraphs) is what is exposed by browser accessibility APIs.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), heading content, palpable content. |
| Permitted content | Zero or more [`<p>`](p) elements, followed by one [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), or [`<h6>`](heading_elements) element, followed by zero or more [`<p>`](p) elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-hgroup-element](https://html.spec.whatwg.org/multipage/sections.html#the-hgroup-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `hgroup` | 5 | 12 | 4 | 9 | 11.1 | 5 | 2.2 | Yes | 4 | 11.1 | 4.2 | Yes |
See also
--------
* Others section-related elements: [`<body>`](body), [`<article>`](article), [`<section>`](section), [`<aside>`](aside), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<nav>`](nav), [`<header>`](header), [`<footer>`](footer), [`<address>`](address);
* [Sections and outlines of an HTML document](heading_elements).
| programming_docs |
html <rt>: The Ruby Text element <rt>: The Ruby Text element
===========================
The `<rt>` [HTML](../index) element specifies the ruby text component of a ruby annotation, which is used to provide pronunciation, translation, or transliteration information for East Asian typography. The `<rt>` element must always be contained within a [`<ruby>`](ruby) element.
Try it
------
See the article about the [`<ruby>`](ruby) element for more examples.
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
### Using ruby annotations
This simple example provides Romaji transliteration for the kanji characters within the [`<ruby>`](ruby) element:
```
<ruby>
漢 <rt>Kan</rt>
字 <rt>ji</rt>
</ruby>
```
The output looks like this in your browser:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | The end tag may be omitted if the `<rt>` element is immediately followed by an `<rt>` or [`<rp>`](rp) element, or if there is no more content in the parent element |
| Permitted parents | A [`<ruby>`](ruby) element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-rt-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-rt-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `rt` | 5 | 79 | 38 | 5 | 15 | 5 | Yes | Yes | 38 | 14 | Yes | Yes |
See also
--------
* [`<ruby>`](ruby)
* [`<rp>`](rp)
* [`<rb>`](rb)
* [`<rtc>`](rtc)
* [`text-transform: full-size-kana`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform)
html <dd>: The Description Details element <dd>: The Description Details element
=====================================
The `<dd>` [HTML](../index) element provides the description, definition, or value for the preceding term ([`<dt>`](dt)) in a description list ([`<dl>`](dl)).
Try it
------
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`nowrap`**](#attr-nowrap) Non-standard Deprecated
If the value of this attribute is set to `yes`, the definition text will not wrap. The default value is `no`.
Examples
--------
For examples, see the [examples provided for the `<dl>` element](dl#examples).
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | The start tag is required. The end tag may be omitted if this element is immediately followed by another `<dd>` element or a [`<dt>`](dt) element, or if there is no more content in the parent element. |
| Permitted parents | A [`<dl>`](dl) or a [`<div>`](div) that is a child of a [`<dl>`](dl).This element can be used after a [`<dt>`](dt) or another [`<dd>`](dd) element. |
| Implicit ARIA role | `[definition](https://w3c.github.io/aria/#definition)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-dd-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-dd-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `dd` | Yes | 12 | 1
Before Firefox 4, this element was implemented using the `HTMLSpanElement` interface instead of `HTMLElement`. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `nowrap` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<dl>`](dl)
* [`<dt>`](dt)
html <hr>: The Thematic Break (Horizontal Rule) element <hr>: The Thematic Break (Horizontal Rule) element
==================================================
The `<hr>` [HTML](../index) element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section.
Try it
------
Historically, this has been presented as a horizontal rule or line. While it may still be displayed as a horizontal rule in visual browsers, this element is now defined in semantic terms, rather than presentational terms, so if you wish to draw a horizontal line, you should do so using appropriate CSS.
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`align`**](#attr-align) Deprecated Non-standard
Sets the alignment of the rule on the page. If no value is specified, the default value is `left`.
[**`color`**](#attr-color) Deprecated Non-standard
Sets the color of the rule through color name or hexadecimal value.
[**`noshade`**](#attr-noshade) Deprecated Non-standard
Sets the rule to have no shading.
[**`size`**](#attr-size) Deprecated Non-standard
Sets the height, in pixels, of the rule.
[**`width`**](#attr-width) Deprecated Non-standard
Sets the length of the rule on the page through a pixel or percentage value.
Example
-------
### HTML
```
<p>
This is the first paragraph of text. This is the first paragraph of text. This
is the first paragraph of text. This is the first paragraph of text.
</p>
<hr />
<p>
This is the second paragraph of text. This is the second paragraph of text.
This is the second paragraph of text. This is the second paragraph of text.
</p>
```
### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content). |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | It must have start tag, but must not have an end tag. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | `[separator](https://w3c.github.io/aria/#separator)` |
| Permitted ARIA roles | `[presentation](https://w3c.github.io/aria/#presentation)` or `[none](https://w3c.github.io/aria/#none)` |
| DOM interface | [`HTMLHRElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHRElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-hr-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-hr-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `hr` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `color` | 33 | 12 | 1 | ≤6 | 20 | 10.1 | 4.4.3 | 33 | 4 | 20 | 10.3 | 2.0 |
| `noshade` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `size` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `width` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
See also
--------
* [`<p>`](p)
html <tfoot>: The Table Foot element <tfoot>: The Table Foot element
===============================
The `<tfoot>` [HTML](../index) element defines a set of rows summarizing the columns of the table.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
### Deprecated attributes
The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only.
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute specifies how horizontal alignment of each cell content will be handled. Possible values are:
* `left`, aligning the content to the left of the cell
* `center`, centering the content in the cell
* `right`, aligning the content to the right of the cell
* `justify`, inserting spaces into the textual content so that the content is justified in the cell
* `char`, aligning the textual content on a special character with a minimal offset, defined by the [`char`](tfoot#attr-char) and [`charoff`](tfoot#attr-charoff) attributes.
If this attribute is not set, the `left` value is assumed.
**Note:**
* To achieve the same effect as the `left`, `center`, `right` or `justify` values, use the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property on it.
* To achieve the same effect as the `char` value, in CSS, you can use the value of the [`char`](tfoot#attr-char) as the value of the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property Unimplemented.
[**`bgcolor`**](#attr-bgcolor) Deprecated
The background color of the table. It is a [6-digit hexadecimal RGB code](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors), prefixed by a '`#`'. One of the predefined [color keywords](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) can also be used.
To achieve a similar effect, use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property.
[**`char`**](#attr-char) Deprecated
This attribute specifies the alignment of the content in a column to a character. Typical values for this include a period (.) when attempting to align numbers or monetary values. If [`align`](tfoot#attr-align) is not set to `char`, this attribute is ignored.
[**`charoff`**](#attr-charoff) Deprecated
This attribute is used to indicate the number of characters to offset the column data from the alignment characters specified by the `char` attribute.
[**`valign`**](#attr-valign) Deprecated
This attribute specifies the vertical alignment of the text within each row of cells of the table footer. Possible values for this attribute are:
* `baseline`, which will put the text as close to the bottom of the cell as it is possible, but align it on the [baseline](https://en.wikipedia.org/wiki/Baseline_%28typography%29) of the characters instead of the bottom of them. If characters are all of the size, this has the same effect as `bottom`.
* `bottom`, which will put the text as close to the bottom of the cell as it is possible;
* `middle`, which will center the text in the cell;
* and `top`, which will put the text as close to the top of the cell as it is possible.
**Note:** Do not use this attribute as it is obsolete (and not supported) in the latest standard: instead set the CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property on it.
Examples
--------
Please see the [`<table>`](table) page for examples on `<tfoot>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | Zero or more [`<tr>`](tr) elements. |
| Tag omission | The start tag is mandatory. The end tag may be omitted if there is no more content in the parent [`<table>`](table) element. |
| Permitted parents | A [`<table>`](table) element. The [`<tfoot>`](tfoot) must appear after any [`<caption>`](caption), [`<colgroup>`](colgroup), [`<thead>`](thead), [`<tbody>`](tbody), or [`<tr>`](tr) element. Note that this is the requirement in HTML.Originally, in HTML4, the opposite was true: the [`<tfoot>`](tfoot) element could not be placed after any [`<tbody>`](tbody) or [`<tr>`](tr) element. |
| Implicit ARIA role | `[rowgroup](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/rowgroup_role)` |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLTableSectionElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableSectionElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-tfoot-element](https://html.spec.whatwg.org/multipage/tables.html#the-tfoot-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `tfoot` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `char` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `charoff` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `valign` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
See also
--------
* Other table-related HTML Elements: [`<caption>`](caption), [`<col>`](col), [`<colgroup>`](colgroup), [`<table>`](table), [`<tbody>`](tbody), [`<td>`](td), [`<th>`](th), [`<thead>`](thead), [`<tr>`](tr);
* CSS properties and pseudo-classes that may be specially useful to style the `<tfoot>` element:
+ the [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child) pseudo-class to set the alignment on the cells of the column;
+ the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to align all cells content on the same character, like '.'.
html <ol>: The Ordered List element <ol>: The Ordered List element
==============================
The `<ol>` [HTML](../index) element represents an ordered list of items — typically rendered as a numbered list.
Try it
------
Attributes
----------
This element also accepts the [global attributes](../global_attributes).
[**`reversed`**](#attr-reversed) This Boolean attribute specifies that the list's items are in reverse order. Items will be numbered from high to low.
[**`start`**](#attr-start) An integer to start counting from for the list items. Always an Arabic numeral (1, 2, 3, etc.), even when the numbering `type` is letters or Roman numerals. For example, to start numbering elements from the letter "d" or the Roman numeral "iv," use `start="4"`.
[**`type`**](#attr-type) Sets the numbering type:
* `a` for lowercase letters
* `A` for uppercase letters
* `i` for lowercase Roman numerals
* `I` for uppercase Roman numerals
* `1` for numbers (default)
The specified type is used for the entire list unless a different [`type`](li#attr-type) attribute is used on an enclosed [`<li>`](li) element.
**Note:** Unless the type of the list number matters (like legal or technical documents where items are referenced by their number/letter), use the CSS [`list-style-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type) property instead.
Usage notes
-----------
Typically, ordered list items display with a preceding [marker](https://developer.mozilla.org/en-US/docs/Web/CSS/::marker), such as a number or letter.
The `<ol>` and [`<ul>`](ul) elements may nest as deeply as desired, alternating between `<ol>` and `<ul>` however you like.
The `<ol>` and [`<ul>`](ul) elements both represent a list of items. The difference is with the `<ol>` element, the order is meaningful. For example:
* Steps in a recipe
* Turn-by-turn directions
* The list of ingredients in decreasing proportion on nutrition information labels
To determine which list to use, try changing the order of the list items; if the meaning changes, use the `<ol>` element — otherwise you can use [`<ul>`](ul).
Examples
--------
### Simple example
```
<ol>
<li>Fee</li>
<li>Fi</li>
<li>Fo</li>
<li>Fum</li>
</ol>
```
The above HTML will output:
### Using Roman Numeral type
```
<ol type="i">
<li>Introduction</li>
<li>List of Grievances</li>
<li>Conclusion</li>
</ol>
```
The above HTML will output:
### Using the start attribute
```
<p>Finishing places of contestants not in the winners' circle:</p>
<ol start="4">
<li>Speedwalk Stu</li>
<li>Saunterin' Sam</li>
<li>Slowpoke Rodriguez</li>
</ol>
```
The above HTML will output:
### Nesting lists
```
<ol>
<li>first item</li>
<li>
second item
<!-- closing </li> tag is not here! -->
<ol>
<li>second item first subitem</li>
<li>second item second subitem</li>
<li>second item third subitem</li>
</ol>
</li>
<!-- Here's the closing </li> tag -->
<li>third item</li>
</ol>
```
The above HTML will output:
### Unordered list inside ordered list
```
<ol>
<li>first item</li>
<li>
second item
<!-- closing </li> tag is not here! -->
<ul>
<li>second item first subitem</li>
<li>second item second subitem</li>
<li>second item third subitem</li>
</ul>
</li>
<!-- Here's the closing </li> tag -->
<li>third item</li>
</ol>
```
The above HTML will output:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), and if the `<ol>` element's children include at least one [`<li>`](li) element, [palpable content](../content_categories#palpable_content). |
| Permitted content | Zero or more [`<li>`](li), [`<script>`](script) and [`<template>`](template) elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | `[list](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/list_role)` |
| Permitted ARIA roles | `[directory](https://w3c.github.io/aria/#directory)`, `[group](https://w3c.github.io/aria/#group)`, `[listbox](https://w3c.github.io/aria/#listbox)`, `[menu](https://w3c.github.io/aria/#menu)`, `[menubar](https://w3c.github.io/aria/#menubar)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[radiogroup](https://w3c.github.io/aria/#radiogroup)`, `[tablist](https://w3c.github.io/aria/#tablist)`, `[toolbar](https://w3c.github.io/aria/#toolbar)`, `[tree](https://w3c.github.io/aria/#tree)` |
| DOM interface | [`HTMLOListElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-ol-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-ol-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ol` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `compact` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `reversed` | 18 | ≤79 | 18 | No | Yes | 6 | Yes | Yes | 18 | Yes | Yes | Yes |
| `start` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Other list-related HTML Elements: [`<ul>`](ul), [`<li>`](li), [`<menu>`](menu)
* CSS properties that may be specially useful to style the `<ol>` element:
+ the [`list-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style) property, to choose the way the ordinal displays
+ [CSS counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters), to handle complex nested lists
+ the [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) property, to simulate the deprecated [`compact`](ol#attr-compact) attribute
+ the [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) property, to control the list indentation
| programming_docs |
html <applet>: The Embed Java Applet element <applet>: The Embed Java Applet element
=======================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The obsolete **HTML Applet Element** (`<applet>`) embeds a Java applet into the document; this element has been deprecated in favor of [`<object>`](object).
Use of Java applets on the Web is deprecated; most browsers no longer support use of plug-ins, including the Java plug-in.
Attributes
----------
[**`align`**](#attr-align) Deprecated
This attribute is used to position the applet on the page relative to content that might flow around it. The HTML 4.01 specification defines values of `bottom`, `left`, `middle`, `right`, and `top`, whereas Microsoft and Netscape also might support `absbottom`, `absmiddle`, `baseline`, `center`, and `texttop`.
[**`alt`**](#attr-alt) Deprecated
This attribute causes a descriptive text alternate to be displayed on browsers that do not support Java. Page designers should also remember that content enclosed within the `<applet>` element may also be rendered as alternative text.
[**`archive`**](#attr-archive) Deprecated
This attribute refers to an archived or compressed version of the applet and its associated class files, which might help reduce download time.
[**`code`**](#attr-code) Deprecated
This attribute specifies the URL of the applet's class file to be loaded and executed. Applet filenames are identified by a .class filename extension. The URL specified by code might be relative to the `codebase` attribute.
[**`codebase`**](#attr-codebase) Deprecated
This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
[**`datafld`**](#attr-datafld) Deprecated
This attribute, supported by Internet Explorer 4 and higher, specifies the column name from the data source object that supplies the bound data. This attribute might be used to specify the various [`<param>`](param) elements passed to the Java applet.
[**`datasrc`**](#attr-datasrc) Deprecated
Like `datafld`, this attribute is used for data binding under Internet Explorer 4. It indicates the id of the data source object that supplies the data that is bound to the [`<param>`](param) elements associated with the applet.
[**`height`**](#attr-height) Deprecated
This attribute specifies the height, in pixels, that the applet needs.
[**`hspace`**](#attr-hspace) Deprecated
This attribute specifies additional horizontal space, in pixels, to be reserved on either side of the applet.
[**`mayscript`**](#attr-mayscript) Deprecated
In the Netscape implementation, this attribute allows access to an applet by programs in a scripting language embedded in the document.
[**`name`**](#attr-name) Deprecated
This attribute assigns a name to the applet so that it can be identified by other resources; particularly scripts.
[**`object`**](#attr-object) Deprecated
This attribute specifies the URL of a serialized representation of an applet.
[**`src`**](#attr-src) Deprecated
As defined for Internet Explorer 4 and higher, this attribute specifies a URL for an associated file for the applet. The meaning and use is unclear and not part of the HTML standard.
[**`vspace`**](#attr-vspace) Deprecated
This attribute specifies additional vertical space, in pixels, to be reserved above and below the applet.
[**`width`**](#attr-width) Deprecated
This attribute specifies in pixels the width that the applet needs.
Example
-------
### HTML
```
<applet
code="game.class"
align="left"
archive="game.zip"
height="250"
width="350">
<param name="difficulty" value="easy" />
<p>Sorry, you need Java to play this game.</p>
</applet>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [embedded content](../content_categories#embedded_content), interactive content, palpable content. |
| Permitted content | Zero or more [`<param>`](param) elements, then [transparent](../content_categories#transparent_content_model). |
| Tag omission | None; both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [embedded content](../content_categories#embedded_content). |
| DOM interface | `HTMLAppletElement` |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # applet](https://html.spec.whatwg.org/multipage/obsolete.html#applet) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `applet` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes
Removal in Safari is [under consideration](https://webkit.org/b/157926). | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `align` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `alt` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `archive` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `code` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `codebase` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `datafld` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `datasrc` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `height` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `hspace` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `mayscript` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `name` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `object` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `src` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `vspace` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
| `width` | Yes-47 | 12-79 | Yes-56 | Yes | Yes-34 | Yes | No | Yes-47 | Yes-56 | Yes-34 | No | Yes-5.0 |
html <slot>: The Web Component Slot element <slot>: The Web Component Slot element
======================================
The `<slot>` [HTML](../index) element—part of the [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`name`**](#attr-name) The slot's name.
A ***named slot*** is a `<slot>` element with a `name` attribute.
Examples
--------
```
<template id="element-details-template">
<style>
details {
font-family: "Open Sans Light", Helvetica, Arial, sans-serif;
}
.name {
font-weight: bold;
color: #217ac0;
font-size: 120%;
}
h4 {
margin: 10px 0 -8px 0;
background: #217ac0;
color: white;
padding: 2px 6px;
border: 1px solid #cee9f9;
border-radius: 4px;
}
.attributes {
margin-left: 22px;
font-size: 90%;
}
.attributes p {
margin-left: 16px;
font-style: italic;
}
</style>
<details>
<summary>
<code class="name"><<slot name="element-name">NEED NAME</slot>></code>
<span class="desc"><slot name="description">NEED DESCRIPTION</slot></span>
</summary>
<div class="attributes">
<h4>Attributes</h4>
<slot name="attributes"><p>None</p></slot>
</div>
</details>
<hr />
</template>
```
**Note:** You can see this complete example in action at [element-details](https://github.com/mdn/web-components-examples/tree/main/element-details) (see it [running live](https://mdn.github.io/web-components-examples/element-details/)). In addition, you can find an explanation at [Using templates and slots](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots).
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content) |
| Permitted content | [Transparent](../content_categories#transparent_content_model) |
| Events | [`slotchange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement/slotchange_event) |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content) |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLSlotElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-slot-element](https://html.spec.whatwg.org/multipage/scripting.html#the-slot-element) |
| [DOM Standard # shadow-tree-slots](https://dom.spec.whatwg.org/#shadow-tree-slots) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `slot` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `name` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
html <area>: The Image Map Area element <area>: The Image Map Area element
==================================
The `<area>` [HTML](../index) element defines an area inside an image map that has predefined clickable areas. An *image map* allows geometric areas on an image to be associated with [hypertext links](https://developer.mozilla.org/en-US/docs/Glossary/Hyperlink).
This element is used only within a [`<map>`](map) element.
Try it
------
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`alt`**](#attr-alt) A text string alternative to display on browsers that do not display images. The text should be phrased so that it presents the user with the same kind of choice as the image would offer when displayed without the alternative text. This attribute is required only if the [`href`](area#attr-href) attribute is used.
[**`coords`**](#attr-coords) The `coords` attribute details the coordinates of the [`shape`](#attr-shape) attribute in size, shape, and placement of an `<area>`. This attribute must not be used if `shape` is set to `default`.
* `rect`: the value is `x1,y1,x2,y2`. The value specifies the coordinates of the top-left and bottom-right corner of the rectangle. For example, in `<area shape="rect" coords="0,0,253,27" href="#" target="_blank" alt="Mozilla">` the coordinates are `0,0` and `253,27`, indicating the top-left and bottom-right corners of the rectangle, respectively.
* `circle`: the value is `x,y,radius`. Value specifies the coordinates of the circle center and the radius. For example: `<area shape="circle" coords="130,136,60" href="#" target="_blank" alt="MDN">`
* `poly`: the value is `x1,y1,x2,y2,..,xn,yn`. Value specifies the coordinates of the edges of the polygon. If the first and last coordinate pairs are not the same, the browser will add the last coordinate pair to close the polygon
The values are numbers of CSS pixels.
[**`download`**](#attr-download) This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. See [`<a>`](a) for a full description of the [`download`](a#attr-download) attribute.
[**`href`**](#attr-href) The hyperlink target for the area. Its value is a valid URL. This attribute may be omitted; if so, the `<area>` element does not represent a hyperlink.
[**`hreflang`**](#attr-hreflang) Deprecated
Indicates the language of the linked resource. Allowed values are defined by [RFC 5646: Tags for Identifying Languages (also known as BCP 47)](https://datatracker.ietf.org/doc/html/rfc5646). Use this attribute only if the [`href`](area#attr-href) attribute is present.
[**`ping`**](#attr-ping) Contains a space-separated list of URLs to which, when the hyperlink is followed, [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) requests with the body `PING` will be sent by the browser (in the background). Typically used for tracking.
[**`referrerpolicy`**](#attr-referrerpolicy) A string indicating which referrer to use when fetching the resource:
* `no-referrer`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent.
* `no-referrer-when-downgrade`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent to [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)s without [TLS](https://developer.mozilla.org/en-US/docs/Glossary/TLS) ([HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS)).
* `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL), [host](https://developer.mozilla.org/en-US/docs/Glossary/Host), and [port](https://developer.mozilla.org/en-US/docs/Glossary/Port).
* `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
* `same-origin`: A referrer will be sent for [same origin](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy), but cross-origin requests will contain no referrer information.
* `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
* `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
* `unsafe-url`: The referrer will include the origin *and* the path (but not the [fragment](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins.
[**`rel`**](#attr-rel) For anchors containing the [`href`](area#attr-href) attribute, this attribute specifies the relationship of the target object to the link object. The value is a space-separated list of [link types values](../link_types). The values and their semantics will be registered by some authority that might have meaning to the document author. The default relationship, if no other is given, is void. Use this attribute only if the [`href`](area#attr-href) attribute is present.
[**`shape`**](#attr-shape) The shape of the associated hot spot. The specifications for HTML defines the values `rect`, which defines a rectangular region; `circle`, which defines a circular region; `poly`, which defines a polygon; and `default`, which indicates the entire region beyond any defined shapes.
[**`target`**](#attr-target) A keyword or author-defined name of the [browsing context](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context) to display the linked resource. The following keywords have special meanings:
* `_self` (default): Show the resource in the current browsing context.
* `_blank`: Show the resource in a new, unnamed browsing context.
* `_parent`: Show the resource in the parent browsing context of the current one, if the current page is inside a frame. If there is no parent, acts the same as `_self`.
* `_top`: Show the resource in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). If there is no parent, acts the same as `_self`.
Use this attribute only if the [`href`](area#attr-href) attribute is present.
**Note:** Setting `target="_blank"` on `<area>` elements implicitly provides the same `rel` behavior as setting [`rel="noopener"`](../link_types/noopener) which does not set `window.opener`. See [browser compatibility](#browser_compatibility) for support status.
### Deprecated attributes
[**`name`**](#attr-name) Deprecated
Define a names for the clickable area so that it can be scripted by older browsers.
[**`nohref`**](#attr-nohref) Deprecated
Indicates that no hyperlink exists for the associated area.
**Note:** The `nohref` attribute is not necessary, as omitting the `href` attribute is sufficient.
[**`type`**](#attr-type) Deprecated
Hint for the type of the referenced resource. Ignored by browsers.
Examples
--------
```
<map name="primary">
<area
shape="circle"
coords="75,75,75"
href="left.html"
alt="Click to go Left" />
<area
shape="circle"
coords="275,75,75"
href="right.html"
alt="Click to go Right" />
</map>
<img
usemap="#primary"
src="https://via.placeholder.com/350x150"
alt="350 x 150 pic" />
```
### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content). |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | Must have a start tag and must not have an end tag. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). The `<area>` element must have an ancestor [`<map>`](map), but it need not be a direct parent. |
| Implicit ARIA role | `[link](https://w3c.github.io/aria/#link)` when [`href`](area#attr-href) attribute is present, otherwise [no corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLAreaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAreaElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-area-element](https://html.spec.whatwg.org/multipage/image-maps.html#the-area-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `area` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `accesskey` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `alt` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `coords` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `download` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `href` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `hreflang` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `implicit_noopener` | 88 | 88 | 79 | No | No | 12.1 | No | 88 | 79 | Yes | 12.2 | 15.0 |
| `media` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `name` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `nohref` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `ping` | 12 | 17 | Yes | No | 15 | 6 | ≤37 | 18 | No | 14 | 6 | 1.0 |
| `referrerpolicy` | 51 | 79 | 50 | No | 38 | 11.1 | 51 | 51 | 50 | 41 | No | 7.2 |
| `rel` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `shape` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `tabindex` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `target` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| programming_docs |
html <sub>: The Subscript element <sub>: The Subscript element
============================
The `<sub>` [HTML](../index) element specifies inline text which should be displayed as subscript for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
The `<sub>` element should be used only for typographical reasons—that is, to change the position of the text to comply with typographical conventions or standards, rather than solely for presentation or appearance purposes.
For example, using `<sub>` to style the name of a company which uses altered baselines in their [wordmark](https://en.wikipedia.org/wiki/Wordmark) would not be appropriate; instead, CSS should be used. For example, you could use the [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property with a declaration like `vertical-align: sub` or, to more precisely control the baseline shift, `vertical-align: -25%`.
Appropriate use cases for `<sub>` include (but aren't necessarily limited to):
* Marking up footnote numbers. See [Footnote numbers](#footnote_numbers) for an example.
* Marking up the subscript in mathematical variable numbers (although you may also consider using a [MathML](https://developer.mozilla.org/en-US/docs/Web/MathML) formula for this). See [Variable subscripts](#variable_subscripts).
* Denoting the number of atoms of a given element within a chemical formula (such as every developer's best friend, C 8 H 10 N 4 O 2 , otherwise known as "caffeine"). See [Chemical formulas](#chemical_formulas).
Examples
--------
### Footnote numbers
Traditional footnotes are denoted using numbers which are rendered in subscript. This is a common use case for `<sub>`:
```
<p>
According to the computations by Nakamura, Johnson, and Mason<sub>1</sub> this
will result in the complete annihilation of both particles.
</p>
```
The resulting output looks like this:
### Variable subscripts
In mathematics, families of variables related to the same concept (such as distances along the same axis) are represented using the same variable name with a subscript following. For example:
```
<p>
The horizontal coordinates' positions along the X-axis are represented as
<var>x<sub>1</sub></var> … <var>x<sub>n</sub></var>.
</p>
```
The resulting output:
### Chemical formulas
When writing a chemical formula, such as H20, the number of atoms of a given element within the described molecule is represented using a subscripted number; in the case of water, the subscripted "2" indicates that there are two atoms of hydrogen in the molecule.
Another example:
```
<p>
Almost every developer's favorite molecule is
C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>, which is commonly known
as "caffeine."
</p>
```
The output:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-sub-and-sup-elements](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-sub-and-sup-elements) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `sub` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The [`<sup>`](sup) HTML element that produces superscript. Note that you cannot use `sup` and `sub` both at the same time: you need to use [MathML](https://developer.mozilla.org/en-US/docs/Web/MathML) to produce both a superscript directly above a subscript next to the chemical symbol of an element, representing its atomic number and its nuclear number.
* The [`<msub>`](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/msub), [`<msup>`](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/msup), and [`<msubsup>`](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/msubsup) MathML elements.
* The CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property.
html <figcaption>: The Figure Caption element <figcaption>: The Figure Caption element
========================================
The `<figcaption>` [HTML](../index) element represents a caption or legend describing the rest of the contents of its parent [`<figure>`](figure) element.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
Please see the [`<figure>`](figure) page for examples on `<figcaption>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | A [`<figure>`](figure) element; the `<figcaption>` element must be its first or last child. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[group](https://w3c.github.io/aria/#group)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)` |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-figcaption-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-figcaption-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `figcaption` | 8 | 12 | 4 | 9 | 11 | 5.1 | Yes | Yes | 4 | 11 | 5 | Yes |
See also
--------
* The [`<figure>`](figure) element.
html <samp>: The Sample Output element <samp>: The Sample Output element
=================================
The `<samp>` [HTML](../index) element is used to enclose inline text which represents sample (or quoted) output from a computer program. Its contents are typically rendered using the browser's default monospaced font (such as [Courier](https://en.wikipedia.org/wiki/Courier_(typeface)) or Lucida Console).
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
You can use a CSS rule to override the browser's default font face for the `<samp>` element; however, it's possible that the browser's preferences may take precedence over any CSS you specify.
The CSS to override the default font face would look like this:
```
samp {
font-family: "Courier";
}
```
**Note:** If you need an element which will serve as a container for output generated by your website or app's JavaScript code, you should instead use the [`<output>`](output) element.
Examples
--------
### Basic example
In this simple example, a paragraph includes an example of the output of a program.
```
<p>
When the process is complete, the utility will output the text
<samp>Scan complete. Found <em>N</em> results.</samp> You can then proceed to
the next step.
</p>
```
The resulting output looks like this:
### Sample output including user input
You can nest the [`<kbd>`](kbd) element within a `<samp>` block to present an example that includes text entered by the user. For example, consider this text presenting a transcript of a Linux (or macOS) console session:
#### HTML
```
<pre>
<samp><span class="prompt">mike@interwebz:~$</span> <kbd>md5 -s "Hello world"</kbd>
MD5 ("Hello world") = 3e25960a79dbc69b674cd4ec67a72c62
<span class="prompt">mike@interwebz:~$</span> <span class="cursor">█</span></samp></pre>
```
Note the use of [`<span>`](span) to allow customization of the appearance of specific portions of the sample text such as the shell prompts and the cursor. Note also the use of `<kbd>` to represent the command the user entered at the prompt in the sample text.
#### CSS
The CSS that achieves the appearance we want is:
```
.prompt {
color: #b00;
}
samp > kbd {
font-weight: bold;
}
.cursor {
color: #00b;
}
```
This gives the prompt and cursor fairly subtle colorization and emboldens the keyboard input within the sample text.
#### Result
The resulting output is this:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-samp-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-samp-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `samp` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Related elements: [`<kbd>`](kbd), [`<code>`](code), [`<pre>`](pre)
* The [`<output>`](output) element: a container for script-generated output
html <s>: The Strikethrough element <s>: The Strikethrough element
==============================
The `<s>` [HTML](../index) element renders text with a strikethrough, or a line through it. Use the `<s>` element to represent things that are no longer relevant or no longer accurate. However, `<s>` is not appropriate when indicating document edits; for that, use the [`<del>`](del) and [`<ins>`](ins) elements, as appropriate.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Phrasing content](../content_categories#phrasing_content), [flow content](../content_categories#flow_content). |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
```
.sold-out {
text-decoration: line-through;
}
```
```
<s>Today's Special: Salmon</s> SOLD OUT<br />
<span class="sold-out">Today's Special: Salmon</span> SOLD OUT
```
Accessibility concerns
----------------------
The presence of the `s` element is not announced by most screen reading technology in its default configuration. It can be made to be announced by using the CSS [`content`](https://developer.mozilla.org/en-US/docs/Web/CSS/content) property, along with the [`::before`](https://developer.mozilla.org/en-US/docs/Web/CSS/::before) and [`::after`](https://developer.mozilla.org/en-US/docs/Web/CSS/::after) pseudo-elements.
```
s::before,
s::after {
clip-path: inset(100%);
clip: rect(1px, 1px, 1px, 1px);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
s::before {
content: " [start of stricken text] ";
}
s::after {
content: " [end of stricken text] ";
}
```
Some people who use screen readers deliberately disable announcing content that creates extra verbosity. Because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has been struck out would adversely affect understanding.
* [Short note on making your mark (more accessible) | The Paciello Group](https://www.tpgi.com/short-note-on-making-your-mark-more-accessible/)
* [Tweaking Text Level Styles | Adrian Roselli](https://adrianroselli.com/2017/12/tweaking-text-level-styles.html)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-s-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-s-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `s` | Yes | 12 | 1
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The [`<strike>`](strike) element, alter ego of the [`<s>`](s) element is obsolete and should not be used on websites anymore.
* The [`<del>`](del) element is to be used instead if the data has been *deleted*.
* The CSS [`text-decoration-line`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-line) property is to be used to achieve the former visual aspect of the [`<s>`](s) element.
html <style>: The Style Information element <style>: The Style Information element
======================================
The `<style>` [HTML](../index) element contains style information for a document, or part of a document. It contains CSS, which is applied to the contents of the document containing the `<style>` element.
Try it
------
The `<style>` element must be included inside the [`<head>`](head) of the document. In general, it is better to put your styles in external stylesheets and apply them using [`<link>`](link) elements.
If you include multiple `<style>` and `<link>` elements in your document, they will be applied to the DOM in the order they are included in the document — make sure you include them in the correct order, to avoid unexpected cascade issues.
In the same manner as `<link>` elements, `<style>` elements can include `media` attributes that contain [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries), allowing you to selectively apply internal stylesheets to your document depending on media features such as viewport width.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`media`**](#attr-media) This attribute defines which media the style should be applied to. Its value is a [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries), which defaults to `all` if the attribute is missing.
[**`nonce`**](#attr-nonce) A cryptographic nonce (number used once) used to allow inline styles in a [style-src Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial.
[**`title`**](#attr-title) This attribute specifies [alternative style sheet](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets) sets.
[**`blocking`**](#attr-blocking) This attribute explicitly indicates that certain operations should be blocked on the fetching of critical subresources. [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import)-ed stylesheets are generally considered as critical subresources, whereas [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image) and fonts are not.
* `render`: The rendering of content on the screen is blocked.
### Deprecated attributes
[**`type`**](#attr-type) Deprecated
This attribute should not be provided: if it is, the only permitted values are the empty string or a case-insensitive match for `text/css`.
Examples
--------
### A simple stylesheet
In the following example, we apply a very simple stylesheet to a document:
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Test page</title>
<style>
p {
color: red;
}
</style>
</head>
<body>
<p>This is my paragraph.</p>
</body>
</html>
```
### Multiple style elements
In this example we've included two `<style>` elements — notice how the conflicting declarations in the later `<style>` element override those in the earlier one, if they have equal [specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity).
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Test page</title>
<style>
p {
color: white;
background-color: blue;
padding: 5px;
border: 1px solid black;
}
</style>
<style>
p {
color: blue;
background-color: yellow;
}
</style>
</head>
<body>
<p>This is my paragraph.</p>
</body>
</html>
```
### Including a media query
In this example we build on the previous one, including a `media` attribute on the second `<style>` element so it is only applied when the viewport is less than 500px in width.
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Test page</title>
<style>
p {
color: white;
background-color: blue;
padding: 5px;
border: 1px solid black;
}
</style>
<style media="all and (max-width: 500px)">
p {
color: blue;
background-color: yellow;
}
</style>
</head>
<body>
<p>This is my paragraph.</p>
</body>
</html>
```
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Metadata content](../content_categories#metadata_content), and if the `scoped` attribute is present: [flow content](../content_categories#flow_content). |
| Permitted content | Text content matching the `type` attribute, that is `text/css`. |
| Tag omission | Neither tag is omissible. |
| Permitted parents | Any element that accepts [metadata content](../content_categories#metadata_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLStyleElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLStyleElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-style-element](https://html.spec.whatwg.org/multipage/semantics.html#the-style-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `style` | 1 | 12 | 1 | 3 | 3.5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `media` | 1 | 12 | 1 | 3 | 3.5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `title` | 1 | 12 | 1 | 3 | 3.5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1
Before 75, Firefox accepted any CSS media (MIME) type, with optional parameters. Starting in 75, this has been restricted to the string 'text/css', per the spec. | 3 | 3.5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
See also
--------
* The [`<link>`](link) element, which allows us to apply external stylesheets to a document.
* [Alternative Style Sheets](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets)
| programming_docs |
html <bdo>: The Bidirectional Text Override element <bdo>: The Bidirectional Text Override element
==============================================
The `<bdo>` [HTML](../index) element overrides the current directionality of text, so that the text within is rendered in a different direction.
Try it
------
The text's characters are drawn from the starting point in the given direction; the individual characters' orientation is not affected (so characters don't get drawn backward, for example).
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`dir`**](#attr-dir) The direction in which text should be rendered in this element's contents. Possible values are:
* `ltr`: Indicates that the text should go in a left-to-right direction.
* `rtl`: Indicates that the text should go in a right-to-left direction.
Examples
--------
```
<!-- Switch text direction -->
<p>This text will go left to right.</p>
<p><bdo dir="rtl">This text will go right to left.</bdo></p>
```
### Result
Notes
-----
The HTML 4 specification did not specify events for this element; they were added in XHTML. This is most likely an oversight.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the `[HTMLSpanElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement)` interface for this element. |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-bdo-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-bdo-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `bdo` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* Related HTML element: [`<bdi>`](bdi)
html <meter>: The HTML Meter element <meter>: The HTML Meter element
===============================
The `<meter>` [HTML](../index) element represents either a scalar value within a known range or a fractional value.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), labelable content, palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content), but there must be no `<meter>` element among its descendants. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLMeterElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`value`**](#attr-value) The current numeric value. This must be between the minimum and maximum values (`min` attribute and `max` attribute) if they are specified. If unspecified or malformed, the value is `0`. If specified, but not within the range given by the `min` attribute and `max` attribute, the value is equal to the nearest end of the range.
**Note:** Unless the `value` attribute is between `0` and `1` (inclusive), the `min` and `max` attributes should define the range so that the `value` attribute's value is within it.
[**`min`**](#attr-min) The lower numeric bound of the measured range. This must be less than the maximum value (`max` attribute), if specified. If unspecified, the minimum value is `0`.
[**`max`**](#attr-max) The upper numeric bound of the measured range. This must be greater than the minimum value (`min` attribute), if specified. If unspecified, the maximum value is `1`.
[**`low`**](#attr-low) The upper numeric bound of the low end of the measured range. This must be greater than the minimum value (`min` attribute), and it also must be less than the high value and maximum value (`high` attribute and `max` attribute, respectively), if any are specified. If unspecified, or if less than the minimum value, the `low` value is equal to the minimum value.
[**`high`**](#attr-high) The lower numeric bound of the high end of the measured range. This must be less than the maximum value (`max` attribute), and it also must be greater than the low value and minimum value (`low` attribute and `min` attribute, respectively), if any are specified. If unspecified, or if greater than the maximum value, the `high` value is equal to the maximum value.
[**`optimum`**](#attr-optimum) This attribute indicates the optimal numeric value. It must be within the range (as defined by the `min` attribute and `max` attribute). When used with the `low` attribute and `high` attribute, it gives an indication where along the range is considered preferable. For example, if it is between the `min` attribute and the `low` attribute, then the lower range is considered preferred. The browser may color the meter's bar differently depending on whether the value is less than or equal to the optimum value.
Examples
--------
### Simple example
#### HTML
```
<p>
Heat the oven to <meter min="200" max="500" value="350">350 degrees</meter>.
</p>
```
#### Result
On Google Chrome, the resulting meter looks like this:
### High and Low range example
Note that in this example the [`min`](meter#attr-min) attribute is omitted. This is allowed, as it will default to `0`.
#### HTML
```
<p>
He got a <meter low="69" high="80" max="100" value="84">B</meter> on the exam.
</p>
```
#### Result
On Google Chrome, the resulting meter looks like this:
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-meter-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-meter-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `meter` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
| `form` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
| `high` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
| `low` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
| `max` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
| `min` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
| `optimum` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
| `value` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 |
See also
--------
* [`<progress>`](progress)
html <output>: The Output element <output>: The Output element
============================
The `<output>` [HTML](../index) element is a container element into which a site or app can inject the results of a calculation or the outcome of a user action.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`for`**](#attr-for) A space-separated list of other elements' [`id`](../global_attributes#id)s, indicating that those elements contributed input values to (or otherwise affected) the calculation.
[**`form`**](#attr-form) The [`<form>`](form) element to associate the output with (its *form owner*). The value of this attribute must be the [`id`](../global_attributes#id) of a `<form>` in the same document. (If this attribute is not set, the `<output>` is associated with its ancestor `<form>` element, if any.)
This attribute lets you associate `<output>` elements to `<form>`s anywhere in the document, not just inside a `<form>`. It can also override an ancestor `<form>` element.
[**`name`**](#attr-name) The element's name. Used in the [`form.elements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements) API.
The `<output>` value, name, and contents are NOT submitted during form submission.
Examples
--------
In the following example, the form provides a slider whose value can range between `0` and `100`, and an [`<input>`](input) element into which you can enter a second number. The two numbers are added together, and the result is displayed in the `<output>` element each time the value of any of the controls changes.
```
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" id="b" name="b" value="50" /> +
<input type="number" id="a" name="a" value="10" /> =
<output name="result" for="a b">60</output>
</form>
```
Accessibility Concerns
----------------------
Many browsers implement this element as an [`aria-live`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) region. Assistive technology will thereby announce the results of UI interactions posted inside it without requiring that focus is switched away from the controls that produce those results.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [listed](../content_categories#form_listed), [labelable](../content_categories#form_labelable), [resettable](../content_categories#form_resettable) [form-associated element](../content_categories#form-associated_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | `[status](https://w3c.github.io/aria/#status)` |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLOutputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-output-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-output-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `output` | 10 | ≤18 | 4 | No | 11 | 7 | Yes | Yes | 4 | No | Yes | Yes |
| `for` | 10 | ≤18 | 4 | No | 11 | 7 | Yes | Yes | 4 | No | Yes | Yes |
| `form` | 10 | ≤18 | 4 | No | 11 | 7 | Yes | Yes | 4 | No | Yes | Yes |
| `name` | 10 | ≤18 | 4 | No | 11 | 7 | Yes | Yes | 4 | No | Yes | Yes |
html <menuitem> <menuitem>
==========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The `<menuitem>` [HTML](../index) element represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button.
A command can either be defined explicitly, with a textual label and optional icon to describe its appearance, or alternatively as an *indirect command* whose behavior is defined by a separate element. Commands can also optionally include a checkbox or be grouped to share radio buttons. (Menu items for indirect commands gain checkboxes or radio buttons when defined against elements `<input type="checkbox">` and `<input type="radio">`.)
Attributes
----------
This element includes the [global attributes](../global_attributes); in particular `title` can be used to describe the command, or provide usage hints.
[**`checked`**](#attr-checked) Deprecated Non-standard
Boolean attribute which indicates whether the command is selected. May only be used when the `type` attribute is `checkbox` or `radio`.
[**`command`**](#attr-command) Deprecated Non-standard
Specifies the ID of a separate element, indicating a command to be invoked indirectly. May not be used within a menu item that also includes the attributes `checked`, `disabled`, `icon`, `label`, `radiogroup` or `type`.
[**`default`**](#attr-default) Deprecated Non-standard
This Boolean attribute indicates use of the same command as the menu's subject element (such as a `button` or `input`).
[**`disabled`**](#attr-disabled) Deprecated Non-standard
Boolean attribute which indicates that the command is not available in the current state. Note that `disabled` is distinct from `hidden`; the `disabled` attribute is appropriate in any context where a change in circumstances might render the command relevant.
[**`icon`**](#attr-icon) Deprecated Non-standard
Image URL, used to provide a picture to represent the command.
[**`label`**](#attr-label) The name of the command as shown to the user. Required when a `command` attribute is not present.
[**`radiogroup`**](#attr-radiogroup) Deprecated Non-standard
This attribute specifies the name of a group of commands to be toggled as radio buttons when selected. May only be used where the `type` attribute is `radio`.
[**`type`**](#attr-type) Deprecated Non-standard
This attribute indicates the kind of command, and can be one of three values.
* `command`: A regular command with an associated action. This is the missing value default.
* `checkbox`: Represents a command that can be toggled between two different states.
* `radio`: Represent one selection from a group of commands that can be toggled as radio buttons.
Example
-------
### HTML
```
<!-- A <div> element with a context menu -->
<div contextmenu="popup-menu">Right-click to see the adjusted context menu</div>
<menu type="context" id="popup-menu">
<menuitem type="checkbox" checked>Checkbox</menuitem>
<hr />
<menuitem
type="command"
label="This command does nothing"
icon="favicon-192x192.png">
Commands don't render their contents.
</menuitem>
<menuitem
type="command"
label="This command has javascript"
onclick="alert('command clicked')">
Commands don't render their contents.
</menuitem>
<hr />
<menuitem type="radio" radiogroup="group1">Radio Button 1</menuitem>
<menuitem type="radio" radiogroup="group1">Radio Button 2</menuitem>
</menu>
```
### CSS content
```
div {
width: 300px;
height: 80px;
background-color: lightgreen;
}
```
### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | Must have a start tag and must not have an end tag. |
| Permitted parents | The [`<menu>`](menu) element, where that element is in the *popup menu* state. (If specified, the `type` attribute of the [`<menu>`](menu) element must be `popup`; if missing, the parent element of the [`<menu>`](menu) must itself be a [`<menu>`](menu) in the *popup menu* state.) |
| Permitted ARIA roles | None |
| DOM interface | [`HTMLMenuItemElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMenuItemElement) |
Specifications
--------------
Not part of any current specifications.
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `menuitem` | No | No | 8-85
["Only works for `<menuitem>` elements defined within a `<menu>` element assigned to an element via the `contextmenu` attribute.", "The `<menuitem>` element requires a closing tag."] | No | No | No | No | No | 8-85
["Only works for `<menuitem>` elements defined within a `<menu>` element assigned to an element via the `contextmenu` attribute.", "The `<menuitem>` element requires a closing tag."] | No | No | No |
| `checked` | No | No | 8-85 | No | No | No | No | No | 8-85 | No | No | No |
| `command` | No | No | 8-85 | No | No | No | No | No | 8-85 | No | No | No |
| `default` | No | No | 8-85 | No | No | No | No | No | 8-85 | No | No | No |
| `disabled` | No | No | 8-85 | No | No | No | No | No | 8-85 | No | No | No |
| `icon` | No | No | 8-85 | No | No | No | No | No | 8-85 | No | No | No |
| `radiogroup` | No | No | 8-85 | No | No | No | No | No | 8-85 | No | No | No |
| `type` | No | No | 8-85 | No | No | No | No | No | 8-85 | No | No | No |
See also
--------
* [HTML context menus in Firefox (Screencast and Code)](https://hacks.mozilla.org/2011/11/html5-context-menus-in-firefox-screencast-and-code/)
html <fieldset>: The Field Set element <fieldset>: The Field Set element
=================================
The `<fieldset>` [HTML](../index) element is used to group several controls as well as labels ([`<label>`](label)) within a web form.
Try it
------
As the example above shows, the `<fieldset>` element provides a grouping for a part of an HTML form, with a nested [`<legend>`](legend) element providing a caption for the `<fieldset>`. It takes few attributes, the most notable of which are `form`, which can contain the `id` of a [`<form>`](form) on the same page, allowing you to make the `<fieldset>` part of that `<form>` even if it is not nested inside it, and `disabled`, which allows you to disable the `<fieldset>` and all its contents in one go.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`disabled`**](#attr-disabled) If this Boolean attribute is set, all form controls that are descendants of the `<fieldset>`, are disabled, meaning they are not editable and won't be submitted along with the [`<form>`](form). They won't receive any browsing events, like mouse clicks or focus-related events. By default browsers display such controls grayed out. Note that form elements inside the [`<legend>`](legend) element won't be disabled.
[**`form`**](#attr-form) This attribute takes the value of the [`id`](../global_attributes#id) attribute of a [`<form>`](form) element you want the `<fieldset>` to be part of, even if it is not inside the form. Please note that usage of this is confusing — if you want the [`<input>`](input) elements inside the `<fieldset>` to be associated with the form, you need to use the `form` attribute directly on those elements. You can check which elements are associated with a form via JavaScript, using [`HTMLFormElement.elements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements).
[**`name`**](#attr-name) The name associated with the group.
**Note:** The caption for the fieldset is given by the first [`<legend>`](legend) element nested inside it.
Styling with CSS
----------------
There are several special styling considerations for `<fieldset>`.
Its [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) value is `block` by default, and it establishes a [block formatting context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context). If the `<fieldset>` is styled with an inline-level `display` value, it will behave as `inline-block`, otherwise it will behave as `block`. By default there is a `2px` `groove` border surrounding the contents, and a small amount of default padding. The element has [`min-inline-size: min-content`](https://developer.mozilla.org/en-US/docs/Web/CSS/min-inline-size) by default.
If a [`<legend>`](legend) is present, it is placed over the `block-start` border. The `<legend>` shrink-wraps, and also establishes a formatting context. The `display` value is blockified. (For example, `display: inline` behaves as `block`.)
There will be an anonymous box holding the contents of the `<fieldset>`, which inherits certain properties from the `<fieldset>`. If the `<fieldset>` is styled with `display: grid` or `display: inline-grid`, then the anonymous box will be a grid formatting context. If the `<fieldset>` is styled with `display: flex` or `display: inline-flex`, then the anonymous box will be a flex formatting context. Otherwise, it establishes a block formatting context.
You can feel free to style the `<fieldset>` and `<legend>` in any way you want to suit your page design.
Examples
--------
### Simple fieldset
This example shows a really simple `<fieldset>` example, with a `<legend>`, and a single control inside it.
```
<form action="#">
<fieldset>
<legend>Do you agree?</legend>
<input type="checkbox" id="chbx" name="agree" value="Yes!" />
<label for="chbx">I agree</label>
</fieldset>
</form>
```
### Disabled fieldset
This example shows a disabled `<fieldset>` with two controls inside it. Note how both the controls are disabled due to being inside a disabled `<fieldset>`.
```
<form action="#">
<fieldset disabled>
<legend>Disabled login fieldset</legend>
<div>
<label for="name">Name: </label>
<input type="text" id="name" value="Chris" />
</div>
<div>
<label for="pwd">Archetype: </label>
<input type="password" id="pwd" value="Wookie" />
</div>
</fieldset>
</form>
```
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [sectioning root](heading_elements#sectioning_root), [listed](../content_categories#form_listed), [form-associated](../content_categories#form-associated_content) element, palpable content. |
| Permitted content | An optional [`<legend>`](legend) element, followed by flow content. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | `[group](https://w3c.github.io/aria/#group)` |
| Permitted ARIA roles | `[radiogroup](https://w3c.github.io/aria/#radiogroup)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[none](https://w3c.github.io/aria/#none)` |
| DOM interface | [`HTMLFieldSetElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-fieldset-element](https://html.spec.whatwg.org/multipage/form-elements.html#the-fieldset-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `fieldset` | Yes
Does not support `flexbox` and `grid` layouts within this element. See [bug 262679](https://crbug.com/262679). | 12
Does not support `flexbox` and `grid` layouts within this element. See [bug 4511145](https://developer.microsoft.com/microsoft-edge/platform/issues/4511145/). | Yes | Yes | Yes
Does not support `flexbox` and `grid` layouts within this element. See [bug 262679](https://crbug.com/262679). | Yes | Yes
Does not support `flexbox` and `grid` layouts within this element. See [bug 262679](https://crbug.com/262679). | Yes
Does not support `flexbox` and `grid` layouts within this element. See [bug 262679](https://crbug.com/262679). | Yes | Yes
Does not support `flexbox` and `grid` layouts within this element. See [bug 262679](https://crbug.com/262679). | Yes | Yes
Does not support `flexbox` and `grid` layouts within this element. See [bug 262679](https://crbug.com/262679). |
| `disabled` | Yes | 12
Does not work with nested fieldsets. For example: `<fieldset disabled><fieldset><!--Still enabled--></fieldset></fieldset>`
| Yes | Yes
Not all form control descendants of a disabled fieldset are properly disabled in IE11; see IE [bug 817488: input[type='file'] not disabled inside disabled fieldset](https://connect.microsoft.com/IE/feedbackdetail/view/817488) and IE [bug 962368: Can still edit input[type='text'] within fieldset[disabled]](https://connect.microsoft.com/IE/feedbackdetail/view/962368/can-still-edit-input-type-text-within-fieldset-disabled). | 12 | 6 | 4.4 | Yes | Yes | No | 6 | Yes |
| `form` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `name` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* The [`<legend>`](legend) element
* The [`<input>`](input) element
* The [`<label>`](label) element
* The [`<form>`](form) element
| programming_docs |
html <caption>: The Table Caption element <caption>: The Table Caption element
====================================
The `<caption>` [HTML](../index) element specifies the caption (or title) of a table.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
### Deprecated attributes
The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only.
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute indicates how the caption must be aligned with respect to the table. It may have one of the following values:
`left` The caption is displayed to the left of the table.
`top` The caption is displayed above the table.
`right` The caption is displayed to the right of the table.
`bottom` The caption is displayed below the table.
**Warning:** Do not use this attribute, as it has been deprecated. The [`<caption>`](caption) element should be styled using the [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) properties [`caption-side`](https://developer.mozilla.org/en-US/docs/Web/CSS/caption-side) and [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align).
Usage notes
-----------
If used, the `<caption>` element must be the first child of its parent [`<table>`](table) element.
When the `<table>` element that contains the `<caption>` is the only descendant of a [`<figure>`](figure) element, you should use the [`<figcaption>`](figcaption) element instead of `<caption>`.
A [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) on the table will not include the caption. Add a `background-color` to the `<caption>` element as well if you want the same color to be behind both.
Example
-------
This simple example presents a table that includes a caption.
```
<table>
<caption>
Example Caption
</caption>
<tr>
<th>Login</th>
<th>Email</th>
</tr>
<tr>
<td>user1</td>
<td>[email protected]</td>
</tr>
<tr>
<td>user2</td>
<td>[email protected]</td>
</tr>
</table>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | The end tag can be omitted if the element is not immediately followed by ASCII whitespace or a comment. |
| Permitted parents | A [`<table>`](table) element, as its first descendant. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLTableCaptionElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCaptionElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-caption-element](https://html.spec.whatwg.org/multipage/tables.html#the-caption-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `caption` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* CSS properties that may be specially useful to style the [`<caption>`](caption) element:
+ [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align), [`caption-side`](https://developer.mozilla.org/en-US/docs/Web/CSS/caption-side).
html <tt>: The Teletype Text element <tt>: The Teletype Text element
===============================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<tt>` [HTML](../index) element creates inline text which is presented using the [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) default monospace font face. This element was created for the purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer.
The terms **non-proportional**, **monotype**, and **monospace** are used interchangeably and have the same general meaning: they describe a typeface whose characters are all the same number of pixels wide.
This element is obsolete, however. You should use the more semantically helpful [`<code>`](code), [`<kbd>`](kbd), [`<samp>`](samp), or [`<var>`](var) elements for inline text that needs to be presented in monospace type, or the [`<pre>`](pre) tag for content that should be presented as a separate block.
**Note:** If none of the semantic elements are appropriate for your use case (for example, if you need to show some content in a non-proportional font), you should consider using the [`<span>`](span) element, styling it as desired using CSS. The [`font-family`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) property is a good place to start.
Attributes
----------
This element only includes the [global attributes](../global_attributes)
Examples
--------
### Basic example
This example uses `<tt>` to show text entered into, and output by, a terminal application.
```
<p>
Enter the following at the telnet command prompt: <code>set localecho</code><br />
The telnet client should display: <tt>Local Echo is on</tt>
</p>
```
#### Result
### Overriding the default font
You can override the browser's default font—if the browser permits you to do so, which it isn't required to do—using CSS:
#### CSS
```
tt {
font-family: "Lucida Console", "Menlo", "Monaco", "Courier", monospace;
}
```
#### HTML
```
<p>
Enter the following at the telnet command prompt: <code>set localecho</code><br />
The telnet client should display: <tt>Local Echo is on</tt>
</p>
```
#### Result
Usage notes
-----------
The `<tt>` element is, by default, rendered using the browser's default non-proportional font. You can override this using CSS by creating a rule using the `tt` selector, as seen in the example [Overriding the default font](#overriding_the_default_font) above.
**Note:** User-configured changes to the default monospace font setting may take precedence over your CSS.
Although this element wasn't officially deprecated in HTML 4.01, its use was discouraged in favor of the semantic elements and/or CSS. The `<tt>` element is obsolete in HTML 5.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # tt](https://html.spec.whatwg.org/multipage/obsolete.html#tt) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `tt` | Yes | 12 | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes |
See also
--------
* The semantic [`<code>`](code), [`<var>`](var), [`<kbd>`](kbd), and [`<samp>`](samp) elements
* The [`<pre>`](pre) element for displaying preformatted text blocks
html <main> <main>
======
The `<main>` [HTML](../index) element represents the dominant content of the [`<body>`](body) of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.
Try it
------
A document mustn't have more than one `<main>` element that doesn't have the [`hidden`](../global_attributes#hidden) attribute specified.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), palpable content. |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | None; both the starting and ending tags are mandatory. |
| Permitted parents | Where [flow content](../content_categories#flow_content) is expected, but only if it is a [hierarchically correct `main` element](https://html.spec.whatwg.org/multipage/grouping-content.html#hierarchically-correct-main-element). |
| Implicit ARIA role | `[main](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/main_role)` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
The content of a `<main>` element should be unique to the document. Content that is repeated across a set of documents or document sections such as sidebars, navigation links, copyright information, site logos, and search forms shouldn't be included unless the search form is the main function of the page.
`<main>` doesn't contribute to the document's outline; that is, unlike elements such as [`<body>`](body), headings such as [`<h2>`](heading_elements), and such, `<main>` doesn't affect the [DOM's](https://developer.mozilla.org/en-US/docs/Glossary/DOM) concept of the structure of the page. It's strictly informative.
Example
-------
```
<!-- other content -->
<main>
<h1>Apples</h1>
<p>The apple is the pomaceous fruit of the apple tree.</p>
<article>
<h2>Red Delicious</h2>
<p>
These bright red apples are the most common found in many supermarkets.
</p>
<p>…</p>
<p>…</p>
</article>
<article>
<h2>Granny Smith</h2>
<p>These juicy, green apples make a great filling for apple pies.</p>
<p>…</p>
<p>…</p>
</article>
</main>
<!-- other content -->
```
Accessibility concerns
----------------------
### Landmark
The `<main>` element behaves like a [`main` landmark](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/main_role) role. [Landmarks](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles) can be used by assistive technology to quickly identify and navigate to large sections of the document. Prefer using the `<main>` element over declaring `role="main"`, unless there are [legacy browser support concerns](#browser_compatibility).
### Skip navigation
Skip navigation, also known as "skipnav", is a technique that allows an assistive technology user to quickly bypass large sections of repeated content (main navigation, info banners, etc.). This lets the user access the main content of the page faster.
Adding an [`id`](../global_attributes#id) attribute to the `<main>` element lets it be a target of a skip navigation link.
```
<body>
<a href="#main-content">Skip to main content</a>
<!-- navigation and header content -->
<main id="main-content">
<!-- main page content -->
</main>
</body>
```
* [WebAIM: "Skip Navigation" Links](https://webaim.org/techniques/skipnav/)
### Reader mode
Browser reader mode functionality looks for the presence of the `<main>` element, as well as [heading](heading_elements) and [content sectioning elements](../element#content_sectioning) when converting content into a specialized reader view.
* [Building websites for Safari Reader Mode and other reading apps.](https://medium.com/@mandy.michael/building-websites-for-safari-reader-mode-and-other-reading-apps-1562913c86c9)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-main-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-main-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `main` | 26 | 12 | 21 | No | 16 | 7 | Yes | Yes | 21 | Yes | 7 | Yes |
See also
--------
* Basic structural elements: [`<html>`](html), [`<head>`](head), [`<body>`](body)
* Section-related elements: [`<article>`](article), [`<aside>`](aside), [`<footer>`](footer), [`<header>`](header), or [`<nav>`](nav)
* [ARIA: Main role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/main_role)
html <ruby>: The Ruby Annotation element <ruby>: The Ruby Annotation element
===================================
The `<ruby>` [HTML](../index) element represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common.
The term *ruby* originated as [a unit of measurement used by typesetters](https://en.wikipedia.org/wiki/Agate_(typography)), representing the smallest size that text can be printed on newsprint while remaining legible.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
### Example 1: Character
```
<ruby>
漢 <rp>(</rp><rt>Kan</rt><rp>)</rp>
字 <rp>(</rp><rt>ji</rt><rp>)</rp>
</ruby>
```
### Example 2: Word
```
<ruby>
明日 <rp>(</rp><rt>Ashita</rt><rp>)</rp>
</ruby>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-ruby-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-ruby-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ruby` | 5 | 12 | 38 | 5 | 15 | 5 | Yes | Yes | 38 | 14 | Yes | Yes |
See also
--------
* [`<rt>`](rt)
* [`<rp>`](rp)
* [`<rb>`](rb)
* [`<rtc>`](rtc)
* [`text-transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform): full-size-kana
html <wbr>: The Line Break Opportunity element <wbr>: The Line Break Opportunity element
=========================================
The `<wbr>` [HTML](../index) element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Notes
-----
On UTF-8 encoded pages, `<wbr>` behaves like the `U+200B ZERO-WIDTH SPACE` code point. In particular, it behaves like a Unicode bidi BN code point, meaning it has no effect on [bidi](https://developer.mozilla.org/en-US/docs/Glossary/BiDi)-ordering: `<div dir=rtl>123,<wbr>456</div>` displays, when not broken on two lines, `123,456` and not `456,123`.
For the same reason, the `<wbr>` element does not introduce a hyphen at the line break point. To make a hyphen appear only at the end of a line, use the soft hyphen character entity (`­`) instead.
Example
-------
*[The Yahoo Style Guide](https://web.archive.org/web/20121014054923/http://styleguide.yahoo.com/)* recommends [breaking a URL *before* punctuation](https://web.archive.org/web/20121105171040/http://styleguide.yahoo.com/editing/treat-abbreviations-capitalization-and-titles-consistently/website-names-and-addresses), to avoid leaving a punctuation mark at the end of the line, which the reader might mistake for the end of the URL.
```
<p>
http://this<wbr />.is<wbr />.a<wbr />.really<wbr />.long<wbr />.example<wbr />.com/With<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages
</p>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content). |
| Permitted content | Empty |
| Tag omission | It is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element); it must have a start tag, but must not have an end tag. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-wbr-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-wbr-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `wbr` | 1 | 79 | 1 | 5.5-7 | 11.6 | 4 | Yes | Yes | 4 | No | No | Yes |
See also
--------
* [`overflow-wrap`](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap)
* [`word-break`](https://developer.mozilla.org/en-US/docs/Web/CSS/word-break)
* [`hyphens`](https://developer.mozilla.org/en-US/docs/Web/CSS/hyphens)
* The [`<br>`](br) element
html <input>: The Input (Form Input) element <input>: The Input (Form Input) element
=======================================
The `<input>` [HTML](../index) element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent). The `<input>` element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes.
Try it
------
<input> types
-------------
How an `<input>` works varies considerably depending on the value of its [`type`](#type) attribute, hence the different types are covered in their own separate reference pages. If this attribute is not specified, the default type adopted is `text`.
The available types are as follows:
| Type | Description | Basic Examples |
| --- | --- | --- |
| [button](input/button) | A push button with no default behavior displaying the value of the [`value`](#value) attribute, empty by default. | |
| [checkbox](input/checkbox) | A check box allowing single values to be selected/deselected. | |
| [color](input/color) | A control for specifying a color; opening a color picker when active in supporting browsers. | |
| [date](input/date) | A control for entering a date (year, month, and day, with no time). Opens a date picker or numeric wheels for year, month, day when active in supporting browsers. | |
| [datetime-local](input/datetime-local) | A control for entering a date and time, with no time zone. Opens a date picker or numeric wheels for date- and time-components when active in supporting browsers. | |
| [email](input/email) | A field for editing an email address. Looks like a `text` input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards. | |
| [file](input/file) | A control that lets the user select a file. Use the [`accept`](#accept) attribute to define the types of files that the control can select. | |
| [hidden](input/hidden) | A control that is not displayed but whose value is submitted to the server. There is an example in the next column, but it's hidden! | |
| [image](input/image) | A graphical `submit` button. Displays an image defined by the `src` attribute. The [`alt`](#alt) attribute displays if the image [`src`](#src) is missing. | |
| [month](input/month) | A control for entering a month and year, with no time zone. | |
| [number](input/number) | A control for entering a number. Displays a spinner and adds default validation. Displays a numeric keypad in some devices with dynamic keypads. | |
| [password](input/password) | A single-line text field whose value is obscured. Will alert user if site is not secure. | |
| [radio](input/radio) | A radio button, allowing a single value to be selected out of multiple choices with the same [`name`](#name) value. | |
| [range](input/range) | A control for entering a number whose exact value is not important. Displays as a range widget defaulting to the middle value. Used in conjunction [`min`](#min) and [`max`](#max) to define the range of acceptable values. | |
| [reset](input/reset) | A button that resets the contents of the form to default values. Not recommended. | |
| [search](input/search) | A single-line text field for entering search strings. Line-breaks are automatically removed from the input value. May include a delete icon in supporting browsers that can be used to clear the field. Displays a search icon instead of enter key on some devices with dynamic keypads. | |
| [submit](input/submit) | A button that submits the form. | |
| [tel](input/tel) | A control for entering a telephone number. Displays a telephone keypad in some devices with dynamic keypads. | |
| [text](input/text) | The default value. A single-line text field. Line-breaks are automatically removed from the input value. | |
| [time](input/time) | A control for entering a time value with no time zone. | |
| [url](input/url) | A field for entering a URL. Looks like a `text` input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards. | |
| [week](input/week) | A control for entering a date consisting of a week-year number and a week number with no time zone. | |
| Obsolete values |
| `datetime` | Deprecated A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone. | |
Attributes
----------
The `<input>` element is so powerful because of its attributes; the [`type`](#type) attribute, described with examples above, being the most important. Since every `<input>` element, regardless of type, is based on the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface, they technically share the exact same set of attributes. However, in reality, most attributes have an effect on only a specific subset of input types. In addition, the way some attributes impact an input depends on the input type, impacting different input types in different ways.
This section provides a table listing all the attributes with a brief description. This table is followed by a list describing each attribute in greater detail, along with which input types they are associated with. Those that are common to most or all input types are defined in greater detail below. Attributes that are unique to particular input types—or attributes which are common to all input types but have special behaviors when used on a given input type—are instead documented on those types' pages.
Attributes for the `<input>` element include the [global HTML attributes](../global_attributes) and additionally:
| Attribute | Type or Types | Description |
| --- | --- | --- |
| [`accept`](#accept) | `file` | Hint for expected file type in file upload controls |
| [`alt`](#alt) | `image` | alt attribute for the image type. Required for accessibility |
| [`autocomplete`](#autocomplete) | all except `checkbox`, `radio`, and buttons | Hint for form autofill feature |
| [`capture`](#capture) | `file` | Media capture input method in file upload controls |
| [`checked`](#checked) | `checkbox`, `radio` | Whether the command or control is checked |
| [`dirname`](#dirname) | `search`, `text` | Name of form field to use for sending the element's directionality in form submission |
| [`disabled`](#disabled) | all | Whether the form control is disabled |
| [`form`](#form) | all | Associates the control with a form element |
| [`formaction`](#formaction) | `image`, `submit` | URL to use for form submission |
| [`formenctype`](#formenctype) | `image`, `submit` | Form data set encoding type to use for form submission |
| [`formmethod`](#formmethod) | `image`, `submit` | HTTP method to use for form submission |
| [`formnovalidate`](#formnovalidate) | `image`, `submit` | Bypass form control validation for form submission |
| [`formtarget`](#formtarget) | `image`, `submit` | Browsing context for form submission |
| [`height`](#height) | `image` | Same as height attribute for [`<img>`](img); vertical dimension |
| [`list`](#list) | all except `hidden`, `password`, `checkbox`, `radio`, and buttons | Value of the id attribute of the [`<datalist>`](datalist) of autocomplete options |
| [`max`](#max) | `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range` | Maximum value |
| [`maxlength`](#maxlength) | `text`, `search`, `url`, `tel`, `email`, `password` | Maximum length (number of characters) of `value` |
| [`min`](#min) | `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range` | Minimum value |
| [`minlength`](#minlength) | `text`, `search`, `url`, `tel`, `email`, `password` | Minimum length (number of characters) of `value` |
| [`multiple`](#multiple) | `email`, `file` | Boolean. Whether to allow multiple values |
| [`name`](#name) | all | Name of the form control. Submitted with the form as part of a name/value pair |
| [`pattern`](#pattern) | `text`, `search`, `url`, `tel`, `email`, `password` | Pattern the `value` must match to be valid |
| [`placeholder`](#placeholder) | `text`, `search`, `url`, `tel`, `email`, `password`, `number` | Text that appears in the form control when it has no value set |
| [`readonly`](#readonly) | all except `hidden`, `range`, `color`, `checkbox`, `radio`, and buttons | Boolean. The value is not editable |
| [`required`](#required) | all except `hidden`, `range`, `color`, and buttons | Boolean. A value is required or must be check for the form to be submittable |
| [`size`](#size) | `text`, `search`, `url`, `tel`, `email`, `password` | Size of the control |
| [`src`](#src) | `image` | Same as `src` attribute for [`<img>`](img); address of image resource |
| [`step`](#step) | `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range` | Incremental values that are valid |
| [`type`](#type) | all | Type of form control |
| [`value`](#value) | all | The initial value of the control |
| [`width`](#width) | `image` | Same as `width` attribute for [`<img>`](img) |
A few additional non-standard attributes are listed following the descriptions of the standard attributes.
### Individual attributes
`accept` Valid for the `file` input type only, the `accept` attribute defines which file types are selectable in a `file` upload control. See the [file](input/file) input type.
`alt` Valid for the `image` button only, the `alt` attribute provides alternative text for the image, displaying the value of the attribute if the image [`src`](#src) is missing or otherwise fails to load. See the [image](input/image) input type.
[`autocomplete`](../attributes/autocomplete) (**Not** a Boolean attribute!) The [`autocomplete`](../attributes/autocomplete) attribute takes as its value a space-separated string that describes what, if any, type of autocomplete functionality the input should provide. A typical implementation of autocomplete recalls previous values entered in the same input field, but more complex forms of autocomplete can exist. For instance, a browser could integrate with a device's contacts list to autocomplete `email` addresses in an email input field. See [Values](../attributes/autocomplete#values) in [HTML attribute: autocomplete](../attributes/autocomplete) for permitted values.
The `autocomplete` attribute is valid on `hidden`, `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range`, `color`, and `password`. This attribute has no effect on input types that do not return numeric or text data, being valid for all input types except `checkbox`, `radio`, `file`, or any of the button types.
See [The HTML autocomplete attribute](../attributes/autocomplete) for additional information, including information on password security and how `autocomplete` is slightly different for `hidden` than for other input types.
`autofocus` A Boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the [`<dialog>`](dialog) containing the element has been displayed).
**Note:** An element with the `autofocus` attribute may gain focus before the [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) event is fired.
No more than one element in the document may have the `autofocus` attribute. If put on more than one element, the first one with the attribute receives focus.
The `autofocus` attribute cannot be used on inputs of type `hidden`, since hidden inputs cannot be focused.
**Warning:** Automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. When `autofocus` is assigned, screen-readers "teleport" their user to the form control without warning them beforehand.
Use careful consideration for accessibility when applying the `autofocus` attribute. Automatically focusing on a control can cause the page to scroll on load. The focus can also cause dynamic keyboards to display on some touch devices. While a screen reader will announce the label of the form control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content.
`capture` Introduced in the HTML Media Capture specification and valid for the `file` input type only, the `capture` attribute defines which media—microphone, video, or camera—should be used to capture a new file for upload with `file` upload control in supporting scenarios. See the [file](input/file) input type.
`checked` Valid for both `radio` and `checkbox` types, `checked` is a Boolean attribute. If present on a `radio` type, it indicates that the radio button is the currently selected one in the group of same-named radio buttons. If present on a `checkbox` type, it indicates that the checkbox is checked by default (when the page loads). It does *not* indicate whether this checkbox is currently checked: if the checkbox's state is changed, this content attribute does not reflect the change. (Only the [`HTMLInputElement`'s `checked` IDL attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) is updated.)
**Note:** Unlike other input controls, a checkboxes and radio buttons value are only included in the submitted data if they are currently `checked`. If they are, the name and the value(s) of the checked controls are submitted.
For example, if a checkbox whose `name` is `fruit` has a `value` of `cherry`, and the checkbox is checked, the form data submitted will include `fruit=cherry`. If the checkbox isn't active, it isn't listed in the form data at all. The default `value` for checkboxes and radio buttons is `on`.
`dirname` Valid for `text` and `search` input types only, the `dirname` attribute enables the submission of the directionality of the element. When included, the form control will submit with two name/value pairs: the first being the [`name`](#name) and [`value`](#value), the second being the value of the `dirname` as the name with the value of `ltr` or `rtl` being set by the browser.
```
<form action="page.html" method="post">
<label
>Fruit:
<input type="text" name="fruit" dirname="fruit.dir" value="cherry" />
</label>
<input type="submit" />
</form>
<!-- page.html?fruit=cherry&fruit.dir=ltr -->
```
When the form above is submitted, the input cause both the `name` / `value` pair of `fruit=cherry` and the `dirname` / direction pair of `fruit.dir=ltr` to be sent.
`disabled` A Boolean attribute which, if present, indicates that the user should not be able to interact with the input. Disabled inputs are typically rendered with a dimmer color or using some other form of indication that the field is not available for use.
Specifically, disabled inputs do not receive the [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) event, and disabled inputs are not submitted with the form.
**Note:** Although not required by the specification, Firefox will by default [persist the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of an `<input>` across page loads. Use the [`autocomplete`](#autocomplete) attribute to control this feature.
`form` A string specifying the [`<form>`](form) element with which the input is associated (that is, its **form owner**). This string's value, if present, must match the [`id`](#id) of a `<form>` element in the same document. If this attribute isn't specified, the `<input>` element is associated with the nearest containing form, if any.
The `form` attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document.
**Note:** An input can only be associated with one form.
`formaction` Valid for the `image` and `submit` input types only. See the [submit](input/submit) input type for more information.
`formenctype` Valid for the `image` and `submit` input types only. See the [submit](input/submit) input type for more information.
`formmethod` Valid for the `image` and `submit` input types only. See the [submit](input/submit) input type for more information.
`formnovalidate` Valid for the `image` and `submit` input types only. See the [submit](input/submit) input type for more information.
`formtarget` Valid for the `image` and `submit` input types only. See the [submit](input/submit) input type for more information.
`height` Valid for the `image` input button only, the `height` is the height of the image file to display to represent the graphical submit button. See the [image](input/image) input type.
`id` Global attribute valid for all elements, including all the input types, it defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking. The value is used as the value of the [`<label>`](label)'s `for` attribute to link the label with the form control. See [`<label>`](label).
`inputmode` Global value valid for all elements, it provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. Values include `none`, `text`, `tel`, `url`, `email`, `numeric`, `decimal`, and `search`.
`list` The value given to the `list` attribute should be the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](datalist) element located in the same document. The `<datalist>` provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.
It is valid on `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range`, and `color`.
Per the specifications, the `list` attribute is not supported by the `hidden`, `password`, `checkbox`, `radio`, `file`, or any of the button types.
Depending on the browser, the user may see a custom color palette suggested, tic marks along a range, or even an input that opens like a [`<select>`](select) but allows for non-listed values. Check out the [browser compatibility table](datalist#browser_compatibility) for the other input types.
See the [`<datalist>`](datalist) element.
`max` Valid for `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`, it defines the greatest value in the range of permitted values. If the [`value`](#value) entered into the element exceeds this, the element fails [constraint validation](../constraint_validation). If the value of the `max` attribute isn't a number, then the element has no maximum value.
There is a special case: if the data type is periodic (such as for dates or times), the value of `max` may be lower than the value of `min`, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM.
`maxlength` Valid for `text`, `search`, `url`, `tel`, `email`, and `password`, it defines the maximum number of characters (as UTF-16 code units) the user can enter into the field. This must be an integer value `0` or higher. If no `maxlength` is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of `minlength`.
The input will fail [constraint validation](../constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. By default, browsers prevent users from entering more characters than allowed by the `maxlength` attribute. See [Client-side validation](#client-side_validation) for more information.
`min` Valid for `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`, it defines the most negative value in the range of permitted values. If the [`value`](#value) entered into the element is less than this, the element fails [constraint validation](../constraint_validation). If the value of the `min` attribute isn't a number, then the element has no minimum value.
This value must be less than or equal to the value of the `max` attribute. If the `min` attribute is present but is not specified or is invalid, no `min` value is applied. If the `min` attribute is valid and a non-empty value is less than the minimum allowed by the `min` attribute, constraint validation will prevent form submission. See [Client-side validation](#client-side_validation) for more information.
There is a special case: if the data type is periodic (such as for dates or times), the value of `max` may be lower than the value of `min`, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM.
`minlength` Valid for `text`, `search`, `url`, `tel`, `email`, and `password`, it defines the minimum number of characters (as UTF-16 code units) the user can enter into the entry field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the input has no minimum length.
The input will fail [constraint validation](../constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long, preventing form submission. See [Client-side validation](#client-side_validation) for more information.
`multiple` The Boolean `multiple` attribute, if set, means the user can enter comma separated email addresses in the email widget or can choose more than one file with the `file` input. See the [email](input/email) and [file](input/file) input type.
`name` A string specifying a name for the input control. This name is submitted along with the control's value when the form data is submitted.
Consider the `name` a required attribute (even though it's not). If an input has no `name` specified, or `name` is empty, the input's value is not submitted with the form! (Disabled controls, unchecked radio buttons, unchecked checkboxes, and reset buttons are also not sent.)
There are two special cases:
1. `_charset_` : If used as the name of an `<input>` element of type [hidden](input/hidden), the input's `value` is automatically set by the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) to the character encoding being used to submit the form.
2. `isindex`: For historical reasons, the name [`isindex`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-name) is not allowed.
The [`name`](#name) attribute creates a unique behavior for radio buttons.
Only one radio button in a same-named group of radio buttons can be checked at a time. Selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. The value of that one checked radio button is sent along with the name if the form is submitted,
When tabbing into a series of same-named group of radio buttons, if one is checked, that one will receive focus. If they aren't grouped together in source order, if one of the group is checked, tabbing into the group starts when the first one in the group is encountered, skipping all those that aren't checked. In other words, if one is checked, tabbing skips the unchecked radio buttons in the group. If none are checked, the radio button group receives focus when the first button in the same name group is reached.
Once one of the radio buttons in a group has focus, using the arrow keys will navigate through all the radio buttons of the same name, even if the radio buttons are not grouped together in the source order.
When an input element is given a `name`, that name becomes a property of the owning form element's [`HTMLFormElement.elements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements) property. If you have an input whose `name` is set to `guest` and another whose `name` is `hat-size`, the following code can be used:
```
let form = document.querySelector("form");
let guestName = form.elements.guest;
let hatSize = form.elements["hat-size"];
```
When this code has run, `guestName` will be the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) for the `guest` field, and `hatSize` the object for the `hat-size` field.
**Warning:** Avoid giving form elements a `name` that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.
`pattern` Valid for `text`, `search`, `url`, `tel`, `email`, and `password`, the `pattern` attribute defines a regular expression that the input's [`value`](#value) must match in order for the value to pass [constraint validation](../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.
If the `pattern` attribute is present but is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. If the pattern attribute is valid and a non-empty value does not match the pattern, constraint validation will prevent form submission.
**Note:** If using the `pattern` attribute, inform the user about the expected format by including explanatory text nearby. You can also include a [`title`](#title) attribute to explain what the requirements are to match the pattern; most browsers will display this title as a tooltip. The visible explanation is required for accessibility. The tooltip is an enhancement.
See [Client-side validation](#client-side_validation) for more information.
`placeholder` Valid for `text`, `search`, `url`, `tel`, `email`, `password`, and `number`, the `placeholder` attribute provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that provides a hint as to the expected type of data, rather than an explanation or prompt. The text *must not* include carriage returns or line feeds. So for example if a field is expected to capture a user's first name, and its label is "First Name", a suitable placeholder might be "e.g. Mustafa".
**Note:** The `placeholder` attribute is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels](#labels) for more information.
`readonly` A Boolean attribute which, if present, indicates that the user should not be able to edit the value of the input. The `readonly` attribute is supported by the `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `password` input types.
See the [HTML attribute: `readonly`](../attributes/readonly) for more information.
`required` `required` is a Boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted. The `required` attribute is supported by `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, `password`, `checkbox`, `radio`, and `file` inputs.
See [Client-side validation](#client-side_validation) and the [HTML attribute: `required`](../attributes/required) for more information.
`size` Valid for `email`, `password`, `tel`, `url`, and `text`, the `size` attribute specifies how much of the input is shown. Basically creates same result as setting CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property with a few specialities. The actual unit of the value depends on the input type. For `password` and `text`, it is a number of characters (or `em` units) with a default value of `20`, and for others, it is pixels (or `px` units). CSS `width` takes precedence over the `size` attribute.
`src` Valid for the `image` input button only, the `src` is string specifying the URL of the image file to display to represent the graphical submit button. See the [image](input/image) input type.
`step` Valid for `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`, the [`step`](../attributes/step) attribute is a number that specifies the granularity that the value must adhere to.
If not explicitly included:
* `step` defaults to 1 for `number` and `range`.
* Each date/time input type has a default `step` value appropriate for the type; see the individual input pages: [`date`](input/date#step), [`datetime-local`](input/datetime-local#step), [`month`](input/month#step), [`time`](input/time#step), and [`week`](input/week#step).
The value must be a positive number—integer or float—or the special value `any`, which means no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)).
If `any` is not explicitly set, valid values for the `number`, date/time input types, and `range` input types are equal to the basis for stepping — the [`min`](#min) value and increments of the step value, up to the [`max`](#max) value, if specified.
For example, if you have `<input type="number" min="10" step="2">`, then any even integer, `10` or greater, is valid. If omitted, `<input type="number">`, any integer is valid, but floats (like `4.2`) are not valid, because `step` defaults to `1`. For `4.2` to be valid, `step` would have had to be set to `any`, 0.1, 0.2, or any the `min` value would have had to be a number ending in `.2`, such as `<input type="number" min="-5.2">`
**Note:** When the data entered by the user doesn't adhere to the stepping configuration, the value is considered invalid in constraint validation and will match the `:invalid` pseudoclass.
See [Client-side validation](#client-side_validation) for more information.
`tabindex` Global attribute valid for all elements, including all the input types, an integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. As all input types except for input of type hidden are focusable, this attribute should not be used on form controls, because doing so would require the management of the focus order for all elements within the document with the risk of harming usability and accessibility if done incorrectly.
`title` Global attribute valid for all elements, including all input types, containing a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip. The title should NOT be used as the primary explanation of the purpose of the form control. Instead, use the [`<label>`](label) element with a `for` attribute set to the form control's [`id`](#id) attribute. See [Labels](#labels) below.
`type` A string specifying the type of control to render. For example, to create a checkbox, a value of `checkbox` is used. If omitted (or an unknown value is specified), the input type `text` is used, creating a plaintext input field.
Permitted values are listed in [Input types](#input_types) above.
`value` The input control's value. When specified in the HTML, this is the initial value, and from then on it can be altered or retrieved at any time using JavaScript to access the respective [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) object's `value` property. The `value` attribute is always optional, though should be considered mandatory for `checkbox`, `radio`, and `hidden`.
`width` Valid for the `image` input button only, the `width` is the width of the image file to display to represent the graphical submit button. See the [image](input/image) input type.
### Non-standard attributes
The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped.
| Attribute | Description |
| --- | --- |
| [`autocorrect`](#autocorrect) | A string indicating whether autocorrect is `on` or `off`. **Safari only.** |
| [`incremental`](#incremental) | Whether or not to send repeated [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/search_event) events to allow updating live search results while the user is still editing the value of the field. **WebKit and Blink only (Safari, Chrome, Opera, etc.).** |
| `mozactionhint` | A string indicating the type of action that will be taken when the user presses the `Enter` or `Return` key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. **Deprecated: use [`enterkeyhint`](../global_attributes/enterkeyhint) instead.** |
| [`orient`](#orient) | Sets the orientation of the range slider. **Firefox only**. |
| [`results`](#results) | The maximum number of items that should be displayed in the drop-down list of previous search queries. **Safari only.** |
| [`webkitdirectory`](#webkitdirectory) | A Boolean indicating whether to only allow the user to choose a directory (or directories, if [`multiple`](#multiple) is also present) |
`autocorrect` Non-standard
(Safari only). A string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are:
`on` Enable automatic correction of typos, as well as processing of text substitutions if any are configured.
`off` Disable automatic correction and text substitutions.
`incremental` Non-standard
The Boolean attribute `incremental` is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) to process the input as a live search. As the user edits the value of the field, the user agent sends [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/search_event) events to the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) object representing the search box. This allows your code to update the search results in real time as the user edits the search.
If `incremental` is not specified, the [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/search_event) event is only sent when the user explicitly initiates a search (such as by pressing the `Enter` or `Return` key while editing the field).
The `search` event is rate-limited so that it is not sent more frequently than an implementation-defined interval.
`orient` Non-standard
Similar to the -moz-orient non-standard CSS property impacting the [`<progress>`](progress) and [`<meter>`](meter) elements, the `orient` attribute defines the orientation of the range slider. Values include `horizontal`, meaning the range is rendered horizontally, and `vertical`, where the range is rendered vertically.
`results` Non-standard
The `results` attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the [`<input>`](input) element's natively-provided drop-down menu of previous search queries.
The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser's default maximum number of entries is used.
`webkitdirectory` Non-standard
The Boolean `webkitdirectory` attribute, if present, indicates that only directories should be available to be selected by the user in the file picker interface. See [`HTMLInputElement.webkitdirectory`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory) for additional details and examples.
Though originally implemented only for WebKit-based browsers, `webkitdirectory` is also usable in Microsoft Edge as well as Firefox 50 and later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative.
Methods
-------
The following methods are provided by the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface which represents `<input>` elements in the DOM. Also available are those methods specified by the parent interfaces, [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement), [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element), [`Node`](https://developer.mozilla.org/en-US/docs/Web/API/Node), and [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget).
[`checkValidity()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity) Returns `true` if the element's value passes validity checks; otherwise, returns `false` and fires an [`invalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event) event at the element.
[`reportValidity()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/reportValidity) Returns `true` if the element's value passes validity checks; otherwise, returns `false`, fires an [`invalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event) event at the element, and (if the event isn't canceled) reports the problem to the user.
[`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) Selects the entire content of the `<input>` element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing.
[`setCustomValidity()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setCustomValidity) Sets a custom message to display if the input element's value isn't valid.
[`setRangeText()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText) Sets the contents of the specified range of characters in the input element to a given string. A `selectMode` parameter is available to allow controlling how the existing content is affected.
[`setSelectionRange()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) Selects the specified range of characters within a textual input element. Does nothing for inputs which aren't presented as text input fields.
[`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown) Decrements the value of a numeric input by one, by default, or by the specified number of units.
[`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp) Increments the value of a numeric input by one or by the specified number of units.
CSS
---
Inputs, being replaced elements, have a few features not applicable to non form elements. There are CSS selectors that can specifically target form controls based on their UI features, also known as UI pseudo-classes. The input element can also be targeted by type with attribute selectors. There are some properties that are especially useful as well.
### UI pseudo-classes
Captions super relevant to the `<input>` element: | Pseudo-class | Description |
| --- | --- |
| [`:enabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled) | Any currently enabled element that can be activated (selected, clicked on, typed into, etc.) or accept focus and also has a disabled state, in which it can't be activated or accept focus. |
| [`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled) | Any currently disabled element that has an enabled state, meaning it otherwise could be activated (selected, clicked on, typed into, etc.) or accept focus were it not disabled. |
| [`:read-only`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-only) | Element not editable by the user |
| [`:read-write`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-write) | Element that is editable by the user. |
| [`:placeholder-shown`](https://developer.mozilla.org/en-US/docs/Web/CSS/:placeholder-shown) | Element that is currently displaying [`placeholder` text](#placeholder), including `<input>` and [`<textarea>`](textarea) elements with the [`placeholder`](#placeholder) attribute present that has, as yet, no value. |
| [`:default`](https://developer.mozilla.org/en-US/docs/Web/CSS/:default) | Form elements that are the default in a group of related elements. Matches [checkbox](input/checkbox) and [radio](input/radio) input types that were checked on page load or render. |
| [`:checked`](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked) | Matches [checkbox](input/checkbox) and [radio](input/radio) input types that are currently checked (and the ([`<option>`](option) in a [`<select>`](select) that is currently selected). |
| [`:indeterminate`](https://developer.mozilla.org/en-US/docs/Web/CSS/:indeterminate) | [checkbox](input/checkbox) elements whose indeterminate property is set to true by JavaScript, [radio](input/radio) elements, when all radio buttons with the same name value in the form are unchecked, and [`<progress>`](progress) elements in an indeterminate state |
| [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) | Form controls that can have constraint validation applied and are currently valid. |
| [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) | Form controls that have constraint validation applied and are currently not valid. Matches a form control whose value doesn't match the constraints set on it by its attributes, such as [`required`](#required), [`pattern`](#pattern), [`step`](#step) and [`max`](#max). |
| [`:in-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:in-range) | A non-empty input whose current value is within the range limits specified by the [`min`](#min) and [`max`](#max) attributes and the [`step`](#step). |
| [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) | A non-empty input whose current value is NOT within the range limits specified by the [`min`](#min) and [`max`](#max) attributes or does not adhere to the [`step`](#step) constraint. |
| [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required) | `<input>`, [`<select>`](select), or [`<textarea>`](textarea) element that has the [`required`](#required) attribute set on it. Only matches elements that can be required. The attribute included on a non-requirable element will not make for a match. |
| [`:optional`](https://developer.mozilla.org/en-US/docs/Web/CSS/:optional) | `<input>`, [`<select>`](select), or [`<textarea>`](textarea) element that does NOT have the [`required`](#required) attribute set on it. Does not match elements that can't be required. |
| [`:blank`](https://developer.mozilla.org/en-US/docs/Web/CSS/:blank) | `<input>` and [`<textarea>`](textarea) elements that currently have no value. |
| [`:user-invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:user-invalid) | Similar to `:invalid`, but is activated on blur. Matches invalid input but only after the user interaction, such as by focusing on the control, leaving the control, or attempting to submit the form containing the invalid control. |
#### Pseudo-classes example
We can style a checkbox label based on whether the checkbox is checked or not. In this example, we are styling the [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) and [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) of the [`<label>`](label) that comes immediately after a checked input. We haven't applied any styles if the `input` is not checked.
```
input:checked + label {
color: red;
font-weight: bold;
}
```
### Attribute selectors
It is possible to target different types of form controls based on their [`type`](#type) using [attribute selectors](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors). CSS attribute selectors match elements based on either just the presence of an attribute or the value of a given attribute.
```
/\* matches a password input \*/
input[type="password"] {
}
/\* matches a form control whose valid values are limited to a range of values\*/
input[min][max] {
}
/\* matches a form control with a pattern attribute \*/
input[pattern] {
}
```
### ::placeholder
By default, the appearance of placeholder text is a translucent or light gray. The [`::placeholder`](https://developer.mozilla.org/en-US/docs/Web/CSS/::placeholder) pseudo-element is the input's [`placeholder` text](#placeholder). It can be styled with a limited subset of CSS properties.
```
::placeholder {
color: blue;
}
```
Only the subset of CSS properties that apply to the [`::first-line`](https://developer.mozilla.org/en-US/docs/Web/CSS/::first-line) pseudo-element can be used in a rule using `::placeholder` in its selector.
### appearance
The [`appearance`](https://developer.mozilla.org/en-US/docs/Web/CSS/appearance) property enables the displaying of (almost) any element as a platform-native style based on the operating system's theme as well as the removal of any platform-native styling with the `none` value.
You could make a `<div>` look like a radio button with `div {appearance: radio;}` or a radio look like a checkbox with `[type="radio"] {appearance: checkbox;}`, but don't.
Setting `appearance: none` removes platform native borders, but not functionality.
### caret-color
A property specific to text entry-related elements is the CSS [`caret-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/caret-color) property, which lets you set the color used to draw the text input caret:
#### HTML
```
<label for="textInput">Note the red caret:</label>
<input id="textInput" class="custom" size="32" />
```
#### CSS
```
input.custom {
caret-color: red;
font: 16px "Helvetica", "Arial", "sans-serif";
}
```
#### Result
### object-position and object-fit
In certain cases (typically involving non-textual inputs and specialized interfaces), the `<input>` element is a [replaced element](https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element). When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) and [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) properties
### Styling
For more information about adding color to elements in HTML, see:
* [Applying color to HTML elements using CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Colors/Applying_color).
Also see:
* [Styling HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms/Styling_web_forms)
* [Advanced styling for HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms/Advanced_form_styling) and
* the [compatibility table of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls).
Additional features
-------------------
### Labels
Labels are needed to associate assistive text with an `<input>`. The [`<label>`](label) element provides explanatory information about a form field that is *always* appropriate (aside from any layout concerns you have). It's never a bad idea to use a `<label>` to explain what should be entered into an `<input>` or [`<textarea>`](textarea).
#### Associated labels
The semantic pairing of `<input>` and `<label>` elements is useful for assistive technologies such as screen readers. By pairing them using the `<label>`'s [`for`](label#for) attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely.
It does not suffice to have plain text adjacent to the `<input>` element. Rather, usability and accessibility requires the inclusion of either implicit or explicit [`<label>`](label):
```
<!-- inaccessible -->
<p>Enter your name: <input id="name" type="text" size="30" /></p>
<!-- implicit label -->
<p>
<label>Enter your name: <input id="name" type="text" size="30" /></label>
</p>
<!-- explicit label -->
<p>
<label for="name">Enter your name: </label>
<input id="name" type="text" size="30" />
</p>
```
The first example is inaccessible: no relationship exists between the prompt and the `<input>` element.
In addition to an accessible name, the label provides a larger 'hit' area for mouse and touch screen users to click on or touch. By pairing a `<label>` with an `<input>`, clicking on either one will focus the `<input>`. If you use plain text to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions.
As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your website—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels.
#### Placeholders are not accessible
The [`placeholder`](#placeholder) attribute lets you specify text that appears within the `<input>` element's content area itself when it is empty. The placeholder should never be required to understand your forms. It is not a label, and should not be used as a substitute, because it isn't. The placeholder is used to provide a hint as to what an inputted value should look like, not an explanation or prompt.
Not only is the placeholder not accessible to screen readers, but once the user enters any text into the form control, or if the form control already has a value, the placeholder disappears. Browsers with automatic page translation features may skip over attributes when translating, meaning the `placeholder` may not get translated.
**Note:** Don't use the [`placeholder`](#placeholder) attribute if you can avoid it. If you need to label an `<input>` element, use the [`<label>`](label) element.
### Client-side validation
**Warning:** Client-side validation is useful, but it does *not* guarantee that the server will receive valid data. If the data must be in a specific format, *always* verify it also on the server-side, and return a [`400` HTTP response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400) if the format is invalid.
In addition to using CSS to style inputs based on the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) or [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) UI states based on the current state of each input, as noted in the [UI pseudo-classes](#ui_pseudo-classes) section above, the browser provides for client-side validation on (attempted) form submission. On form submission, if there is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you.
Some input types and other attributes place limits on what values are valid for a given input. For example, `<input type="number" min="2" max="10" step="2">` means only the number 2, 4, 6, 8, or 10 are valid. Several errors could occur, including a `rangeUnderflow` error if the value is less than 2, `rangeOverflow` if greater than 10, `stepMismatch` if the value is a number between 2 and 10, but not an even integer (does not match the requirements of the `step` attribute), or `typeMismatch` if the value is not a number.
For the input types whose domain of possible values is periodic (that is, at the highest possible value, the values wrap back around to the beginning rather than ending), it's possible for the values of the [`max`](#max) and [`min`](#min) properties to be reversed, which indicates that the range of permitted values starts at `min`, wraps around to the lowest possible value, then continues on until `max` is reached. This is particularly useful for dates and times, such as when you want to allow the range to be from 8 PM to 8 AM:
```
<input type="time" min="20:00" max="08:00" name="overnight" />
```
Specific attributes and their values can lead to a specific error [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState):
Validity object errors depend on the [`<input>`](input) attributes and their values: | Attribute | Relevant property | Description |
| --- | --- | --- |
| [`max`](#max) | [`validityState.rangeOverflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow) | Occurs when the value is greater than the maximum value as defined by the `max` attribute |
| [`maxlength`](#maxlength) | [`validityState.tooLong`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooLong) | Occurs when the number of characters is greater than the number allowed by the `maxlength` property |
| [`min`](#min) | [`validityState.rangeUnderflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeUnderflow) | Occurs when the value is less than the minimum value as defined by the `min` attribute |
| [`minlength`](#minlength) | [`validityState.tooShort`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooShort) | Occurs when the number of characters is less than the number required by the `minlength` property |
| [`pattern`](#pattern) | [`validityState.patternMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/patternMismatch) | Occurs when a pattern attribute is included with a valid regular expression and the `value` does not match it. |
| [`required`](#required) | [`validityState.valueMissing`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/valueMissing) | Occurs when the `required` attribute is present but the value is `null` or radio or checkbox is not checked. |
| [`step`](#step) | [`validityState.stepMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/stepMismatch) | The value doesn't match the step increment. Increment default is `1`, so only integers are valid on `type="number"` is step is not included. `step="any"` will never throw this error. |
| [`type`](#type) | [`validityState.typeMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/typeMismatch) | Occurs when the value is not of the correct type, for example an email does not contain an `@` or a url doesn't contain a protocol. |
If a form control doesn't have the `required` attribute, no value, or an empty string, is not invalid. Even if the above attributes are present, with the exception of `required`, and empty string will not lead to an error.
We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted.
In addition to the errors described in the table above, the `validityState` interface contains the `badInput`, `valid`, and `customError` boolean readonly properties. The validity object includes:
* [`validityState.valueMissing`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/valueMissing)
* [`validityState.typeMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/typeMismatch)
* [`validityState.patternMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/patternMismatch)
* [`validityState.tooLong`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooLong)
* [`validityState.tooShort`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooShort)
* [`validityState.rangeUnderflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeUnderflow)
* [`validityState.rangeOverflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow)
* [`validityState.stepMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/stepMismatch)
* [`validityState.badInput`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/badInput)
* `validityState.valid`
* `validityState.customError`
For each of these Boolean properties, a value of `true` indicates that the specified reason validation may have failed is true, with the exception of the `valid` property, which is `true` if the element's value obeys all constraints.
If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or `null`), the form will be prevented from being submitted. If there is no custom error message, and none of the other properties return true, `valid` will be true, and the form can be submitted.
```
function validate(input) {
let validityState_object = input.validity;
if (validityState_object.valueMissing) {
input.setCustomValidity("A value is required");
} else if (validityState_object.rangeUnderflow) {
input.setCustomValidity("Your value is too low");
} else if (validityState_object.rangeOverflow) {
input.setCustomValidity("Your value is too high");
} else {
input.setCustomValidity("");
}
}
```
The last line, setting the custom validity message to the empty string is vital. If the user makes an error, and the validity is set, it will fail to submit, even if all the values are valid, until the message is `null`.
#### Custom validation error example
If you want to present a custom error message when a field fails to validate, you need to use the [Constraint Validation API](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#validating_forms_using_javascript) available on `<input>` (and related) elements. Take the following form:
```
<form>
<label for="name">Enter username (upper and lowercase letters): </label>
<input type="text" name="name" id="name" required pattern="[A-Za-z]+" />
<button>Submit</button>
</form>
```
The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the `pattern`.
If you wanted to instead display custom error messages, you could use JavaScript like the following:
```
const nameInput = document.querySelector("input");
nameInput.addEventListener("input", () => {
nameInput.setCustomValidity("");
nameInput.checkValidity();
});
nameInput.addEventListener("invalid", () => {
if (nameInput.value === "") {
nameInput.setCustomValidity("Enter your username!");
} else {
nameInput.setCustomValidity(
"Usernames can only contain upper and lowercase letters. Try again!"
);
}
});
```
The example renders like so:
In brief:
* We check the valid state of the input element every time its value is changed by running the `checkValidity()` method via the `input` event handler.
* If the value is invalid, an `invalid` event is raised, and the `invalid` event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an `if ()` block, and set a custom validity error message.
* As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.
* If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking `setCustomValidity()` with an empty string value. We therefore do this every time the `input` event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it currently contains a valid value on submission.
**Note:** Always validate input constraints both client side and server side. Constraint validation doesn't remove the need for validation on the *server side*. Invalid values can still be sent by older browsers or by bad actors.
**Note:** Firefox supported a proprietary error attribute — `x-moz-errormessage` — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see [bug 1513890](https://bugzilla.mozilla.org/show_bug.cgi?id=1513890)).
### Localization
The allowed inputs for certain `<input>` types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.
Firefox uses the following heuristics to determine the locale to validate the user's input (at least for `type="number"`):
* Try the language specified by a `lang`/`xml:lang` attribute on the element or any of its parents.
* Try the language specified by any `Content-Language` HTTP header. Or,
* If none specified, use the browser's locale.
### Technical summary
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), listed, submittable, resettable, form-associated element, [phrasing content](../content_categories#phrasing_content). If the [`type`](#type) is not `hidden`, then labelable element, palpable content. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | Must have a start tag and must not have an end tag. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | * `type=button`: `[button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)`
* `type=checkbox`: `[checkbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role)`
* `type=email`
+ with no `list` attribute: `[textbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role)`
+ with `list` attribute: `[combobox](https://w3c.github.io/aria/#combobox)`
* `type=image`: `[button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)`
* `type=number`: `[spinbutton](https://w3c.github.io/aria/#spinbutton)`
* `type=radio`: `[radio](https://w3c.github.io/aria/#radio)`
* `type=range`: `[slider](https://w3c.github.io/aria/#slider)`
* `type=reset`: `[button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)`
* `type=search`
+ with no `list` attribute: `[searchbox](https://w3c.github.io/aria/#searchbox)`
+ with `list` attribute:`[combobox](https://w3c.github.io/aria/#combobox)`
* `type=submit`: `[button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)`
* `type=tel`
+ with no `list` attribute: `[textbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role)`
+ with `list` attribute: `[combobox](https://w3c.github.io/aria/#combobox)`
* `type=text`
+ with no `list` attribute: `[textbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role)`
+ with `list` attribute: `[combobox](https://w3c.github.io/aria/#combobox)`
* `type=url`
+ with no `list` attribute: `[textbox](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role)`
+ with `list` attribute: `[combobox](https://w3c.github.io/aria/#combobox)`
* `type=color|date|datetime-local|file|hidden|month|password|time|week`: [no corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role)
|
| Permitted ARIA roles | * `type=button`: `[checkbox](https://w3c.github.io/aria/#checkbox)`, `[combobox](https://w3c.github.io/aria/#combobox)`, `[link](https://w3c.github.io/aria/#link)`, `[menuitem](https://w3c.github.io/aria/#menuitem)`, `[menuitemcheckbox](https://w3c.github.io/aria/#menuitemcheckbox)`, `[menuitemradio](https://w3c.github.io/aria/#menuitemradio)`, `[option](https://w3c.github.io/aria/#option)`, `[radio](https://w3c.github.io/aria/#radio)`, `[switch](https://w3c.github.io/aria/#switch)`, `[tab](https://w3c.github.io/aria/#tab)`
* `type=checkbox`: `[button](https://w3c.github.io/aria/#button)` when used with `aria-pressed`, `[menuitemcheckbox](https://w3c.github.io/aria/#menuitemcheckbox)`, `[option](https://w3c.github.io/aria/#option)`, `[switch](https://w3c.github.io/aria/#switch)`
* `type=image`: `[link](https://w3c.github.io/aria/#link)`, `[menuitem](https://w3c.github.io/aria/#menuitem)`, `[menuitemcheckbox](https://w3c.github.io/aria/#menuitemcheckbox)`, `[menuitemradio](https://w3c.github.io/aria/#menuitemradio)`, `[radio](https://w3c.github.io/aria/#radio)`, `[switch](https://w3c.github.io/aria/#switch)`
* `type=radio`: `[menuitemradio](https://w3c.github.io/aria/#menuitemradio)`
* `type=text` with no `list` attribute: `[combobox](https://w3c.github.io/aria/#combobox)`, `[searchbox](https://w3c.github.io/aria/#searchbox)`, `[spinbutton](https://w3c.github.io/aria/#spinbutton)`
* `type=color|date|datetime-local|email|file|hidden|` `month|number|password|range|reset|search|submit|tel|url|week` or `text` with `list` attribute: no `role` permitted
|
| DOM interface | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) |
Accessibility concerns
----------------------
### Labels
When including inputs, it is an accessibility requirement to add labels alongside. This is needed so those who use assistive technologies can tell what the input is for. Also, clicking or touching a label gives focus to the label's associated form control. This improves the accessibility and usability for sighted users, increases the area a user can click or touch to activate the form control. This is especially useful (and even needed) for radio buttons and checkboxes, which are tiny. For more information about labels in general see [Labels](#labels) .
The following is an example of how to associate the `<label>` with an `<input>` element in the above style. You need to give the `<input>` an `id` attribute. The `<label>` then needs a `for` attribute whose value is the same as the input's `id`.
```
<label for="peas">Do you like peas?</label>
<input type="checkbox" name="peas" id="peas" />
```
### Size
Interactive elements such as form input should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44×44 [CSS pixels](https://www.w3.org/TR/WCAG21/#dfn-css-pixels) is recommended.
* [Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/target-size.html)
* [Target Size and 2.5.5 | Adrian Roselli](https://adrianroselli.com/2019/06/target-size-and-2-5-5.html)
* [Quick test: Large touch targets - The A11Y Project](https://www.a11yproject.com/posts/large-touch-targets/)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-input-element](https://html.spec.whatwg.org/multipage/input.html#the-input-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `input` | Yes | 12 | 1
Before Firefox 89, manipulating the content of `<input>` elements using `Document.execCommand()` commands requires workarounds (see [bug 1220696](https://bugzil.la/1220696)). | Yes | Yes | 1 | 1 | Yes | 4
Before Firefox 89, manipulating the content of `<input>` elements using `Document.execCommand()` commands requires workarounds (see [bug 1220696](https://bugzil.la/1220696)). | Yes | 1 | Yes |
| `accept` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `alt` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `capture` | No | No | No | No | No | No | 4.4 | 25 | 79 | 14 | 10 | 1.5 |
| `checked` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `dirname` | 17 | 79 | No | No | ≤12.1 | 6 | 4.4 | 18 | No | ≤12.1 | 6 | 1.0 |
| `disabled` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `form` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `formaction` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `formenctype` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `formmethod` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `formnovalidate` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `formtarget` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `list` | 20 | 12 | 4 | 10 | ≤12.1 | 12.1 | 4.4.3 | 25 | 4 | ≤12.1 | 12.2 | 1.5 |
| `max` | 4 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 |
| `maxlength` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `min` | 4 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 |
| `minlength` | 40 | 17 | 51 | No | 27 | 10.1 | 40 | 40 | 51 | 27 | 10.3 | 4.0 |
| `multiple` | 2 | 12 | 3.6 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `pattern` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `placeholder` | 3 | 12 | 4 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `readonly` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `src` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `step` | 5 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 |
| `type_button` | 1 | 12 | 1 | Yes | Yes | 1 | Yes | 18 | 4 | Yes | Yes | 1.0 |
| `type_checkbox` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type_color` | 20 | 14 | 29 | No | 12 | 12.1 | 4.4 | 25 | 27
Firefox for Android doesn't allow the user to choose a custom color, only one of the predefined ones. | 12 | 12.2 | 1.5 |
| `type_date` | 20 | 12 | 57 | No | 11 | 14.1 | Yes | Yes | 57 | 11 | 5 | Yes |
| `type_datetime-local` | 20 | 12 | 93 | No | 11 | 14.1 | Yes | Yes | Yes | 11 | Yes | Yes |
| `type_email` | 5 | 12 | Yes | 10 | 11 | Yes | No | No | 4 | Yes | 3
["Doesn't do validation, but instead offers a custom 'email' keyboard, which is designed to make entering email addresses easier.", "The custom 'email' keyboard does not provide a comma key, so users cannot enter multiple email addresses.", "Automatically applies a default style of `opacity: 0.4` to disable textual `<input>` elements, including those of type 'email'. Other major browsers don't currently share this particular default style."] | No |
| `type_file` | 1 | 12 | 1
You can set as well as get the value of `HTMLInputElement.files` in all modern browsers; this was most recently added to Firefox, in version 57 (see [bug 1384030](https://bugzil.la/1384030)). | Yes | 11 | 1 | Yes | Yes | 4 | 11 | Yes | Yes |
| `type_hidden` | 1 | 12 | 1 | Yes | 2 | 1 | Yes | Yes | 4 | Yes | Yes | Yes |
| `type_image` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes | No |
| `type_month` | 20 | 12 | No
See [bug 888320](https://bugzil.la/888320). | No | 11 | No
The input type is recognized, but there is no month-specific control. See [bug 200416](https://webkit.org/b/200416). | Yes | Yes | 18 | Yes | Yes | Yes |
| `type_number` | Yes | 12 | Yes | 10 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `type_password` | 1 | 12 | 1 | 2 | 2 | 1 | No | Yes | 4 | Yes | Yes | Yes |
| `type_radio` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type_range` | 4 | 12 | 23 | 10 | 11 | 3.1 | 4.4
2-4.4
Pre-Chromium Android WebView recognizes the `range` type, but doesn't implement a range-specific control. | 57 | 52 | Yes | 5 | 7.0 |
| `type_reset` | 1 | 12 | 1
Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | 1 | Yes | Yes | 4
Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | Yes |
| `type_search` | 5 | 12 | 4 | 10 | 10.6 | 5 | Yes | Yes | Yes | Yes | Yes | Yes |
| `type_submit` | 1 | 12 | 1
Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | 1 | Yes | Yes | 4
Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | Yes |
| `type_tel` | 3
The field type doesn't demonstrate any special behavior. | 12 | Yes | 10 | 11 | 4
The field type doesn't demonstrate any special behavior. | ≤37 | 18 | Yes | 11 | 3 | 1.0 |
| `type_text` | 1 | 12 | 1 | Yes | Yes | 1 | Yes | Yes | 4 | Yes | Yes | Yes |
| `type_time` | 20 | 12 | 57 | No | 10 | 14.1 | Yes | 25 | 57 | Yes | Yes | 1.5 |
| `type_url` | 1 | 12 | Yes | 10 | 11 | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| `type_week` | 20 | 12 | No
See [bug 888320](https://bugzil.la/888320). | No | 11 | No
See [bug 200416](https://webkit.org/b/200416). | Yes | Yes | 18 | Yes | No
See [bug 200416](https://webkit.org/b/200416). | Yes |
| `usemap` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `x-moz-errormessage` | No | No | Yes-66 | No | No | No | No | No | Yes-66 | No | No | No |
See also
--------
* [Form constraint validation](../constraint_validation)
* [Your first HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms/Your_first_form)
* [How to structure an HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms/How_to_structure_a_web_form)
* [The native form widgets](https://developer.mozilla.org/en-US/docs/Learn/Forms/Basic_native_form_controls)
* [Sending form data](https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data)
* [Form data validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation)
* [How to build custom form widgets](https://developer.mozilla.org/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
* [HTML forms in legacy browsers](https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML_forms_in_legacy_browsers)
* [Styling HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms/Styling_web_forms)
* [Advanced styling for HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms/Advanced_form_styling)
* [CSS property compatibility table](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| programming_docs |
html <plaintext>: The Plain Text element (Deprecated) <plaintext>: The Plain Text element (Deprecated)
================================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<plaintext>` [HTML](../index) element renders everything following the start tag as raw text, ignoring any following HTML. There is no closing tag, since everything after it is considered raw text.
**Warning:** Do not use this element.
* `<plaintext>` is deprecated since HTML 2, and not all browsers implemented it. Browsers that did implement it didn't do so consistently.
* `<plaintext>` is obsolete; browsers that accept it may instead treat it as a [`<pre>`](pre) element that still interprets HTML within.
* If `<plaintext>` is the first element on the page (other than any non-displayed elements, like [`<head>`](head)), do not use HTML at all. Instead serve a text file with the `text/plain` [MIME-type](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Configuring_server_MIME_types).
* Instead of `<plaintext>`, use the [`<pre>`](pre) element or, if semantically accurate (such as for inline text), the [`<code>`](code) element. Escape any `<`, `>` and `&` characters, to prevent browsers inadvertently parsing content the element content as HTML.
* A monospaced font can be applied to any HTML element via a [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) [`font-family`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) style with the `monospace` generic value.
Attributes
----------
This element has no other attributes than the [global attributes](../global_attributes) common to all elements.
DOM interface
-------------
This element implements the [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # plaintext](https://html.spec.whatwg.org/multipage/obsolete.html#plaintext) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `plaintext` | Yes | 12 | 4
Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The [`<pre>`](pre) and [`<code>`](code) elements, which should be used instead.
* The `<listing>` and [`<xmp>`](xmp) elements, which are both obsolete elements similar to [`<plaintext>`](plaintext).
html <head>: The Document Metadata (Header) element <head>: The Document Metadata (Header) element
==============================================
The `<head>` [HTML](../index) element contains machine-readable information ([metadata](https://developer.mozilla.org/en-US/docs/Glossary/Metadata)) about the document, like its <title>, [scripts](script), and [style sheets](style).
**Note:** `<head>` primarily holds information for machine processing, not human-readability. For human-visible information, like top-level headings and listed authors, see the [`<header>`](header) element.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`profile`**](#attr-profile) Deprecated Non-standard
The [URI](https://developer.mozilla.org/en-US/docs/Glossary/URI)s of one or more metadata profiles, separated by [white space](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace).
Example
-------
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Document title</title>
</head>
</html>
```
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | If the document is an [`<iframe>`](iframe) [`srcdoc`](iframe#attr-srcdoc) document, or if title information is available from a higher level protocol (like the subject line in HTML email), zero or more elements of metadata content. Otherwise, one or more elements of metadata content where exactly one is a [`<title>`](title) element. |
| Tag omission | The start tag may be omitted if the first thing inside the `<head>` element is an element.The end tag may be omitted if the first thing following the `<head>` element is not a space character or a comment. |
| Permitted parents | An [`<html>`](html) element, as its first child. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLHeadElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-head-element](https://html.spec.whatwg.org/multipage/semantics.html#the-head-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `head` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `profile` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Elements that can be used inside the `<head>`:
+ [`<title>`](title)
+ [`<base>`](base)
+ [`<link>`](link)
+ [`<style>`](style)
+ [`<meta>`](meta)
+ [`<script>`](script)
+ [`<noscript>`](noscript)
+ [`<template>`](template)
html <section>: The Generic Section element <section>: The Generic Section element
======================================
The `<section>` [HTML](../index) element represents a generic standalone section of a document, which doesn't have a more specific semantic element to represent it. Sections should always have a heading, with very few exceptions.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
As mentioned above, `<section>` is a generic sectioning element, and should only be used if there isn't a more specific element to represent it. As an example, a navigation menu should be wrapped in a [`<nav>`](nav) element, but a list of search results or a map display and its controls don't have specific elements, and could be put inside a `<section>`.
Also consider these cases:
* If the contents of the element represent a standalone, atomic unit of content that makes sense syndicated as a standalone piece (e.g. a blog post or blog comment, or a newspaper article), the [`<article>`](article) element would be a better choice.
* If the contents represent useful tangential information that works alongside the main content, but is not directly part of it (like related links, or an author bio), use an [`<aside>`](aside).
* If the contents represent the main content area of a document, use [`<main>`](main).
* If you are only using the element as a styling wrapper, use a [`<div>`](div) instead.
To reiterate, each `<section>` should be identified, typically by including a heading ([`<h1>`](heading_elements) - [`<h6>`](heading_elements) element) as a child of the `<section>` element, wherever possible. See below for examples of where you might see a `<section>` without a heading.
Examples
--------
### Simple usage example
#### Before
```
<div>
<h2>Heading</h2>
<p>Bunch of awesome content</p>
</div>
```
#### After
```
<section>
<h2>Heading</h2>
<p>Bunch of awesome content</p>
</section>
```
### Using a section without a heading
Circumstances where you might see `<section>` used without a heading are typically found in web application/UI sections rather than in traditional document structures. In a document, it doesn't really make any sense to have a separate section of content without a heading to describe its contents. Such headings are useful for all readers, but particularly useful for users of assistive technologies like screen readers, and they are also good for SEO.
Consider however a secondary navigation mechanism. If the global navigation is already wrapped in a `<nav>` element, you could conceivably wrap a previous/next menu in a `<section>`:
```
<section>
<a href="#">Previous article</a>
<a href="#">Next article</a>
</section>
```
Or what about some kind of button bar for controlling your app? This might not necessarily want a heading, but it is still a distinct section of the document:
```
<section>
<button class="reply">Reply</button>
<button class="reply-all">Reply to all</button>
<button class="fwd">Forward</button>
<button class="del">Delete</button>
</section>
```
Make sure to use some assistive technology and screen-reader-friendly CSS to hide it, like so:
```
.hidden {
position: absolute;
top: -9999px;
left: -9999px;
}
```
Depending on the content, including a heading could also be good for SEO, so it is an option to consider.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [Sectioning content](../content_categories#sectioning_content), [palpable content](../content_categories#palpable_content). |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). Note that a `<section>` element must not be a descendant of an [`<address>`](address) element. |
| Implicit ARIA role | `[region](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/region_role)` if the element has an [accessible name](https://developer.paciellogroup.com/blog/2017/04/what-is-an-accessible-name/), otherwise [no corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[alert](https://w3c.github.io/aria/#alert)`, `[alertdialog](https://w3c.github.io/aria/#alertdialog)`, `[application](https://w3c.github.io/aria/#application)`, `[banner](https://w3c.github.io/aria/#banner)`, `[complementary](https://w3c.github.io/aria/#complementary)`, `[contentinfo](https://w3c.github.io/aria/#contentinfo)`, `[dialog](https://w3c.github.io/aria/#dialog)`, `[document](https://w3c.github.io/aria/#document)`, `[feed](https://w3c.github.io/aria/#feed)`, `[log](https://w3c.github.io/aria/#log)`, `[main](https://w3c.github.io/aria/#main)`, `[marquee](https://w3c.github.io/aria/#marquee)`, `[navigation](https://w3c.github.io/aria/#navigation)`, `[none](https://w3c.github.io/aria/#none)`, `[note](https://w3c.github.io/aria/#note)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[search](https://w3c.github.io/aria/#search)`, `[status](https://w3c.github.io/aria/#status)`, `[tabpanel](https://w3c.github.io/aria/#tabpanel)` |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-section-element](https://html.spec.whatwg.org/multipage/sections.html#the-section-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `section` | 5 | 12 | 4 | 9 | 11.1 | 5 | Yes | Yes | 4 | 11.1 | 4.2 | Yes |
See also
--------
* Other section-related elements: [`<body>`](body), [`<nav>`](nav), [`<article>`](article), [`<aside>`](aside), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<hgroup>`](hgroup), [`<header>`](header), [`<footer>`](footer), [`<address>`](address)
* [Using HTML sections and outlines](heading_elements)
* [ARIA: Region role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/region_role)
* [Why You Should Choose HTML5 article Over section](https://www.smashingmagazine.com/2020/01/html5-article-section/), by Bruce Lawson
html <big>: The Bigger Text element <big>: The Bigger Text element
==============================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<big>` [HTML](../index) deprecated element renders the enclosed text at a font size one level larger than the surrounding text (`medium` becomes `large`, for example). The size is capped at the browser's maximum permitted font size.
**Warning:** This element has been removed from the specification and shouldn't be used anymore. Use the CSS [`font-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) property to adjust the font size.
Attributes
----------
This element has no other attributes than the [global attributes](../global_attributes), common to all elements.
Examples
--------
Here we see examples showing the use of `<big>` followed by an example showing how to accomplish the same results using modern CSS syntax instead.
### Using big
This example uses the obsolete `<big>` element to increase the size of some text.
#### HTML
```
<p>
This is the first sentence.
<big>This whole sentence is in bigger letters.</big>
</p>
```
#### Result
### Using CSS `font-size`
This example uses the CSS [`font-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) property to increase the font size by one level.
#### CSS
```
.bigger {
font-size: larger;
}
```
#### HTML
```
<p>
This is the first sentence.
<span class="bigger">This whole sentence is in bigger letters.</span>
</p>
```
#### Result
DOM interface
-------------
This element implements the [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # big](https://html.spec.whatwg.org/multipage/obsolete.html#big) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `big` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* CSS: [`font-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size), [`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font)
* HTML: [`<small>`](small), [`<font>`](font), [`<style>`](style)
* HTML 4.01 Specification: [Font Styles](https://www.w3.org/TR/html4/present/graphics.html#h-15.2)
html <blockquote>: The Block Quotation element <blockquote>: The Block Quotation element
=========================================
The `<blockquote>` [HTML](../index) element indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see [Notes](#usage_notes) for how to change it). A URL for the source of the quotation may be given using the `cite` attribute, while a text representation of the source can be given using the [`<cite>`](cite) element.
Try it
------
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`cite`**](#attr-cite) A URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote.
Usage notes
-----------
To change the indentation applied to the quoted text, use the [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS) [`margin-left`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left) and/or [`margin-right`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right) properties, or the [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) shorthand property.
To include shorter quotes inline rather than in a separate block, use the [`<q>`](q) (Quotation) element.
Example
-------
This example demonstrates the use of the `<blockquote>` element to quote a passage from [RFC 1149](https://datatracker.ietf.org/doc/html/rfc1149), *A Standard for the Transmission of IP Datagrams on Avian Carriers*.
```
<blockquote cite="https://datatracker.ietf.org/doc/html/rfc1149">
<p>
Avian carriers can provide high delay, low throughput, and low altitude
service. The connection topology is limited to a single point-to-point path
for each carrier, used with standard carriers, but many carriers can be used
without significant interference with each other, outside early spring.
This is because of the 3D ether space available to the carriers, in contrast
to the 1D ether used by IEEE802.3. The carriers have an intrinsic collision
avoidance system, which increases availability.
</p>
</blockquote>
```
The output from this HTML snippet looks like this:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), sectioning root, palpable content. |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLQuoteElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLQuoteElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-blockquote-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-blockquote-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `blockquote` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `cite` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The [`<q>`](q) element for inline quotations.
* The [`<cite>`](cite) element for source citations.
html <acronym> <acronym>
=========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Summary
-------
The `<acronym>` [HTML](../index) element allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word.
**Warning:** Don't use this element. Use the [`<abbr>`](abbr) element instead.
Attributes
----------
This element only has [global attributes](../global_attributes), which are common to all elements.
DOM Interface
-------------
This element implements the [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface.
Example
-------
```
<p>
The <acronym title="World Wide Web">WWW</acronym> is only a component of the
Internet.
</p>
```
Default styling
---------------
Though the purpose of this tag is purely for the convenience of the author, its default styling varies from one browser to another:
* Some browsers, like Internet Explorer, do not style it differently than a [`<span>`](span) element.
* Opera, Firefox, Chrome, and some others add a dotted underline to the content of the element.
* A few browsers not only add a dotted underline, but also put it in small caps; to avoid this styling, adding something like [`font-variant`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant)`: none` in the CSS takes care of this case.
It is therefore recommended that web authors either explicitly style this element, or accept some cross-browser variation.
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # acronym](https://html.spec.whatwg.org/multipage/obsolete.html#acronym) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `acronym` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* The [`<abbr>`](abbr) HTML element
| programming_docs |
html <template>: The Content Template element <template>: The Content Template element
========================================
The `<template>` [HTML](../index) element is a mechanism for holding [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript.
Think of a template as a content fragment that is being stored for subsequent use in the document. While the parser does process the contents of the `<template>` element while loading the page, it does so only to ensure that those contents are valid; the element's contents are not rendered, however.
Attributes
----------
The only standard attributes that the `template` element supports are the [global attributes](../global_attributes).
In Chromium-based browsers, the `template` element also supports a non-standard [`shadowroot` attribute](https://github.com/mfreed7/declarative-shadow-dom/blob/master/README.md#syntax), as part of an experimental ["Declarative Shadow DOM"](https://web.dev/declarative-shadow-dom/) proposal. In those browsers, a `template` element with the `shadowroot` attribute is detected by the HTML parser and immediately applied as the shadow root of its parent element.
Also, the [`HTMLTemplateElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement) has a standard [`content`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content) property (without a corresponding content/markup attribute), which is a read-only [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) containing the DOM subtree which the template represents. Note that directly using the value of the [`content`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content) property could lead to unexpected behavior; for details, see the [Avoiding DocumentFragment pitfall](#avoiding_documentfragment_pitfall) section below.
Examples
--------
First we start with the HTML portion of the example.
```
<table id="producttable">
<thead>
<tr>
<td>UPC_Code</td>
<td>Product_Name</td>
</tr>
</thead>
<tbody>
<!-- existing data could optionally be included here -->
</tbody>
</table>
<template id="productrow">
<tr>
<td class="record"></td>
<td></td>
</tr>
</template>
```
First, we have a table into which we will later insert content using JavaScript code. Then comes the template, which describes the structure of an HTML fragment representing a single table row.
Now that the table has been created and the template defined, we use JavaScript to insert rows into the table, with each row being constructed using the template as its basis.
```
// Test to see if the browser supports the HTML template element by checking
// for the presence of the template element's content attribute.
if ('content' in document.createElement('template')) {
// Instantiate the table with the existing HTML tbody
// and the row with the template
const tbody = document.querySelector("tbody");
const template = document.querySelector('#productrow');
// Clone the new row and insert it into the table
const clone = template.content.cloneNode(true);
let td = clone.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
tbody.appendChild(clone);
// Clone the new row and insert it into the table
const clone2 = template.content.cloneNode(true);
td = clone2.querySelectorAll("td");
td[0].textContent = "0384928528";
td[1].textContent = "Acme Kidney Beans 2";
tbody.appendChild(clone2);
} else {
// Find another way to add the rows to the table because
// the HTML template element is not supported.
}
```
The result is the original HTML table, with two new rows appended to it via JavaScript:
Avoiding DocumentFragment pitfall
---------------------------------
A [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) is not a valid target for various events, as such it is often preferable to clone or refer to the elements within it.
Consider the following HTML and JavaScript:
### HTML
```
<div id="container"></div>
<template id="template">
<div>Click me</div>
</template>
```
### JavaScript
```
const container = document.getElementById("container");
const template = document.getElementById("template");
function clickHandler(event) {
event.target.append(" — Clicked this div");
}
const firstClone = template.content.cloneNode(true);
firstClone.addEventListener("click", clickHandler);
container.appendChild(firstClone);
const secondClone = template.content.firstElementChild.cloneNode(true);
secondClone.addEventListener("click", clickHandler);
container.appendChild(secondClone);
```
### Result
`firstClone` is a DocumentFragment instance, so while it gets appended inside the container as expected, clicking on it does not trigger the click event. `secondClone` is an [HTMLDivElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement) instance, clicking on it works as one would expect.
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Metadata content](../content_categories#metadata_content), [flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [script-supporting element](../content_categories#script-supporting_elements) |
| Permitted content | No restrictions |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [metadata content](../content_categories#metadata_content), [phrasing content](../content_categories#phrasing_content), or [script-supporting elements](../content_categories#script-supporting_elements). Also allowed as a child of a [`<colgroup>`](colgroup) element that does *not* have a [`span`](colgroup#attr-span) attribute. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLTemplateElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-template-element](https://html.spec.whatwg.org/multipage/scripting.html#the-template-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `template` | 26 | 13 | 22 | No | 15 | 8 | Yes | 26 | 22 | No | 8 | 1.5 |
| `shadowroot` | 90 | 90 | No | No | No | No | 90 | 90 | No | No | No | 15.0 |
See also
--------
* Web components: [`<slot>`](slot) (and historical: [`<shadow>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/shadow))
* [Using templates and slots](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots)
html <u>: The Unarticulated Annotation (Underline) element <u>: The Unarticulated Annotation (Underline) element
=====================================================
The `<u>` [HTML](../index) element represents a span of inline text which should be rendered in a way that indicates that it has a non-textual annotation. This is rendered by default as a simple solid underline, but may be altered using CSS.
**Warning:** This element used to be called the "Underline" element in older versions of HTML, and is still sometimes misused in this way. To underline text, you should instead apply a style that includes the CSS [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) property set to `underline`.
Try it
------
See the [Usage notes](#usage_notes) section for further details on when it's appropriate to use `<u>` and when it isn't.
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
Along with other pure styling elements, the original HTML Underline (`<u>`) element was deprecated in HTML 4; however, `<u>` was restored in HTML 5 with a new, semantic, meaning: to mark text as having some form of non-textual annotation applied.
**Note:** Avoid using the `<u>` element with its default styling (of underlined text) in such a way as to be confused with a hyperlink, which is also underlined by default.
### Use cases
Valid use cases for the `<u>` element include annotating spelling errors, applying a [proper name mark](https://en.wikipedia.org/wiki/Proper_name_mark) to denote proper names in Chinese text, and other forms of annotation.
You should *not* use `<u>` to underline text for presentation purposes, or to denote titles of books.
### Other elements to consider using
In most cases, you should use an element other than `<u>`, such as:
* [`<em>`](em) to denote stress emphasis
* [`<b>`](b) to draw attention to text
* [`<mark>`](mark) to mark key words or phrases
* [`<strong>`](strong) to indicate that text has strong importance
* [`<cite>`](cite) to mark the titles of books or other publications
* [`<i>`](i) to denote technical terms, transliterations, thoughts, or names of vessels in Western texts
To provide textual annotations (as opposed to the non-textual annotations created with `<u>`), use the [`<ruby>`](ruby) element.
To apply an underlined appearance without any semantic meaning, use the [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) property's value `underline`.
Examples
--------
### Indicating a spelling error
This example uses the `<u>` element and some CSS to display a paragraph which includes a misspelled error, with the error indicated in the red wavy underline style which is fairly commonly used for this purpose.
#### HTML
```
<p>This paragraph includes a <u class="spelling">wrnogly</u> spelled word.</p>
```
In the HTML, we see the use of `<u>` with a class, `spelling`, which is used to indicate the misspelling of the word "wrongly".
#### CSS
```
u.spelling {
text-decoration: red wavy underline;
}
```
This CSS indicates that when the `<u>` element is styled with the class `spelling`, it should have a red wavy underline underneath its text. This is a common styling for spelling errors. Another common style can be presented using `red dashed underline`.
#### Result
The result should be familiar to anyone who has used any of the more popular word processors available today.
### Avoiding <u>
Most of the time, you actually don't want to use `<u>`. Here are some examples that show what you should do instead in several cases.
#### Non-semantic underlines
To underline text without implying any semantic meaning, use a [`<span>`](span) element with the [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) property set to `"underline"`, as shown below.
##### HTML
```
<span class="underline">Today's Special</span>
<br />
Chicken Noodle Soup With Carrots
```
##### CSS
```
.underline {
text-decoration: underline;
}
```
##### Result
#### Presenting a book title
Book titles should be presented using the [`<cite>`](cite) element instead of `<u>` or even `<i>`.
##### Using the cite element
```
<p>The class read <cite>Moby Dick</cite> in the first term.</p>
```
##### Styling the cite element
The default styling for the `<cite>` element renders the text in italics. You can override that using CSS:
```
<p>The class read <cite>Moby Dick</cite> in the first term.</p>
```
```
cite {
font-style: normal;
text-decoration: underline;
}
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-u-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-u-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `u` | Yes | 12 | 1
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* The [`<span>`](span), [`<i>`](i), [`<em>`](em), [`<b>`](b), and [`<cite>`](cite) elements should usually be used instead.
* The CSS [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) property should be used for non-semantic underlining.
html <code>: The Inline Code element <code>: The Inline Code element
===============================
The `<code>` [HTML](../index) element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) default monospace font.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Example
-------
A paragraph of text that includes `<code>`:
```
<p>
The function <code>selectAll()</code> highlights all the text in the input
field so the user can, for example, copy or delete the text.
</p>
```
The output generated by this HTML looks like this:
Notes
-----
To represent multiple lines of code, wrap the `<code>` element within a [`<pre>`](pre) element. The `<code>` element by itself only represents a single phrase of code or line of code.
A CSS rule can be defined for the `code` selector to override the browser's default font face. Preferences set by the user might take precedence over the specified CSS.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the [`HTMLSpanElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement) interface for this element. |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-code-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-code-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `code` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<samp>`](samp)
* [`<kbd>`](kbd)
* `<command>` (deprecated)
* [`<var>`](var)
* [`<pre>`](pre)
html <footer> <footer>
========
The `<footer>` [HTML](../index) element represents a footer for its nearest ancestor [sectioning content](../content_categories#sectioning_content) or [sectioning root](heading_elements#sectioning_root) element. A `<footer>` typically contains information about the author of the section, copyright data or links to related documents.
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), palpable content. |
| Permitted content | [Flow content](../content_categories#flow_content), but with no `<footer>` or [`<header>`](header) descendants. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). Note that a `<footer>` element must not be a descendant of an [`<address>`](address), [`<header>`](header) or another `<footer>` element. |
| Implicit ARIA role | [contentinfo](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role), or [no corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) if a descendant of an <article>, <aside>, <main>, <nav> or <section> element, or an element with `role=[article](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/article_role)`, [complementary](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role), [main](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/main_role), [navigation](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role) or [region](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/region_role) |
| Permitted ARIA roles | `[group](https://w3c.github.io/aria/#group)`, `[presentation](https://w3c.github.io/aria/#presentation)` or `[none](https://w3c.github.io/aria/#none)` |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Enclose information about the author in an [`<address>`](address) element that can be included into the `<footer>` element.
* When the nearest ancestor sectioning content or sectioning root element is the body element the footer applies to the whole page.
* The `<footer>` element is not sectioning content and therefore doesn't introduce a new section in the [outline](heading_elements).
Examples
--------
```
<footer>
Some copyright info or perhaps some author info for an <article>?
</footer>
```
Accessibility concerns
----------------------
Prior to the release of Safari 13, the `contentinfo` [landmark role](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics#signpostslandmarks) was not properly exposed by [VoiceOver](https://help.apple.com/voiceover/info/guide/). If needing to support legacy Safari browsers, add `role="contentinfo"` to the `footer` element to ensure the landmark will be properly exposed.
* Related: [WebKit Bugzilla: 146930 – AX: HTML native elements (header, footer, main, aside, nav) should work the same as ARIA landmarks, sometimes they don't](https://bugs.webkit.org/show_bug.cgi?id=146930)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-footer-element](https://html.spec.whatwg.org/multipage/sections.html#the-footer-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `footer` | 5 | 12 | 4 | 9 | 11.1 | 5 | Yes | Yes | 4 | 11.1 | 4.2 | Yes |
See also
--------
* Other section-related elements: [`<body>`](body), [`<nav>`](nav), [`<article>`](article), [`<aside>`](aside), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<hgroup>`](hgroup), [`<header>`](header), [`<section>`](section), [`<address>`](address);
* [Using HTML sections and outlines](heading_elements)
* [ARIA: Contentinfo role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role)
| programming_docs |
html <bdi>: The Bidirectional Isolate element <bdi>: The Bidirectional Isolate element
========================================
The `<bdi>` [HTML](../index) element tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. It's particularly useful when a website dynamically inserts some text and doesn't know the directionality of the text being inserted.
Try it
------
Bidirectional text is text that may contain both sequences of characters that are arranged left-to-right (LTR) and sequences of characters that are arranged right-to-left (RTL), such as an Arabic quotation embedded in an English string. Browsers implement the [Unicode Bidirectional Algorithm](https://www.w3.org/International/articles/inline-bidi-markup/uba-basics) to handle this. In this algorithm, characters are given an implicit directionality: for example, Latin characters are treated as LTR while Arabic characters are treated as RTL. Some other characters (such as spaces and some punctuation) are treated as neutral and are assigned directionality based on that of their surrounding characters.
Usually, the bidirectional algorithm will do the right thing without the author having to provide any special markup but, occasionally, the algorithm needs help. That's where `<bdi>` comes in.
The `<bdi>` element is used to wrap a span of text and instructs the bidirectional algorithm to treat this text in isolation from its surroundings. This works in two ways:
* The directionality of text embedded in `<bdi>` *does not influence* the directionality of the surrounding text.
* The directionality of text embedded in `<bdi>` *is not influenced by* the directionality of the surrounding text.
For example, consider some text like:
```
EMBEDDED-TEXT - 1st place
```
If `EMBEDDED-TEXT` is LTR, this works fine. But if `EMBEDDED-TEXT` is RTL, then `- 1` will be treated as RTL text (because it consists of neutral and weak characters). The result will be garbled:
```
1 - EMBEDDED-TEXTst place
```
If you know the directionality of `EMBEDDED-TEXT` in advance, you can fix this problem by wrapping `EMBEDDED-TEXT` in a [`<span>`](span) with the [`dir`](../global_attributes#dir) attribute set to the known directionality. But if you don't know the directionality - for example, because `EMBEDDED-TEXT` is being read from a database or entered by the user - you should use `<bdi>` to prevent the directionality of `EMBEDDED-TEXT` from affecting its surroundings.
Though the same visual effect can be achieved using the CSS rule [`unicode-bidi`](https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi)`: isolate` on a [`<span>`](span) or another text-formatting element, HTML authors should not use this approach because it is not semantic and browsers are allowed to ignore CSS styling.
Embedding the characters in `<span dir="auto">` has the same effect as using `<bdi>`, but its semantics are less clear.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes), except that the [`dir`](../global_attributes#dir) attribute behaves differently than normal: it defaults to `auto`, meaning its value is never inherited from the parent element. This means that unless you specify a value of either `rtl` or `ltr` for `dir`, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) will determine the correct directionality to use based on the contents of the `<bdi>`.
Examples
--------
### No bdi with only LTR
This example lists the winners of a competition using [`<span>`](span) elements only. When the names only contain LTR text the results look fine:
```
<ul>
<li><span class="name">Henrietta Boffin</span> - 1st place</li>
<li><span class="name">Jerry Cruncher</span> - 2nd place</li>
</ul>
```
### No bdi with RTL text
This example lists the winners of a competition using [`<span>`](span) elements only, and one of the winners has a name consisting of RTL text. In this case the "`- 1`", which consists of characters with neutral or weak directionality, will adopt the directionality of the RTL text, and the result will be garbled:
```
<ul>
<li><span class="name">اَلأَعْشَى</span> - 1st place</li>
<li><span class="name">Jerry Cruncher</span> - 2nd place</li>
</ul>
```
### Using bdi with LTR and RTL text
This example lists the winners of a competition using `<bdi>` elements. These elements instruct the browser to treat the name in isolation from its embedding context, so the example output is properly ordered:
```
<ul>
<li><bdi class="name">اَلأَعْشَى</bdi> - 1st place</li>
<li><bdi class="name">Jerry Cruncher</bdi> - 2nd place</li>
</ul>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-bdi-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-bdi-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `bdi` | 16 | 79 | 10 | No | 15 | 6 | ≤37 | 18 | 10 | 14 | 6 | 1.0 |
See also
--------
* [Inline markup and bidirectional text in HTML](https://www.w3.org/International/articles/inline-bidi-markup/)
* [Unicode Bidirectional Algorithm basics](https://www.w3.org/International/articles/inline-bidi-markup/uba-basics)
* [Localization](https://developer.mozilla.org/en-US/docs/Glossary/Localization)
* Related HTML element: [`<bdo>`](bdo)
* Related CSS properties: [`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction), [`unicode-bidi`](https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi)
html <small>: the side comment element <small>: the side comment element
=================================
The `<small>` [HTML](../index) element represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font-size smaller, such as from `small` to `x-small`.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
### Basic usage
```
<p>
This is the first sentence.
<small>This whole sentence is in small letters.</small>
</p>
```
### CSS alternative
```
<p>
This is the first sentence.
<span style="font-size:0.8em">This whole sentence is in small letters.</span>
</p>
```
Notes
-----
Although the `<small>` element, like the [`<b>`](b) and [`<i>`](i) elements, may be perceived to violate the principle of separation between structure and presentation, all three are valid in HTML. Authors are encouraged to use their best judgement when determining whether to use `<small>` or CSS.
Technical summary
-----------------
| | |
| --- | --- |
| Content categories | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content) |
| Permitted content | [Phrasing content](../content_categories#phrasing_content) |
| Tag omission | None; must have both a start tag and an end tag. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content), or any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-small-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-small-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `small` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<b>`](b)
* [`<sub>`](sub) and [`<sup>`](sup)
* [`<font>`](font)
* [`<style>`](style)
* HTML 4.01 Specification: [Font Styles](https://www.w3.org/TR/html4/present/graphics.html#h-15.2)
html <colgroup>: The Table Column Group element <colgroup>: The Table Column Group element
==========================================
The `<colgroup>` [HTML](../index) element defines a group of columns within a table.
Try it
------
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`span`**](#attr-span) This attribute contains a positive integer indicating the number of consecutive columns the `<colgroup>` element spans. If not present, its default value is `1`.
The `span` attribute is not permitted if there are one or more [`<col>`](col) elements within the `<colgroup>`.
### Deprecated attributes
The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only.
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute specifies how horizontal alignment of each column cell content will be handled. Possible values are:
* `left`, aligning the content to the left of the cell
* `center`, centering the content in the cell
* `right`, aligning the content to the right of the cell
* `justify`, inserting spaces into the textual content so that the content is justified in the cell
* `char`, aligning the textual content on a special character with a minimal offset, defined by the [`char`](col#attr-char) and [`charoff`](col#attr-charoff) attributes.
If this attribute is not set, the `left` value is assumed. The descendant [`<col>`](col) elements may override this value using their own [`align`](col#attr-align) attribute.
**Note:** Do not try to set the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property on a selector giving a [`<colgroup>`](colgroup) element. Because [`<td>`](td) elements are not descendant of the [`<colgroup>`](colgroup) element, they won't inherit it.
If the table doesn't use a [`colspan`](td#attr-colspan) attribute, use one `td:nth-child(an+b)` CSS selector per column, where 'a' is the total number of the columns in the table and 'b' is the ordinal position of this column in the table. Only after this selector the `text-align` property can be used.
If the table does use a [`colspan`](td#attr-colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial.
[**`bgcolor`**](#attr-bgcolor) Deprecated
The background color of the table. It is a [6-digit hexadecimal RGB code](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors), prefixed by a '`#`'. One of the predefined [color keywords](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) can also be used.
To achieve a similar effect, use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property.
[**`char`**](#attr-char) Deprecated
This attribute specifies the alignment of the content in a column group to a character. Typical values for this include a period (.) when attempting to align numbers or monetary values. If [`align`](colgroup#attr-align) is not set to `char`, this attribute is ignored, though it will still be used as the default value for the [`align`](col#attr-align) of the [`<col>`](col) which are members of this column group.
[**`charoff`**](#attr-charoff) Deprecated
This attribute is used to indicate the number of characters to offset the column data from the alignment character specified by the `char` attribute.
[**`valign`**](#attr-valign) Deprecated
This attribute specifies the vertical alignment of the text within each cell of the column. Possible values for this attribute are:
* `baseline`, which will put the text as close to the bottom of the cell as it is possible, but align it on the [baseline](https://en.wikipedia.org/wiki/Baseline_%28typography%29) of the characters instead of the bottom of them. If characters are all of the size, this has the same effect as `bottom`.
* `bottom`, which will put the text as close to the bottom of the cell as it is possible;
* `middle`, which will center the text in the cell;
* and `top`, which will put the text as close to the top of the cell as it is possible.
**Note:** Do not try to set the [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property on a selector giving a `<colgroup>` element. Because [`<td>`](td) elements are not descendant of the `<colgroup>` element, they won't inherit it.
If the table doesn't use a [`colspan`](td#attr-colspan) attribute, use the `td:nth-child(an+b)` CSS selector per column, where 'a' is the total number of the columns in the table and 'b' is the ordinal position of the column in the table. Only after this selector the `vertical-align` property can be used.
If the table does use a [`colspan`](td#attr-colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial.
Examples
--------
Please see the [`<table>`](table) page for examples on `<colgroup>`.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | If the [`span`](colgroup#attr-span) attribute is present: none.If the attribute is not present: zero or more [`<col>`](col) element |
| Tag omission | The start tag may be omitted, if it has a [`<col>`](col) element as its first child and if it is not preceded by a [`<colgroup>`](colgroup) whose end tag has been omitted.The end tag may be omitted, if it is not followed by a space or a comment. |
| Permitted parents | A [`<table>`](table) element. The [`<colgroup>`](colgroup) must appear after any optional [`<caption>`](caption) element but before any [`<thead>`](thead), [`<th>`](th), [`<tbody>`](tbody), [`<tfoot>`](tfoot) and [`<tr>`](tr) element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLTableColElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-colgroup-element](https://html.spec.whatwg.org/multipage/tables.html#the-colgroup-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `colgroup` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `char` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `charoff` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `span` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `valign` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `width` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* CSS properties and [pseudo-classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes) that may be specially useful to style the `<col>` element:
+ the [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property to control the width of the column;
+ the [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child) pseudo-class to set the alignment on the cells of the column;
+ the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to align all cells content on the same character, like '.'.
html <source>: The Media or Image Source element <source>: The Media or Image Source element
===========================================
The `<source>` [HTML](../index) element specifies multiple media resources for the [`<picture>`](picture), the [`<audio>`](audio) element, or the [`<video>`](video) element. It is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element), meaning that it has no content and does not have a closing tag. It is commonly used to offer the same media content in multiple file formats in order to provide compatibility with a broad range of browsers given their differing support for [image file formats](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types) and [media file formats](https://developer.mozilla.org/en-US/docs/Web/Media/Formats).
Try it
------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | It must have a start tag, but must not have an end tag. |
| Permitted parents | A media element—[`<audio>`](audio) or [`<video>`](video)—and it must be placed before any [flow content](../content_categories#flow_content) or [`<track>`](track) element. A [`<picture>`](picture) element, and it must be placed before the [`<img>`](img) element. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLSourceElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSourceElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`type`**](#attr-type) The [MIME media type of the image](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types) or [other media type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers), optionally with a [`codecs` parameter](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter).
[**`src`**](#attr-src) Required if the `source` element's parent is an [`<audio>`](audio) and [`<video>`](video) element, but not allowed if the `source` element's parent is a [`<picture>`](picture) element.
Address of the media resource.
[**`srcset`**](#attr-srcset) Required if the `source` element's parent is a [`<picture>`](picture) element, but not allowed if the `source` element's parent is an [`<audio>`](audio) or [`<video>`](video) element.
A list of one or more strings, separated by commas, indicating a set of possible images represented by the source for the browser to use. Each string is composed of:
1. One URL specifying an image.
2. A width descriptor, which consists of a string containing a positive integer directly followed by `"w"`, such as `300w`. The default value, if missing, is the infinity.
3. A pixel density descriptor, that is a positive floating number directly followed by `"x"`. The default value, if missing, is `1x`.
Each string in the list must have at least a width descriptor or a pixel density descriptor to be valid. Among the list, there must be only one string containing the same tuple of width descriptor and pixel density descriptor. The browser chooses the most adequate image to display at a given point of time. If width descriptors are used, the `sizes` attribute must also be present, or the `srcset` value will be ignored.
[**`sizes`**](#attr-sizes) Allowed if the `source` element's parent is a [`<picture>`](picture) element, but not allowed if the `source` element's parent is an [`<audio>`](audio) or [`<video>`](video) element.
A list of source sizes that describes the final rendered width of the image represented by the source. Each source size consists of a comma-separated list of media condition-length pairs. This information is used by the browser to determine, before laying the page out, which image defined in [`srcset`](source#attr-srcset) to use. Please note that `sizes` will have its effect only if width dimension descriptors are provided with `srcset` instead of pixel ratio values (200w instead of 2x for example).
[**`media`**](#attr-media) Allowed if the `source` element's parent is a [`<picture>`](picture) element, but not allowed if the `source` element's parent is an [`<audio>`](audio) or [`<video>`](video) element.
[Media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) of the resource's intended media.
[**`height`**](#attr-height) Allowed if the `source` element's parent is a [`<picture>`](picture) element, but not allowed if the `source` element's parent is an [`<audio>`](audio) or [`<video>`](video) element.
The intrinsic height of the image, in pixels. Must be an integer without a unit.
[**`width`**](#attr-width) Allowed if the `source` element's parent is a [`<picture>`](picture) element, but not allowed if the `source` element's parent is an [`<audio>`](audio) or [`<video>`](video) element.
The intrinsic width of the image in pixels. Must be an integer without a unit.
If the `type` attribute isn't specified, the media's type is retrieved from the server and checked to see if the user agent can handle it; if it can't be rendered, the next `<source>` is checked. If the `type` attribute is specified, it's compared against the types the user agent can present, and if it's not recognized, the server doesn't even get queried; instead, the next `<source>` element is checked at once.
When used in the context of a `<picture>` element, the browser will fall back to using the image specified by the `<picture>` element's [`<img>`](img) child if it is unable to find a suitable image to use after examining every provided `<source>`.
Usage notes
-----------
The `<source>` element is a **[void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element)**, which means that it not only has no content but also has no closing tag. That is, you *never* use "`</source>`" in your HTML.
For information about image formats supported by web browsers and guidance on selecting appropriate formats to use, see our [Image file type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types) on the web. For details on the video and audio media types you can use, see the [Guide to media types formats used on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats).
Examples
--------
### Video example
This example demonstrates how to offer a video in Ogg format for users whose browsers support Ogg format, and a QuickTime format video for users whose browsers support that. If the `audio` or `video` element is not supported by the browser, a notice is displayed instead. If the browser supports the element but does not support any of the specified formats, an `error` event is raised and the default media controls (if enabled) will indicate an error. Be sure to reference our [guide to media types and formats on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats) for details on what media file formats you can use and how well they're supported by browsers.
```
<video controls>
<source src="foo.webm" type="video/webm" />
<source src="foo.ogg" type="video/ogg" />
<source src="foo.mov" type="video/quicktime" />
I'm sorry; your browser doesn't support HTML video.
</video>
```
For more examples, the learning area article [Video and audio content](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) is a great resource.
### Picture example
In this example, two `<source>` elements are included within the [`<picture>`](picture), providing versions of an image to use when the available space exceeds certain widths. If the available width is less than the smallest of these widths, the user agent will fall back to the image given by the [`<img>`](img) element.
```
<picture>
<source srcset="mdn-logo-wide.png" media="(min-width: 800px)" />
<source srcset="mdn-logo-medium.png" media="(min-width: 600px)" />
<img src="mdn-logo-narrow.png" alt="MDN Web Docs" />
</picture>
```
With the `<picture>` element, you must always include an `<img>` with a fallback image, with an `alt` attribute to ensure accessibility (unless the image is an irrelevant background decorative image).
### Picture with height & width attributes example
In this example, three `<source>` elements with [**`height`**](#attr-height) and [**`width`**](#attr-width) attributes are included in a [`<picture>`](picture) element. A [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) allows the browser to select an image to display with the `height` and `width` attributes based on the [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport) size.
```
<picture>
<source srcset="landscape.png" media="(min-width: 1000px)" width="1000" height="400">
<source srcset="square.png" media="(min-width: 800px)" width="800" height="800">
<source srcset="portrait.png" media="(min-width: 600px)" width="600" height="800">
<img src="fallback.png" alt="Image used when the browser does not support the sources" width="500" height="400">
</picture>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-source-element](https://html.spec.whatwg.org/multipage/embedded-content.html#the-source-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `source` | Yes | 12 | 3.5
Until Firefox 15, Firefox picked the first source element that has a type matching the MIME-type of a supported media format; see [bug 449363](https://bugzil.la/449363) for details. | 9 | Yes | Yes | Yes | Yes | 4
Until Firefox 15, Firefox picked the first source element that has a type matching the MIME-type of a supported media format; see [bug 449363](https://bugzil.la/449363) for details. | Yes | Yes | Yes |
| `height` | 90 | 12 | 108 | 9 | 76 | 15 | 90 | 90 | 108 | 64 | 15 | 15.0 |
| `media` | Yes | 12 | 15 | 9 | Yes | Yes | Yes | Yes | 15 | No | Yes | Yes |
| `sizes` | 38
34-38
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | ≤18 | 38 | No | 25
21-25
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 9.1 | 38
37-38
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 38
34-38
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 38 | 25
21-25
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 9.3 | 3.0
2.0-3.0
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). |
| `src` | Yes | 12 | 3.5 | 9 | Yes | Yes | Yes | Yes | 4 | No | Yes | Yes |
| `srcset` | 38
34-38
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | ≤18 | 38 | No | 25
21-25
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 9.1 | 38
37-38
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 38
34-38
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 38 | 25
21-25
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). | 9.3 | 3.0
2.0-3.0
Supports a subset of the syntax for resolution switching (using the `x` descriptor), but not the full syntax that can be used with `sizes` (using the `w` descriptor). |
| `type` | Yes | 12 | 3.5 | 9 | Yes | Yes | Yes | Yes | 4 | No | Yes | Yes |
| `width` | 90 | 12 | 108 | 9 | 76 | 15 | 90 | 90 | 108 | 64 | 15 | 15.0 |
See also
--------
* [Guide to media types and formats on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats)
* [Image file type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types)
* [`<picture>`](picture) element
* [`<audio>`](audio) element
* [`<video>`](video) element
* [Web Performance](https://developer.mozilla.org/en-US/docs/Learn/Performance)
| programming_docs |
html <param>: The Object Parameter element <param>: The Object Parameter element
=====================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<param>` [HTML](../index) element defines parameters for an [`<object>`](object) element.
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`name`**](#attr-name) Deprecated
Name of the parameter.
[**`value`**](#attr-value) Deprecated
Specifies the value of the parameter.
[**`type`**](#attr-type) Deprecated
Only used if the `valuetype` is set to `ref`. Specifies the MIME type of values found at the URI specified by value.
[**`valuetype`**](#attr-valuetype) Deprecated
Specifies the type of the `value` attribute. Possible values are:
* `data`: Default value. The value is passed to the object's implementation as a string.
* `ref`: The value is a URI to a resource where run-time values are stored.
* `object`: An ID of another [`<object>`](object) in the same document.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | As it is a void element, the start tag must be present and the end tag must not be present. |
| Permitted parents | An [`<object>`](object) before any [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLParamElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLParamElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-param-element](https://html.spec.whatwg.org/multipage/obsolete.html#the-param-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `param` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `name` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `value` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `valuetype` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`<object>`](object)
html <marquee>: The Marquee element <marquee>: The Marquee element
==============================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<marquee>` [HTML](../index) element is used to insert a scrolling area of text. You can control what happens when the text reaches the edges of its content area using its attributes.
Attributes
----------
[**`behavior`**](#attr-behavior) Deprecated
Sets how the text is scrolled within the marquee. Possible values are `scroll`, `slide` and `alternate`. If no value is specified, the default value is `scroll`.
[**`bgcolor`**](#attr-bgcolor) Deprecated
Sets the background color through color name or hexadecimal value.
[**`direction`**](#attr-direction) Deprecated
Sets the direction of the scrolling within the marquee. Possible values are `left`, `right`, `up` and `down`. If no value is specified, the default value is `left`.
[**`height`**](#attr-height) Deprecated
Sets the height in pixels or percentage value.
[**`hspace`**](#attr-hspace) Deprecated
Sets the horizontal margin
[**`loop`**](#attr-loop) Deprecated
Sets the number of times the marquee will scroll. If no value is specified, the default value is −1, which means the marquee will scroll continuously.
[**`scrollamount`**](#attr-scrollamount) Deprecated
Sets the amount of scrolling at each interval in pixels. The default value is 6.
[**`scrolldelay`**](#attr-scrolldelay) Deprecated
Sets the interval between each scroll movement in milliseconds. The default value is 85. Note that any value smaller than 60 is ignored and the value 60 is used instead unless `truespeed` is specified.
[**`truespeed`**](#attr-truespeed) Deprecated
By default, `scrolldelay` values lower than 60 are ignored. If `truespeed` is present, those values are not ignored.
[**`vspace`**](#attr-vspace) Deprecated
Sets the vertical margin in pixels or percentage value.
[**`width`**](#attr-width) Deprecated
Sets the width in pixels or percentage value.
Event handlers
--------------
[**`onbounce`**](#attr-onbounce) Fires when the marquee has reached the end of its scroll position. It can only fire when the behavior attribute is set to `alternate`.
[**`onfinish`**](#attr-onfinish) Fires when the marquee has finished the amount of scrolling that is set by the loop attribute. It can only fire when the loop attribute is set to some number that is greater than 0.
[**`onstart`**](#attr-onstart) Fires when the marquee starts scrolling.
Methods
-------
`start()` Starts scrolling of the marquee.
`stop()` Stops scrolling of the marquee.
Examples
--------
```
<marquee>This text will scroll from right to left</marquee>
<marquee direction="up">This text will scroll from bottom to top</marquee>
<marquee
direction="down"
width="250"
height="200"
behavior="alternate"
style="border:solid">
<marquee behavior="alternate"> This text will bounce </marquee>
</marquee>
```
Technical Summary
-----------------
| | |
| --- | --- |
| DOM interface | [`HTMLMarqueeElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMarqueeElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-marquee-element-2](https://html.spec.whatwg.org/multipage/rendering.html#the-marquee-element-2) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `marquee` | 1 | 12 | 65
1
Implements the `HTMLDivElement` interface. | 2 | 7.2 | 1.2 | 4.4 | 18 | 65
4
Implements the `HTMLDivElement` interface. | 10.1 | 1 | 1.0 |
| `behavior` | 1 | 12 | 1 | 2 | 7.2 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `bgcolor` | 1 | 12 | 1 | 2 | 7.2 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `direction` | 1 | 12 | 1 | 2 | 7.2 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `height` | 1 | 12 | 1 | 2 | 7.2 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `hspace` | 1 | 12 | 3 | 5.5 | 15 | 1.2 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `loop` | 1 | 12 | 3 | 5.5 | 15 | 1.2 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `scrollamount` | 1 | 12 | 1 | 2 | 7.2 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `scrolldelay` | 1 | 12 | 1 | 2 | 7.2 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `truespeed` | 1 | 12 | 3 | 4 | 15 | 1.2 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `vspace` | 1 | 12 | 3 | 5.5 | 15 | 1.2 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 2 | 7.2 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
See also
--------
* [`HTMLMarqueeElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMarqueeElement)
html <ul>: The Unordered List element <ul>: The Unordered List element
================================
The `<ul>` [HTML](../index) element represents an unordered list of items, typically rendered as a bulleted list.
Try it
------
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`compact`**](#attr-compact) Deprecated Non-standard
This Boolean attribute hints that the list should be rendered in a compact style. The interpretation of this attribute depends on the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent), and it doesn't work in all browsers.
**Warning:** Do not use this attribute, as it has been deprecated: use [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) instead. To give a similar effect as the `compact` attribute, the CSS property [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) can be used with a value of `80%`.
[**`type`**](#attr-type) Deprecated Non-standard
This attribute sets the bullet style for the list. The values defined under HTML3.2 and the transitional version of HTML 4.0/4.01 are:
* `circle`
* `disc`
* `square`
A fourth bullet type has been defined in the WebTV interface, but not all browsers support it: `triangle`.
If not present and if no [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) [`list-style-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type) property applies to the element, the user agent selects a bullet type depending on the nesting level of the list.
**Warning:** Do not use this attribute, as it has been deprecated; use the [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) [`list-style-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type) property instead.
Usage notes
-----------
* The `<ul>` element is for grouping a collection of items that do not have a numerical ordering, and their order in the list is meaningless. Typically, unordered-list items are displayed with a bullet, which can be of several forms, like a dot, a circle, or a square. The bullet style is not defined in the HTML description of the page, but in its associated CSS, using the [`list-style-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type) property.
* The `<ul>` and [`<ol>`](ol) elements may be nested as deeply as desired. Moreover, the nested lists may alternate between `<ol>` and `<ul>` without restriction.
* The [`<ol>`](ol) and `<ul>` elements both represent a list of items. They differ in that, with the [`<ol>`](ol) element, the order is meaningful. To determine which one to use, try changing the order of the list items; if the meaning is changed, the [`<ol>`](ol) element should be used, otherwise you can use `<ul>`.
Examples
--------
### Simple example
```
<ul>
<li>first item</li>
<li>second item</li>
<li>third item</li>
</ul>
```
The above HTML will output:
### Nesting a list
```
<ul>
<li>first item</li>
<li>
second item
<!-- Look, the closing </li> tag is not placed here! -->
<ul>
<li>second item first subitem</li>
<li>
second item second subitem
<!-- Same for the second nested unordered list! -->
<ul>
<li>second item second subitem first sub-subitem</li>
<li>second item second subitem second sub-subitem</li>
<li>second item second subitem third sub-subitem</li>
</ul>
</li>
<!-- Closing </li> tag for the li that
contains the third unordered list -->
<li>second item third subitem</li>
</ul>
<!-- Here is the closing </li> tag -->
</li>
<li>third item</li>
</ul>
```
The above HTML will output:
### Ordered list inside unordered list
```
<ul>
<li>first item</li>
<li>
second item
<!-- Look, the closing </li> tag is not placed here! -->
<ol>
<li>second item first subitem</li>
<li>second item second subitem</li>
<li>second item third subitem</li>
</ol>
<!-- Here is the closing </li> tag -->
</li>
<li>third item</li>
</ul>
```
The above HTML will output:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), and if the `<ul>` element's children include at least one [`<li>`](li) element, [palpable content](../content_categories#palpable_content). |
| Permitted content | Zero or more [`<li>`](li), [`<script>`](script) and [`<template>`](template) elements. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | `[list](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/list_role)` |
| Permitted ARIA roles | `[directory](https://w3c.github.io/aria/#directory)`, `[group](https://w3c.github.io/aria/#group)`, `[listbox](https://w3c.github.io/aria/#listbox)`, `[menu](https://w3c.github.io/aria/#menu)`, `[menubar](https://w3c.github.io/aria/#menubar)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[radiogroup](https://w3c.github.io/aria/#radiogroup)`, `[tablist](https://w3c.github.io/aria/#tablist)`, `[toolbar](https://w3c.github.io/aria/#toolbar)`, `[tree](https://w3c.github.io/aria/#tree)` |
| DOM Interface | [`HTMLUListElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLUListElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-ul-element](https://html.spec.whatwg.org/multipage/grouping-content.html#the-ul-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ul` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `compact` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Other list-related HTML Elements: [`<ol>`](ol), [`<li>`](li), [`<menu>`](menu)
* CSS properties that may be specially useful to style the `<ul>` element:
+ the [`list-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style) property, to choose the way the ordinal displays.
+ [CSS counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters), to handle complex nested lists.
+ the [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) property, to simulate the deprecated [`compact`](ul#attr-compact) attribute.
+ the [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) property, to control the list indentation.
html <script>: The Script element <script>: The Script element
============================
The `<script>` [HTML](../index) element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The `<script>` element can also be used with other languages, such as [WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API)'s GLSL shader programming language and [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON).
| | |
| --- | --- |
| [Content categories](../content_categories) | [Metadata content](../content_categories#metadata_content), [Flow content](../content_categories#flow_content), [Phrasing content](../content_categories#phrasing_content). |
| Permitted content | Dynamic script such as `text/javascript`. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [metadata content](../content_categories#metadata_content), or any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | [`HTMLScriptElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`async`**](#attr-async) For classic scripts, if the `async` attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.
For [module scripts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), if the `async` attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available.
This attribute allows the elimination of **parser-blocking JavaScript** where the browser would have to load and evaluate scripts before continuing to parse. `defer` has a similar effect in this case.
This is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
See [Browser compatibility](#browser_compatibility) for notes on browser support. See also [Async scripts for asm.js](https://developer.mozilla.org/en-US/docs/Games/Techniques/Async_scripts).
[**`crossorigin`**](#attr-crossorigin) Normal `script` elements pass minimal information to the [`window.onerror`](https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event) for scripts which do not pass the standard [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) checks. To allow error logging for sites which use a separate domain for static media, use this attribute. See [CORS settings attributes](../attributes/crossorigin) for a more descriptive explanation of its valid arguments.
[**`defer`**](#attr-defer) This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event).
Scripts with the `defer` attribute will prevent the `DOMContentLoaded` event from firing until the script has loaded and finished evaluating.
**Warning:** This attribute must not be used if the `src` attribute is absent (i.e. for inline scripts), in this case it would have no effect.
The `defer` attribute has no effect on [module scripts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) — they defer by default.
Scripts with the `defer` attribute will execute in the order in which they appear in the document.
This attribute allows the elimination of **parser-blocking JavaScript** where the browser would have to load and evaluate scripts before continuing to parse. `async` has a similar effect in this case.
[**`fetchpriority`**](#attr-fetchpriority) Experimental
Provides a hint of the relative priority to use when fetching an external script. Allowed values:
`high` Signals a high-priority fetch relative to other external scripts.
`low` Signals a low-priority fetch relative to other external scripts.
`auto` Default: Signals automatic determination of fetch priority relative to other external scripts.
[**`integrity`**](#attr-integrity) This attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. See [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
[**`nomodule`**](#attr-nomodule) This Boolean attribute is set to indicate that the script should not be executed in browsers that support [ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) — in effect, this can be used to serve fallback scripts to older browsers that do not support modular JavaScript code.
[**`nonce`**](#attr-nonce) A cryptographic nonce (number used once) to allow scripts in a [script-src Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial.
[**`referrerpolicy`**](#attr-referrerpolicy) Indicates which [referrer](https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer) to send when fetching the script, or resources fetched by the script:
* `no-referrer`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent.
* `no-referrer-when-downgrade`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent to [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)s without [TLS](https://developer.mozilla.org/en-US/docs/Glossary/TLS) ([HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS)).
* `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL), [host](https://developer.mozilla.org/en-US/docs/Glossary/Host), and [port](https://developer.mozilla.org/en-US/docs/Glossary/Port).
* `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
* `same-origin`: A referrer will be sent for [same origin](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy), but cross-origin requests will contain no referrer information.
* `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
* `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
* `unsafe-url`: The referrer will include the origin *and* the path (but not the [fragment](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins.
**Note:** An empty string value (`""`) is both the default value, and a fallback value if `referrerpolicy` is not supported. If `referrerpolicy` is not explicitly specified on the `<script>` element, it will adopt a higher-level referrer policy, i.e. one set on the whole document or domain. If a higher-level policy is not available, the empty string is treated as being equivalent to `strict-origin-when-cross-origin`.
[**`src`**](#attr-src) This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document.
[`type`](script/type) This attribute indicates the type of script represented. The value of this attribute will be one of the following:
**Attribute is not set (default), an empty string, or a JavaScript MIME type** Indicates that the script is a "classic script", containing JavaScript code. Authors are encouraged to omit the attribute if the script refers to JavaScript code rather than specify a MIME type. JavaScript MIME types are [listed in the IANA media types specification](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#javascript_types).
`module` This value causes the code to be treated as a JavaScript module. The processing of the script contents is deferred. The `charset` and `defer` attributes have no effect. For information on using `module`, see our [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) guide. Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching.
[`importmap`](script/type/importmap) This value indicates that the body of the element contains an import map. The import map is a JSON object that developers can use to control how the browser resolves module specifiers when importing [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps).
**Any other value** The embedded content is treated as a data block, and won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. All of the other attributes will be ignored, including the `src` attribute.
[**`blocking`**](#attr-blocking) This attribute explicitly indicates that certain operations should be blocked on the fetching of the script. The operations that are to be blocked must be a space-separated list of blocking attributes listed below.
* `render`: The rendering of content on the screen is blocked.
### Deprecated attributes
[**`charset`**](#attr-charset) Deprecated
If present, its value must be an ASCII case-insensitive match for "`utf-8`". It's unnecessary to specify the `charset` attribute, because documents must use UTF-8, and the `script` element inherits its character encoding from the document.
[**`language`**](#attr-language) Deprecated Non-standard
Like the `type` attribute, this attribute identifies the scripting language in use. Unlike the `type` attribute, however, this attribute's possible values were never standardized. The `type` attribute should be used instead.
Notes
-----
Scripts without [`async`](script#attr-async), [`defer`](script#attr-defer) or `type="module"` attributes, as well as inline scripts without the `type="module"` attribute, are fetched and executed immediately, before the browser continues to parse the page.
The script should be served with the `text/javascript` MIME type, but browsers are lenient and only block them if the script is served with an image type (`image/*`), a video type (`video/*`), an audio type (`audio/*`), or `text/csv`. If the script is blocked, an [`error`](https://developer.mozilla.org/en-US/docs/Web/API/Element/error_event) event is sent to the element; otherwise, a `load` event is sent.
Examples
--------
### Basic usage
These examples show how to import (an external) script using the `<script>` element.
```
<script src="javascript.js"></script>
```
And the following examples show how to put (an inline) script inside the `<script>` element.
```
<script>
alert("Hello World!");
</script>
```
### Module fallback
Browsers that support the `module` value for the [`type`](script#attr-type) attribute ignore any script with a `nomodule` attribute. That enables you to use module scripts while also providing `nomodule`-marked fallback scripts for non-supporting browsers.
```
<script type="module" src="main.js"></script>
<script nomodule src="fallback.js"></script>
```
### Importing modules with importmap
When importing modules in scripts, if you don't use the [`type=importmap`](#importmap) feature, then each module must be imported using a module specifier that is either an absolute or relative URL. In the example below, the first module specifier ("./shapes/square.js") resolves relative to the base URL of the document, while the second is an absolute URL.
```
import { name as squareName, draw } from "./shapes/square.js";
import { name as circleName } from "https://example.com/shapes/circle.js";
```
An import map allows you to provide a mapping that, if matched, can replace the text in the module specifier. The import map below defines keys `square` and `circle` that can be used as aliases for the module specifiers shown above.
```
<script type="importmap">
{
"imports": {
"square": "./shapes/square.js",
"circle": "https://example.com/shapes/circle.js"
}
}
</script>
```
This allows us to import modules using names in the module specifier (rather than absolute or relative URLs).
```
import { name as squareName, draw } from "square";
import { name as circleName } from "circle";
```
For more examples of what you can do with import maps, see the [Importing modules using import maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) section in the JavaScript modules guide.
### Embedding data in HTML
You can also use the `<script>` element to embed data in HTML with server-side rendering by specifying a valid non-JavaScript MIME type in the `type` attribute.
```
<!-- Generated by the server -->
<script id="data" type="application/json">
{
"userId": 1234,
"userName": "Maria Cruz",
"memberSince": "2000-01-01T00:00:00.000Z"
}
</script>
<!-- Static -->
<script>
const userInfo = JSON.parse(document.getElementById("data").text);
console.log("User information: %o", userInfo);
</script>
```
### Blocking rendering till a script is fetched and executed
You can include `render` token inside a `blocking` attribute; the rendering of the page will be blocked till the script is fetched and executed. In the example below, we block rendering on an async script, so that the script doesn't block parsing but is guaranteed to be evaluated before rendering starts.
```
<script blocking="render" async src="async-script.js"></script>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-script-element](https://html.spec.whatwg.org/multipage/scripting.html#the-script-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `script` | 1 | 12 | 1
Starting in Firefox 4, inserting <script> elements that have been created by calling `document.createElement("script")` no longer enforces execution in insertion order. This change lets Firefox properly abide by the specification. To make script-inserted external scripts execute in their insertion order, set `.async=false` on them. | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `async` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `crossorigin` | 30 | ≤18 | 13 | No | 12 | Yes
The `crossorigin` attribute was implemented in WebKit in WebKit [bug 81438](https://webkit.org/b/81438). | Yes | Yes | 14 | No | No | Yes |
| `defer` | Yes
Chrome does not defer scripts with the `defer` attribute when the page is served as XHTML (`application/xhtml+xml`) - [Chromium Issue #611136](https://crbug.com/611136), [Chromium Issue #874749](https://crbug.com/874749)
| 12 | 3.5
Since Firefox 3.6, the `defer` attribute is ignored on scripts that don't have the `src` attribute. However, in Firefox 3.5 even inline scripts are deferred if the `defer` attribute is set. | 10
Before version 10, Internet Explorer implemented `defer` by a proprietary specification. Since version 10 it conforms to the W3C specification. | Yes
Opera does not defer scripts with the `defer` attribute when the page is served as XHTML (`application/xhtml+xml`) - [Chromium Issue #611136](https://crbug.com/611136), [Chromium Issue #874749](https://crbug.com/874749)
| Yes | Yes
Chrome does not defer scripts with the `defer` attribute when the page is served as XHTML (`application/xhtml+xml`) - [Chromium Issue #611136](https://crbug.com/611136), [Chromium Issue #874749](https://crbug.com/874749)
| Yes
Chrome does not defer scripts with the `defer` attribute when the page is served as XHTML (`application/xhtml+xml`) - [Chromium Issue #611136](https://crbug.com/611136), [Chromium Issue #874749](https://crbug.com/874749)
| 4 | Yes
Opera does not defer scripts with the `defer` attribute when the page is served as XHTML (`application/xhtml+xml`) - [Chromium Issue #611136](https://crbug.com/611136), [Chromium Issue #874749](https://crbug.com/874749)
| Yes | Yes
Samsung Internet does not defer scripts with the `defer` attribute when the page is served as XHTML (`application/xhtml+xml`) - [Chromium Issue #611136](https://crbug.com/611136), [Chromium Issue #874749](https://crbug.com/874749)
|
| `fetchpriority` | 101 | 101 | No | No | No | No | 101 | 101 | No | 70 | No | 19.0 |
| `integrity` | 45 | 17 | 43 | No | Yes | 11.1 | 45 | 45 | 43 | No | 11.3 | 5.0 |
| `language` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `nomodule` | 61 | 16 | 60 | No | 48 | 11 | 61 | 61 | 60 | 45 | 11 | 8.0 |
| `referrerpolicy` | 70 | ≤79 | 65 | No | Yes | 13.1 | 70 | 70 | 65 | No | 13.4 | 10.0 |
| `src` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `text` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `type` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [`document.currentScript`](https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript)
* [Ryan Grove's `<script>` and `<link>` node event compatibility chart](https://pie.gd/test/script-link-events/)
* [Flavio Copes' article on loading JavaScript efficiently and explaining the differences between `async` and `defer`](https://flaviocopes.com/javascript-async-defer/)
* [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) guide
| programming_docs |
html <abbr>: The Abbreviation element <abbr>: The Abbreviation element
================================
The `<abbr>` [HTML](../index) element represents an abbreviation or acronym.
When including an abbreviation or acronym, provide a full expansion of the term in plain text on first use, along with the `<abbr>` to mark up the abbreviation. This informs the user what the abbreviation or acronym means.
The optional [`title`](../global_attributes#title) attribute can provide an expansion for the abbreviation or acronym when a full expansion is not present. This provides a hint to user agents on how to announce/display the content while informing all users what the abbreviation means. If present, `title` must contain this full description and nothing else.
Try it
------
Attributes
----------
This element only supports the [global attributes](../global_attributes). The [`title`](../global_attributes#title) attribute has a specific semantic meaning when used with the `<abbr>` element; it *must* contain a full human-readable description or expansion of the abbreviation. This text is often presented by browsers as a tooltip when the mouse cursor is hovered over the element.
Each `<abbr>` element you use is independent of all others; providing a `title` for one does not automatically attach the same expansion text to others with the same content text.
Usage notes
-----------
### Typical use cases
It's certainly not required that all abbreviations be marked up using `<abbr>`. There are, though, a few cases where it's helpful to do so:
* When an abbreviation is used and you want to provide an expansion or definition outside the flow of the document's content, use `<abbr>` with an appropriate [`title`](../global_attributes#title).
* To define an abbreviation which may be unfamiliar to the reader, present the term using `<abbr>` and inline text providing the definition. Include a `title` attribute only when the inline expansion or definition is not available.
* When an abbreviation's presence in the text needs to be semantically noted, the `<abbr>` element is useful. This can be used, in turn, for styling or scripting purposes.
* You can use `<abbr>` in concert with [`<dfn>`](dfn) to establish definitions for terms which are abbreviations or acronyms. See the example [Defining an abbreviation](#defining_an_abbreviation) below.
### Grammar considerations
In languages with [grammatical number](https://en.wikipedia.org/wiki/Grammatical_number) (that is, languages where the number of items affects the grammar of a sentence), use the same grammatical number in your `title` attribute as inside your `<abbr>` element. This is especially important in languages with more than two numbers, such as Arabic, but is also relevant in English.
Default styling
---------------
The purpose of this element is purely for the convenience of the author and all browsers display it inline ([`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display)`: inline`) by default, though its default styling varies from one browser to another:
Some browsers add a dotted underline to the content of the element. Others add a dotted underline while converting the contents to small caps. Others may not style it differently than a [`<span>`](span) element. To control this styling, use [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) and [`font-variant`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant).
Examples
--------
### Marking up an abbreviation semantically
To mark up an abbreviation without providing an expansion or description, use `<abbr>` without any attributes, as seen in this example.
#### HTML
```
<p>Using <abbr>HTML</abbr> is fun and easy!</p>
```
#### Result
### Styling abbreviations
You can use CSS to set a custom style to be used for abbreviations, as seen in this simple example.
#### HTML
```
<p>Using <abbr>CSS</abbr>, you can style your abbreviations!</p>
```
#### CSS
```
abbr {
font-variant: all-small-caps;
}
```
#### Result
### Providing an expansion
Adding a [`title`](../global_attributes#title) attribute lets you provide an expansion or definition for the abbreviation or acronym.
#### HTML
```
<p>Ashok's joke made me <abbr title="Laugh Out Loud">LOL</abbr> big time.</p>
```
#### Result
### Defining an abbreviation
You can use `<abbr>` in tandem with [`<dfn>`](dfn) to more formally define an abbreviation, as shown here.
#### HTML
```
<p>
<dfn id="html"><abbr title="HyperText Markup Language">HTML</abbr> </dfn> is a
markup language used to create the semantics and structure of a web page.
</p>
<p>
A <dfn id="spec">Specification</dfn> (<abbr>spec</abbr>) is a document that
outlines in detail how a technology or API is intended to function and how it
is accessed.
</p>
```
#### Result
Accessibility concerns
----------------------
Spelling out the acronym or abbreviation in full the first time it is used on a page is beneficial for helping people understand it, especially if the content is technical or industry jargon.
Only include a `title` if expanding the abbreviation or acronym in the text is not possible. Having a difference between the announced word or phrase and what is displayed on the screen, especially if it's technical jargon the reader may not be familiar with, can be jarring.
### Example
```
<p>
JavaScript Object Notation (<abbr>JSON</abbr>) is a lightweight
data-interchange format.
</p>
```
This is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are new to the language, and people with cognitive concerns.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content |
| Permitted content | [Phrasing content](../content_categories#phrasing_content) |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content) |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM Interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-abbr-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-abbr-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `abbr` | 2 | 12 | 1
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | 7 | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* [Using the `<abbr>` element](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formatting#abbreviations)
html <spacer> <spacer>
========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<spacer>` [HTML](../index) element is an obsolete HTML element which allowed insertion of empty spaces on pages. It was devised by Netscape to accomplish the same effect as a single-pixel layout image, which was something web designers used to use to add white spaces to web pages without actually using an image. However, `<spacer>` is no longer supported by any major browser and the same effects can now be achieved using simple CSS.
Firefox, which is the descendant of Netscape's browsers, removed support for `<spacer>` in version 4.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes).
[**`type`**](#attr-type) This attribute determines type of spacer. Possible values are `horizontal`, `vertical` and `block`.
[**`size`**](#attr-size) This attribute can be used for defining size of spacer in pixels when type is `horizontal` or `vertical`.
[**`width`**](#attr-width) This attribute can be used for defining width of spacer in pixels when type is `block`.
[**`height`**](#attr-height) This attribute can be used for defining height of spacer in pixels when type is `block`.
[**`align`**](#attr-align) This attribute determines alignment of spacer. Possible values are `left`, `right` and `center`.
Example
-------
```
<span>Just a text node</span>
<spacer type="horizontal" size="10"></spacer>
<span>Just another text node</span>
<spacer type="block" width="10" height="10"></spacer>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # spacer](https://html.spec.whatwg.org/multipage/obsolete.html#spacer) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `spacer` | No | No | 1-4 | No | No | No | No | No | No | No | No | No |
html <strike> <strike>
========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<strike>` [HTML](../index) element places a strikethrough (horizontal line) over text.
**Warning:** This element is deprecated in HTML 4 and XHTML 1, and obsoleted in the [HTML Living Standard](https://html.spec.whatwg.org/#strike). If semantically appropriate, i.e., if it represents *deleted* content, use [`<del>`](del) instead. In all other cases use [`<s>`](s).
Attributes
----------
This element includes the [global attributes](../global_attributes).
Example
-------
```
<strike>: <strike>Today's Special: Salmon</strike> SOLD OUT<br />
<s>: <s>Today's Special: Salmon</s> SOLD OUT
```
The result of this code is:
Technical Summary
-----------------
| | |
| --- | --- |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # strike](https://html.spec.whatwg.org/multipage/obsolete.html#strike) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `strike` | Yes | 12 | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes | Yes | Yes | Yes
Before Firefox 4, this element implemented the `HTMLSpanElement` interface instead of the standard `HTMLElement` interface. | Yes | Yes | Yes |
See also
--------
* The [`<s>`](s) element.
* The [`<del>`](del) element should be used if the data has been *deleted*.
* The CSS [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) property can be used to style text with a strikethrough.
html <dfn>: The Definition element <dfn>: The Definition element
=============================
The `<dfn>` [HTML](../index) element is used to indicate the term being defined within the context of a definition phrase or sentence. The ancestor [`<p>`](p) element, the [`<dt>`](dt)/[`<dd>`](dd) pairing, or the nearest [`<section>`](section) ancestor of the `<dfn>` element, is considered to be the definition of the term.
Try it
------
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
The [`title`](../global_attributes#title) attribute has special meaning, as noted below.
Usage notes
-----------
There are some not-entirely-obvious aspects to using the `<dfn>` element. We examine those here.
### Specifying the term being defined
The term being defined is identified following these rules:
1. If the `<dfn>` element has a [`title`](../global_attributes#title) attribute, the value of the `title` attribute is considered to be the term being defined. The element must still have text within it, but that text may be an abbreviation (perhaps using [`<abbr>`](abbr)) or another form of the term.
2. If the `<dfn>` contains a single child element and does not have any text content of its own, and the child element is an [`<abbr>`](abbr) element with a `title` attribute itself, then the exact value of the `<abbr>` element's `title` is the term being defined.
3. Otherwise, the text content of the `<dfn>` element is the term being defined. This is shown [in the first example below](#basic_identification_of_a_term).
**Note:** If the `<dfn>` element has a `title` attribute, it *must* contain the term being defined and no other text.
### Links to `<dfn>` elements
If you include an [`id`](../global_attributes#id) attribute on the `<dfn>` element, you can then link to it using [`<a>`](a) elements. Such links should be uses of the term, with the intent being that the reader can quickly navigate to the term's definition if they're not already aware of it, by clicking on the term's link.
This is shown in the example under [Links to definitions](#links_to_definitions) below.
Examples
--------
Let's take a look at some examples of various usage scenarios.
### Basic identification of a term
This example uses a plain `<dfn>` element to identify the location of a term within the definition.
#### HTML
```
<p>The <strong>HTML Definition element</strong>
(<strong><dfn><dfn></dfn></strong>) is used to indicate the
term being defined within the context of a definition phrase or
sentence.</p>
```
Since the `<dfn>` element has no `title`, the text contents of the `<dfn>` element itself are used as the term being defined.
#### Result
This looks like this rendered in your browser:
### Links to definitions
To add links to the definitions, you create the link the same way you always do, with the [`<a>`](a) element.
#### HTML
```
<p>The <strong>HTML Definition element</strong>
(<strong><dfn id="definition-dfn"><dfn></dfn></strong>) is
used to indicate the term being defined within the context of a
definition phrase or sentence.</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Graece donan, Latine
voluptatem vocant. Confecta res esset. Duo Reges: constructio interrete.
Scrupulum, inquam, abeunti;
</p>
<p>
Negare non possum. Dat enim intervalla et relaxat. Quonam modo? Equidem e Cn.
Quid de Pythagora? In schola desinis.
</p>
<p>
Ubi ut eam caperet aut quando? Cur iustitia laudatur? Aperiendum est igitur,
quid sit voluptas; Quid enim? Non est igitur voluptas bonum. Urgent tamen et
nihil remittunt. Quid enim possumus hoc agere divinius?
</p>
<p>Because of all of that, we decided to use the
<code><a href="#definition-dfn"><dfn></a></code> element for
this project.</p>
```
Here we see the definition — now with an [`id`](../global_attributes#id) attribute, `"definition-dfn"`, which can be used as the target of a link. Later on, a link is created using `<a>` with the [`href`](a#attr-href) attribute set to `"#definition-dfn"` to set up the link back to the definition.
#### Result
The resulting content looks like this:
### Using abbreviations and definitions together
In some cases, you may wish to use an abbreviation for a term when defining it. This can be done by using the `<dfn>` and [`<abbr>`](abbr) elements in tandem, like this:
#### HTML
```
<p>
The <dfn><abbr title="Hubble Space Telescope">HST</abbr></dfn> is among the
most productive scientific instruments ever constructed. It has been in orbit
for over 20 years, scanning the sky and returning data and photographs of
unprecedented quality and detail.
</p>
<p>
Indeed, the <abbr title="Hubble Space Telescope">HST</abbr> has arguably done
more to advance science than any device ever built.
</p>
```
Note the `<abbr>` element nested inside the `<dfn>`. The former establishes that the term is an abbreviation ("HST") and specifies the full term ("Hubble Space Telescope") in its `title` attribute. The latter indicates that the abbreviated term represents a term being defined.
#### Result
The output of the above code looks like this:
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. |
| Permitted content | [Phrasing content](../content_categories#phrasing_content), but no [`<dfn>`](dfn) element must be a descendant. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | `[term](https://w3c.github.io/aria/#term)` |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-dfn-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-dfn-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `dfn` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* Elements related to definition lists: [`<dl>`](dl), [`<dt>`](dt), [`<dd>`](dd)
* [`<abbr>`](abbr)
html <embed>: The Embed External Content element <embed>: The Embed External Content element
===========================================
The `<embed>` [HTML](../index) element embeds external content at the specified point in the document. This content is provided by an external application or other source of interactive content such as a browser plug-in.
Try it
------
**Note:** This topic documents only the element that is defined as part of the [HTML Living Standard](https://html.spec.whatwg.org/#the-embed-element). It does not address earlier, non-standardized implementation of the element.
Keep in mind that most modern browsers have deprecated and removed support for browser plug-ins, so relying upon `<embed>` is generally not wise if you want your site to be operable on the average user's browser.
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`height`**](#attr-height) The displayed height of the resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). This must be an absolute value; percentages are *not* allowed.
[**`src`**](#attr-src) The URL of the resource being embedded.
[**`type`**](#attr-type) The [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) to use to select the plug-in to instantiate.
[**`width`**](#attr-width) The displayed width of the resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). This must be an absolute value; percentages are *not* allowed.
Usage notes
-----------
You can use the [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) property to adjust the positioning of the embedded object within the element's frame, and the [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) property to control how the object's size is adjusted to fit within the frame.
Examples
--------
```
<embed
type="video/quicktime"
src="movie.mov"
width="640"
height="480"
title="Title of my video" />
```
Accessibility concerns
----------------------
Use the [`title` attribute](../global_attributes/title) on an `embed` element to label its content so that people navigating with assistive technology such as a screen reader can understand what it contains. The title's value should concisely describe the embedded content. Without a title, they may not be able to determine what its embedded content is. This context shift can be confusing and time-consuming, especially if the `embed` element contains interactive content like video or audio.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), embedded content, interactive content, [palpable content](../content_categories#palpable_content). |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | Must have a start tag, and must not have an end tag. |
| Permitted parents | Any element that accepts embedded content. |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | `[application](https://w3c.github.io/aria/#application)`, `[document](https://w3c.github.io/aria/#document)`, `[img](https://w3c.github.io/aria/#img)`, `[none](https://w3c.github.io/aria/#none)`, `[presentation](https://w3c.github.io/aria/#presentation)` |
| DOM interface | [`HTMLEmbedElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-embed-element](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-embed-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `embed` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | 1 | 79 | 1 | No | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `height` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `name` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `src` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `type` | 1 | 79 | 1 | No | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `width` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
See also
--------
* Other elements that are used for embedding content of various types include [`<audio>`](audio), [`<canvas>`](canvas), [`<iframe>`](iframe), [`<img>`](img), `[<math>](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math)`, [`<object>`](object), [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg), and [`<video>`](video).
* Positioning and sizing the embedded content within its frame: [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) and [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
| programming_docs |
html <noframes>: The Frame Fallback element <noframes>: The Frame Fallback element
======================================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<noframes>` [HTML](../index) element provides content to be presented in browsers that don't support (or have disabled support for) the [`<frame>`](frame) element. Although most commonly-used browsers support frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers.
A `<noframes>` element can contain any HTML elements that are allowed within the body of an HTML document, except for the [`<frameset>`](frameset) and [`<frame>`](frame) elements, since using frames when they aren't supported doesn't make sense.
`<noframes>` can be used to present a message explaining that the user's browser doesn't support frames, but ideally should be used to present an alternate form of the site that doesn't use frames but still offers the same or similar functionality.
**Note:** This element is obsolete and shouldn't be used, since the [`<frame>`](frame) and [`<frameset>`](frameset) elements are also obsolete. When frames are needed at all, they should be presented using the [`<iframe>`](iframe) element.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes). It has no other attributes available.
Example
-------
In this example, we see a frameset with two frames. In addition, `<noframes>` is used to present an explanatory message if the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) doesn't support frames.
```
<frameset cols="50%,50%">
<frame src="https://developer.mozilla.org/en/HTML/Element/frameset" />
<frame src="https://developer.mozilla.org/en/HTML/Element/frame" />
<noframes>
<p>
It seems your browser does not support frames or is configured to not
allow them.
</p>
</noframes>
</frameset>
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # noframes](https://html.spec.whatwg.org/multipage/obsolete.html#noframes) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `noframes` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
See also
--------
* [`<frameset>`](frameset)
* [`<frame>`](frame)
html <header> <header>
========
The `<header>` [HTML](../index) element represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also a logo, a search form, an author name, and other elements.
Try it
------
Usage notes
-----------
The `<header>` element has an identical meaning to the site-wide [`banner`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role) landmark role, unless nested within sectioning content. Then, the `<header>` element is not a landmark.
The `<header>` element can define a global site header, described as a `banner` in the accessibility tree. It usually includes a logo, company name, search feature, and possibly the global navigation or a slogan. It is generally located at the top of the page.
Otherwise, it is a `section` in the accessibility tree, and usually contain the surrounding section's heading (an `h1` – `h6` element) and optional subheading, but this is **not** required.
### Historical Usage
The `<header>` element originally existed at the very beginning of HTML for headings. It is seen in [the very first website](http://info.cern.ch/). At some point, headings became [`<h1>` through `<h6>`](heading_elements), allowing `<header>` to be free to fill a different role.
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Examples
--------
### Page Header
```
<header>
<h1>Main Page Title</h1>
<img src="mdn-logo-sm.png" alt="MDN logo" />
</header>
```
### Article Header
```
<article>
<header>
<h2>The Planet Earth</h2>
<p>
Posted on Wednesday, <time datetime="2017-10-04">4 October 2017</time> by
Jane Smith
</p>
</header>
<p>
We live on a planet that's blue and green, with so many things still unseen.
</p>
<p><a href="https://example.com/the-planet-earth/">Continue reading…</a></p>
</article>
```
Accessibility
-------------
The `<header>` element defines a [`banner`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role) landmark when its context is the [`<body>`](body) element. The HTML header element is not considered a banner landmark when it is descendant of an [`<article>`](article), [`<aside>`](aside), [`<main>`](main), [`<nav>`](nav), or [`<section>`](section) element.
Technical summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [palpable content](../content_categories#palpable_content). |
| Permitted content | [Flow content](../content_categories#flow_content), but with no `<header>` or [`<footer>`](footer) descendant. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). Note that a `<header>` element must not be a descendant of an [`<address>`](address), [`<footer>`](footer) or another [`<header>`](header) element. |
| Implicit ARIA role | [banner](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role), or [no corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) if a descendant of an `<article>`, `<aside>`, `<main>`, `<nav>` or `<section>` element, or an element with `role=[article](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/article_role)`, `[complementary](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role)`, `[main](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/main_role)`, `[navigation](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role)` or `[region](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/region_role)` |
| Permitted ARIA roles | `[group](https://w3c.github.io/aria/#group)`, `[presentation](https://w3c.github.io/aria/#presentation)` or `[none](https://w3c.github.io/aria/#none)` |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-header-element](https://html.spec.whatwg.org/multipage/sections.html#the-header-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `header` | 5 | 12 | 4 | 9 | 11.1 | 5 | Yes | Yes | 4 | 11.1 | 4.2 | Yes |
See also
--------
* Other section-related elements: [`<body>`](body), [`<nav>`](nav), [`<article>`](article), [`<aside>`](aside), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<footer>`](footer), [`<section>`](section), [`<address>`](address).
html <keygen> <keygen>
========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<keygen>` [HTML](../index) element exists to facilitate generation of key material, and submission of the public key as part of an [HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms). This mechanism is designed for use with Web-based certificate management systems. It is expected that the `<keygen>` element will be used in an HTML form along with other information needed to construct a certificate request, and that the result of the process will be a signed certificate.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), interactive content, [listed](../content_categories#form_listed), [labelable](../content_categories#form_labelable), [submittable](../content_categories#form_submittable), [resettable](../content_categories#form_resettable) [form-associated element](../content_categories#form-associated_content), palpable content. |
| Permitted content | None; it is a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element). |
| Tag omission | Must have a start tag and must not have an end tag. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Permitted ARIA roles | None |
| DOM interface | `HTMLKeygenElement` |
Attributes
----------
This element includes the [global attributes](../global_attributes).
[**`autofocus`**](#attr-autofocus) This Boolean attribute lets you specify that the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the `autofocus` attribute, which is a Boolean.
[**`challenge`**](#attr-challenge) A challenge string that is submitted along with the public key. Defaults to an empty string if not specified.
[**`disabled`**](#attr-disabled) This Boolean attribute indicates that the form control is not available for interaction.
[**`form`**](#attr-form) The form element that this element is associated with (its *form owner*). The value of the attribute must be an `id` of a [`<form>`](form) element in the same document. If this attribute is not specified, this element must be a descendant of a [`<form>`](form) element. This attribute enables you to place `<keygen>` elements anywhere within a document, not just as descendants of their form elements.
[**`keytype`**](#attr-keytype) The type of key generated. The default value is `RSA`.
[**`name`**](#attr-name) The name of the control, which is submitted with the form data.
The element is written as follows:
```
<keygen name="name" challenge="challenge string" keytype="type"
keyparams="pqg-params">
```
The `keytype` parameter is used to specify what type of key is to be generated. Valid values are "`RSA`", which is the default, "`DSA`" and "`EC`". The `name` and `challenge` attributes are required in all cases. The `keytype` attribute is optional for RSA key generation and required for DSA and EC key generation. The `keyparams` attribute is required for DSA and EC key generation and ignored for RSA key generation. `PQG` is a synonym for `keyparams`. That is, you may specify `keyparams="pqg-params"` or `pqg="pqg-params"`.
For RSA keys, the `keyparams` parameter is not used (ignored if present). The user may be given a choice of RSA key strengths. Currently, the user is given a choice between "high" strength (2048 bits) and "medium" strength (1024 bits).
For DSA keys, the `keyparams` parameter specifies the DSA PQG parameters which are to be used in the keygen process. The value of the `pqg` parameter is the BASE64 encoded, DER encoded Dss-Parms as specified in IETF [RFC 3279](https://datatracker.ietf.org/doc/html/rfc3279). The user may be given a choice of DSA key sizes, allowing the user to choose one of the sizes defined in the DSA standard.
For EC keys, the `keyparams` parameter specifies the name of the elliptic curve on which the key will be generated. It is normally a string from the list in [RFC 5480, section 2.1.1.1](https://datatracker.ietf.org/doc/html/rfc5480#section-2.1.1.1). (Note that only a subset of the curves named there may actually be supported in any particular browser.) If the `keyparams` parameter string is not a recognized curve name string, then a curve is chosen according to the user's chosen key strength (low, medium, high), using the curve named "`secp384r1`" for high, and the curve named "`secp256r1`" for medium keys. (Note: choice of the number of key strengths, default values for each strength, and the UI by which the user is offered a choice, are outside the scope of this specification.)
The `<keygen>` element is only valid within an HTML form. It will cause some sort of selection to be presented to the user for selecting key size. The UI for the selection may be a menu, radio buttons, or possibly something else. The browser presents several possible key strengths. Currently, two strengths are offered, high and medium. If the user's browser is configured to support cryptographic hardware (e.g. "smart cards") the user may also be given a choice of where to generate the key, i.e., in a smart card or in software and stored on disk.
When the submit button is pressed, a key pair of the selected size is generated. The private key is encrypted and stored in the local key database.
```
PublicKeyAndChallenge ::= SEQUENCE {
spki SubjectPublicKeyInfo,
challenge IA5STRING
}
SignedPublicKeyAndChallenge ::= SEQUENCE {
publicKeyAndChallenge PublicKeyAndChallenge,
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING
}
```
The public key and challenge string are DER encoded as `PublicKeyAndChallenge`, and then digitally signed with the private key to produce a `SignedPublicKeyAndChallenge`. The `SignedPublicKeyAndChallenge` is [Base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64) encoded, and the ASCII data is finally submitted to the server as the value of a form name/value pair, where the name is *name* as specified by the `name` attribute of the `keygen` element. If no challenge string is provided, then it will be encoded as an `IA5STRING` of length zero.
Here is an example form submission as it would be delivered to a CGI program by the HTTP server:
```
commonname=John+Doe&[email protected]&org=Foobar+Computing+Corp.&
orgunit=Bureau+of+Bureaucracy&locality=Anytown&state=California&country=US&
key=MIHFMHEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAnX0TILJrOMUue%2BPtwBRE6XfV%0AWtKQbsshxk5ZhcUwcwyvcnIq9b82QhJdoACdD34rqfCAIND46fXKQUnb0mvKzQID%0AAQABFhFNb3ppbGxhSXNNeUZyaWVuZDANBgkqhkiG9w0BAQQFAANBAAKv2Eex2n%2FS%0Ar%2F7iJNroWlSzSMtTiQTEB%2BADWHGj9u1xrUrOilq%2Fo2cuQxIfZcNZkYAkWP4DubqW%0Ai0%2F%2FrgBvmco%3D
```
Specifications
--------------
Not part of any current specifications.
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `keygen` | Yes-57 | ≤18-79 | 1-69 | No | 3 | 1.2 | Yes-57 | Yes-57 | 4 | No | No | Yes-7.0 |
html <canvas>: The Graphics Canvas element <canvas>: The Graphics Canvas element
=====================================
Use the `<canvas>` with either the [canvas scripting API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) or the [WebGL API](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) to draw graphics and animations.
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [embedded content](../content_categories#embedded_content), palpable content. |
| Permitted content | Transparent but with no [interactive content](../content_categories#interactive_content) descendants except for [`<a>`](a) elements, [`<button>`](button) elements, [`<input>`](input) elements whose [`type`](input#attr-type) attribute is `checkbox`, `radio`, or `button`. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLCanvasElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) |
Attributes
----------
This element's attributes include the [global attributes](../global_attributes).
[**`height`**](#attr-height) The height of the coordinate space in CSS pixels. Defaults to 150.
[**`moz-opaque`**](#attr-moz-opaque) Non-standard Deprecated
Lets the canvas know whether translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported by Mozilla-based browsers; use the standardized [`canvas.getContext('2d', { alpha: false })`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext) instead.
[**`width`**](#attr-width) The width of the coordinate space in CSS pixels. Defaults to 300.
Usage notes
-----------
### Alternative content
You should provide alternate content inside the `<canvas>` block. That content will be rendered both on older browsers that don't support canvas and in browsers with JavaScript disabled.
### Required </canvas> tag
Unlike the [`<img>`](img) element, the [`<canvas>`](canvas) element **requires** the closing tag (`</canvas>`).
### Sizing the canvas using CSS versus HTML
The displayed size of the canvas can be changed using CSS, but if you do this the image is scaled during rendering to fit the styled size, which can make the final graphics rendering end up being distorted.
It is better to specify your canvas dimensions by setting the `width` and `height` attributes directly on the `<canvas>` elements, either directly in the HTML or by using JavaScript.
### Maximum canvas size
The maximum size of a `<canvas>` element is very large, but the exact size depends on the browser. The following is some data we've collected from various tests and other sources (e.g. [Stack Overflow](https://stackoverflow.com/questions/6081483/maximum-size-of-a-canvas-element)):
| Browser | Maximum height | Maximum width | Maximum area |
| --- | --- | --- | --- |
| Chrome | 32,767 pixels | 32,767 pixels | 268,435,456 pixels (i.e., 16,384 x 16,384) |
| Firefox | 32,767 pixels | 32,767 pixels | 472,907,776 pixels (i.e., 22,528 x 20,992) |
| Safari | 32,767 pixels | 32,767 pixels | 268,435,456 pixels (i.e., 16,384 x 16,384) |
| IE | 8,192 pixels | 8,192 pixels | ? |
**Note:** Exceeding the maximum dimensions or area renders the canvas unusable — drawing commands will not work.
Examples
--------
### HTML
This code snippet adds a canvas element to your HTML document. A fallback text is provided if a browser is unable to read or render the canvas.
```
<canvas width="300" height="300">
An alternative text describing what your canvas displays.
</canvas>
```
### JavaScript
Then in the JavaScript code, call [`HTMLCanvasElement.getContext()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext) to get a drawing context and start drawing onto the canvas:
```
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);
```
### Result
Accessibility concerns
----------------------
### Alternative content
The `<canvas>` element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools as semantic HTML is. In general, you should avoid using canvas in an accessible website or app. The following guides can help to make it more accessible.
* [Canvas accessibility use cases](https://www.w3.org/WAI/PF/HTML/wiki/Canvas_Accessibility_Use_Cases)
* [Canvas element accessibility issues](https://www.w3.org/html/wg/wiki/AddedElementCanvas)
* [HTML Canvas Accessibility in Firefox 13 – by Steve Faulkner](https://www.tpgi.com/html5-canvas-accessibility-in-firefox-13/)
* [Best practices for interactive canvas elements](https://html.spec.whatwg.org/multipage/scripting.html#best-practices)
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-canvas-element](https://html.spec.whatwg.org/multipage/canvas.html#the-canvas-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `canvas` | 1 | 12 | 1.5
["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 9 | 9 | 2
Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 37 | 18 | 4
["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 10.1 | 1 | 1.0 |
| `height` | 1 | 12 | 1.5
["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 9 | 9 | 2
Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 37 | 18 | 4
["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 10.1 | 1 | 1.0 |
| `moz-opaque` | No | No | 3.5 | No | No | No | No | No | 4 | No | No | No |
| `width` | 1 | 12 | 1.5
["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 9 | 9 | 2
Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 37 | 18 | 4
["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 10.1 | 1 | 1.0 |
See also
--------
* [MDN canvas portal](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
* [Canvas tutorial](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial)
* [Canvas-related demos](https://developer.mozilla.org/en-US/docs/Web/Demos#canvas)
* [Canvas cheat sheet (2009)](https://simon.html5.org/dump/html5-canvas-cheat-sheet.html)
* [Canvas cheat sheet (pdf) (2015)](https://websitesetup.org/wp-content/uploads/2015/11/Infopgraphic-CanvasCheatSheet-Final2.pdf)
* [Canvas cheat sheet (pdf)](https://www.coding-dude.com/wp/wp-content/uploads/2020/09/HTML5-canvas-cheat-sheet.pdf)
* [Canvas introduction by Apple (2013)](https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HTML-canvas-guide/Introduction/Introduction.html)
| programming_docs |
html <span>: The Content Span element <span>: The Content Span element
================================
The `<span>` [HTML](../index) element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the [`class`](../global_attributes#class) or [`id`](../global_attributes#id) attributes), or because they share attribute values, such as [`lang`](../global_attributes#lang). It should be used only when no other semantic element is appropriate. `<span>` is very much like a [`<div>`](div) element, but [`<div>`](div) is a [block-level element](../block-level_elements) whereas a `<span>` is an [inline element](../inline_elements).
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Example
-------
### Example 1
#### HTML
```
<p><span>Some text</span></p>
```
#### Result
### Example 2
#### HTML
```
<li>
<span>
<a href="portfolio.html" target="\_blank">See my portfolio</a>
</span>
</li>
```
#### CSS
```
li span {
background: gold;
}
```
#### Result
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content). |
| Permitted content | [Phrasing content](../content_categories#phrasing_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content), or any element that accepts [flow content](../content_categories#flow_content). |
| Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLSpanElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-span-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-span-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `span` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
See also
--------
* HTML [`<div>`](div) element
html <aside>: The Aside element <aside>: The Aside element
==========================
The `<aside>` [HTML](../index) element represents a portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes.
Try it
------
Attributes
----------
This element only includes the [global attributes](../global_attributes).
Usage notes
-----------
* Do not use the `<aside>` element to tag parenthesized text, as this kind of text is considered part of the main flow.
Examples
--------
### Using <aside>
This example uses `<aside>` to mark up a paragraph in an article. The paragraph is only indirectly related to the main article content:
```
<article>
<p>
The Disney movie <cite>The Little Mermaid</cite> was first released to
theatres in 1989.
</p>
<aside>
<p>The movie earned $87 million during its initial release.</p>
</aside>
<p>More info about the movie…</p>
</article>
```
Technical Summary
-----------------
| | |
| --- | --- |
| [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [sectioning content](../content_categories#sectioning_content), [palpable content](../content_categories#palpable_content). |
| Permitted content | [Flow content](../content_categories#flow_content). |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). Note that an `<aside>` element must not be a descendant of an [`<address>`](address) element. |
| Implicit ARIA role | `[complementary](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role)` |
| Permitted ARIA roles | `[feed](https://w3c.github.io/aria/#feed)`, `[none](https://w3c.github.io/aria/#none)`, `[note](https://w3c.github.io/aria/#note)`, `[presentation](https://w3c.github.io/aria/#presentation)`, `[region](https://w3c.github.io/aria/#region)`, `[search](https://w3c.github.io/aria/#search)` |
| DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-aside-element](https://html.spec.whatwg.org/multipage/sections.html#the-aside-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `aside` | 5 | 12 | 4 | 9 | 11.1 | 5 | Yes | Yes | 4 | 11.1 | 4.2 | Yes |
See also
--------
* Other section-related elements: [`<body>`](body), [`<article>`](article), [`<section>`](section), [`<nav>`](nav), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<hgroup>`](hgroup), [`<header>`](header), [`<footer>`](footer), [`<address>`](address);
* [Using HTML sections and outlines](heading_elements)
* [ARIA: Complementary role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role)
html <dir>: The Directory element <dir>: The Directory element
============================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The `<dir>` [HTML](../index) element is used as a container for a directory of files and/or folders, potentially with styles and icons applied by the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent). Do not use this obsolete element; instead, you should use the [`<ul>`](ul) element for lists, including lists of files.
**Warning:** Do not use this element. Though present in early HTML specifications, it has been deprecated in HTML 4, and has since been removed entirely. **No major browsers support this element.**
DOM interface
-------------
This element implements the `HTMLDirectoryElement` interface.
Attributes
----------
Like all other HTML elements, this element supports the [global attributes](../global_attributes).
[**`compact`**](#attr-compact) Deprecated
This Boolean attribute hints that the list should be rendered in a compact style. The interpretation of this attribute depends on the user agent and it doesn't work in all browsers.
Specifications
--------------
Not part of any current specifications.
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `dir` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
| `compact` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |
See also
--------
* Other list-related HTML Elements: [`<ol>`](ol), [`<ul>`](ul), [`<li>`](li), and [`<menu>`](menu);
* CSS properties that may be specially useful to style the `<dir>` element:
+ The [`list-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style) property, useful to choose the way the ordinal is displayed.
+ [CSS counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters), useful to handle complex nested lists.
+ The [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) property, useful to simulate the deprecated [`compact`](dir#attr-compact) attribute.
+ The [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) property, useful to control the indent of the list.
html <tbody>: The Table Body element <tbody>: The Table Body element
===============================
The `<tbody>` [HTML](../index) element encapsulates a set of table rows ([`<tr>`](tr) elements), indicating that they comprise the body of the table ([`<table>`](table)).
Try it
------
The `<tbody>` element, along with its related [`<thead>`](thead) and [`<tfoot>`](tfoot) elements, provide useful semantic information that can be used when rendering for either screen or printer.
| | |
| --- | --- |
| [Content categories](../content_categories) | None. |
| Permitted content | Zero or more [`<tr>`](tr) elements. |
| Tag omission | A `<tbody>` element's start tag can be omitted if the first thing inside the `<tbody>` element is a [`<tr>`](tr) element, and if the element is not immediately preceded by a `<tbody>`, [`<thead>`](thead), or [`<tfoot>`](tfoot) element whose end tag has been omitted. (It can't be omitted if the element is empty.) A `<tbody>` element's end tag can be omitted if the `<tbody>` element is immediately followed by a `<tbody>` or [`<tfoot>`](tfoot) element, or if there is no more content in the parent element. |
| Permitted parents | Within the required parent [`<table>`](table) element, the `<tbody>` element can be added after a [`<caption>`](caption), [`<colgroup>`](colgroup), and a [`<thead>`](thead) element. |
| Implicit ARIA role | `[rowgroup](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/rowgroup_role)` |
| Permitted ARIA roles | Any |
| DOM interface | [`HTMLTableSectionElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableSectionElement) |
Attributes
----------
This element includes the [global attributes](../global_attributes).
### Deprecated attributes
[**`align`**](#attr-align) Deprecated
This [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute specifies how horizontal alignment of each cell content will be handled. Possible values are:
* `left`, aligning the content to the left of the cell
* `center`, centering the content in the cell
* `right`, aligning the content to the right of the cell
* `justify`, inserting spaces into the textual content so that the content is justified in the cell
* `char`, aligning the textual content on a special character with a minimal offset, defined by the [`char`](tbody#attr-char) and [`charoff`](tbody#attr-charoff) attributes.
If this attribute is not set, the `left` value is assumed.
As this attribute is deprecated, use the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property instead.
**Note:** The equivalent `text-align` property for the `align="char"` is not implemented in any browsers yet. See the [`text-align`'s browser compatibility section](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align#browser_compatibility) for the `<string>` value.
[**`bgcolor`**](#attr-bgcolor) Deprecated
The background color of the table. It is a [6-digit hexadecimal RGB code](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors), prefixed by a '`#`'. One of the predefined [color keywords](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) can also be used.
As this attribute is deprecated, use the CSS [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) property instead.
[**`char`**](#attr-char) Deprecated
This attribute is used to set the character to align the cells in a column on. Typical values for this include a period (`.`) when attempting to align numbers or monetary values. If [`align`](tbody#attr-align) is not set to `char`, this attribute is ignored.
[**`charoff`**](#attr-charoff) Deprecated
This attribute is used to indicate the number of characters to offset the column data from the alignment characters specified by the `char` attribute.
[**`valign`**](#attr-valign) Deprecated
This attribute specifies the vertical alignment of the text within each row of cells of the table header. Possible values for this attribute are:
* `baseline`, which will put the text as close to the bottom of the cell as it is possible, but align it on the [baseline](https://en.wikipedia.org/wiki/Baseline_%28typography%29) of the characters instead of the bottom of them. If characters are all of the size, this has the same effect as `bottom`.
* `bottom`, which will put the text as close to the bottom of the cell as it is possible;
* `middle`, which will center the text in the cell;
* and `top`, which will put the text as close to the top of the cell as it is possible.
As this attribute is deprecated, use the CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property instead.
Usage notes
-----------
* If the table includes a [`<thead>`](thead) block (to semantically identify a row of column headers), the `<tbody>` block *must* come after it.
* If [`<tr>`](tr) elements are specified outside an existing `<tbody>` element, as direct children of the [`<table>`](table), these elements will be encapsulated by a separate `<tbody>` element generated by the browser.
* When printing a document, the `<thead>` and [`<tfoot>`](tfoot) elements specify information that may be the same—or at least very similar—on every page of a multipage table, while the `<tbody>` element's contents generally will differ from page to page.
* When a table is presented in a screen context (such as a window) which is not large enough to display the entire table, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may let the user scroll the contents of the `<thead>`, `<tbody>`, `<tfoot>`, and [`<caption>`](caption) blocks separately from one another for the same parent table.
* You *may* use more than one `<tbody>` per table as long as they are all consecutive. This lets you divide the rows in large tables into sections, each of which may be separately formatted if so desired. If not marked up to be consecutive elements, browsers will correct this author error, ensuring any `<thead>` and `<tfoot>` elements are rendered as the first and last elements of the table, respectively.
Examples
--------
Below are some examples showing the use of the `<tbody>` element. For more examples of this element, see the examples for [`<table>`](table#examples).
### Basic example
In this relatively simple example, we create a table containing information about a group of students with a [`<thead>`](thead) and a [`<tbody>`](tbody), with a number of rows in the body.
#### HTML
The table's HTML is shown here. Note that all the body cells including information about students are contained within a single `<tbody>` element.
```
<table>
<thead>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<tr>
<td>3741255</td>
<td>Jones, Martha</td>
<td>Computer Science</td>
</tr>
<tr>
<td>3971244</td>
<td>Nim, Victor</td>
<td>Russian Literature</td>
</tr>
<tr>
<td>4100332</td>
<td>Petrov, Alexandra</td>
<td>Astrophysics</td>
</tr>
</tbody>
</table>
```
#### CSS
The CSS to style our table is shown next.
```
table {
border: 2px solid #555;
border-collapse: collapse;
font: 16px "Lucida Grande", "Helvetica", "Arial", sans-serif;
}
```
First, the table's overall style attributes are set, configuring the thickness, style, and color of the table's exterior borders and using [`border-collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) to ensure that the border lines are shared among adjacent cells rather than each having its own borders with space in between. [`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) is used to establish an initial font for the table.
```
th,
td {
border: 1px solid #bbb;
padding: 2px 8px 0;
text-align: left;
}
```
Then the style is set for the majority of the cells in the table, including all data cells but also those styles shared between our [`<td>`](td) and [`<th>`](th) cells. The cells are given a light gray outline which is a single pixel thick, padding is adjusted, and all cells are left-aligned using [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align)
```
thead > tr > th {
background-color: #cce;
font-size: 18px;
border-bottom: 2px solid #999;
}
```
Finally, header cells contained within the [`<thead>`](thead) element are given additional styling. They use a darker [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color), a larger font size, and a thicker, darker bottom border than the other cell borders.
#### Result
The resulting table looks like this:
### Multiple bodies
You can create row groupings within a table by using multiple `<tbody>` elements. Each may potentially have its own header row or rows; however, *there can be only one [`<thead>`](thead) per table!* Because of that, you need to use a [`<tr>`](tr) filled with [`<th>`](th) elements to create headers within each `<tbody>`. Let's see how that's done.
Let's take the previous example, add some more students to the list, and update the table so that instead of listing each student's major on every row, the students are grouped by major, with heading rows for each major.
#### Result
First, the resulting table, so you know what we're building:
#### HTML
The revised HTML looks like this:
```
<table>
<thead>
<tr>
<th>Student ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="2">Computer Science</th>
</tr>
<tr>
<td>3741255</td>
<td>Jones, Martha</td>
</tr>
<tr>
<td>4077830</td>
<td>Pierce, Benjamin</td>
</tr>
<tr>
<td>5151701</td>
<td>Kirk, James</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="2">Russian Literature</th>
</tr>
<tr>
<td>3971244</td>
<td>Nim, Victor</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="2">Astrophysics</th>
</tr>
<tr>
<td>4100332</td>
<td>Petrov, Alexandra</td>
</tr>
<tr>
<td>8892377</td>
<td>Toyota, Hiroko</td>
</tr>
</tbody>
</table>
```
Notice that each major is placed in a separate `<tbody>` block, the first row of which contains a single [`<th>`](th) element with a [`colspan`](th#attr-colspan) attribute that spans the entire width of the table. That heading lists the name of the major contained within the `<tbody>`.
Then each remaining row in each major's `<tbody>` consists of two cells: the first for the student's ID and the second for their name.
#### CSS
Most of the CSS is unchanged. We do, however, add a slightly more subtle style for header cells contained directly within a `<tbody>` (as opposed to those which reside in a [`<thead>`](thead)). This is used for the headers indicating each table section's corresponding major.
```
tbody > tr > th {
background-color: #dde;
border-bottom: 1.5px solid #bbb;
font-weight: normal;
}
```
Specifications
--------------
| Specification |
| --- |
| [HTML Standard # the-tbody-element](https://html.spec.whatwg.org/multipage/tables.html#the-tbody-element) |
Browser compatibility
---------------------
| | Desktop | Mobile |
| --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `tbody` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| `align` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
| `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 |
| `char` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `charoff` | No | 12 | No
See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No
See [bug 2212](https://bugzil.la/2212). | No | No | No |
| `valign` | No | 12 | No
See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No
See [bug 915](https://bugzil.la/915). | No | No | No |
See also
--------
* CSS properties and [pseudo-classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes) that may be specially useful to style the `<tbody>` element:
+ the [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child) pseudo-class to set the alignment on the cells of the column;
+ the [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to align all cells content on the same character, like '.'.
| programming_docs |
Subsets and Splits