We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
templateing: jinja2: pass kwargs for environment
I think it would be good to pass something like `env_kwargs` via https://github.com/blueyed/starlette/blob/24c135de71ac56a73f7f797258115941579155bf/starlette/templating.py#L51-L53.

While you can change the env afterwards, it would allow Jinja2 to validate e.g. `enable_async`, and call `load_extensions` etc.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `starlette/templating.py`
Content:
```
1 import typing
2 from os import PathLike
3 
4 from starlette.background import BackgroundTask
5 from starlette.responses import Response
6 from starlette.types import Receive, Scope, Send
7 
8 try:
9     import jinja2
10 
11     # @contextfunction renamed to @pass_context in Jinja 3.0, to be removed in 3.1
12     if hasattr(jinja2, "pass_context"):
13         pass_context = jinja2.pass_context
14     else:  # pragma: nocover
15         pass_context = jinja2.contextfunction
16 except ImportError:  # pragma: nocover
17     jinja2 = None  # type: ignore
18 
19 
20 class _TemplateResponse(Response):
21     media_type = "text/html"
22 
23     def __init__(
24         self,
25         template: typing.Any,
26         context: dict,
27         status_code: int = 200,
28         headers: dict = None,
29         media_type: str = None,
30         background: BackgroundTask = None,
31     ):
32         self.template = template
33         self.context = context
34         content = template.render(context)
35         super().__init__(content, status_code, headers, media_type, background)
36 
37     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
38         request = self.context.get("request", {})
39         extensions = request.get("extensions", {})
40         if "http.response.template" in extensions:
41             await send(
42                 {
43                     "type": "http.response.template",
44                     "template": self.template,
45                     "context": self.context,
46                 }
47             )
48         await super().__call__(scope, receive, send)
49 
50 
51 class Jinja2Templates:
52     """
53     templates = Jinja2Templates("templates")
54 
55     return templates.TemplateResponse("index.html", {"request": request})
56     """
57 
58     def __init__(self, directory: typing.Union[str, PathLike]) -> None:
59         assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates"
60         self.env = self._create_env(directory)
61 
62     def _create_env(
63         self, directory: typing.Union[str, PathLike]
64     ) -> "jinja2.Environment":
65         @pass_context
66         def url_for(context: dict, name: str, **path_params: typing.Any) -> str:
67             request = context["request"]
68             return request.url_for(name, **path_params)
69 
70         loader = jinja2.FileSystemLoader(directory)
71         env = jinja2.Environment(loader=loader, autoescape=True)
72         env.globals["url_for"] = url_for
73         return env
74 
75     def get_template(self, name: str) -> "jinja2.Template":
76         return self.env.get_template(name)
77 
78     def TemplateResponse(
79         self,
80         name: str,
81         context: dict,
82         status_code: int = 200,
83         headers: dict = None,
84         media_type: str = None,
85         background: BackgroundTask = None,
86     ) -> _TemplateResponse:
87         if "request" not in context:
88             raise ValueError('context must include a "request" key')
89         template = self.get_template(name)
90         return _TemplateResponse(
91             template,
92             context,
93             status_code=status_code,
94             headers=headers,
95             media_type=media_type,
96             background=background,
97         )
98
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/starlette/templating.py b/starlette/templating.py
--- a/starlette/templating.py
+++ b/starlette/templating.py
@@ -55,12 +55,14 @@
     return templates.TemplateResponse("index.html", {"request": request})
     """
 
-    def __init__(self, directory: typing.Union[str, PathLike]) -> None:
+    def __init__(
+        self, directory: typing.Union[str, PathLike], **env_options: typing.Any
+    ) -> None:
         assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates"
-        self.env = self._create_env(directory)
+        self.env = self._create_env(directory, **env_options)
 
     def _create_env(
-        self, directory: typing.Union[str, PathLike]
+        self, directory: typing.Union[str, PathLike], **env_options: typing.Any
     ) -> "jinja2.Environment":
         @pass_context
         def url_for(context: dict, name: str, **path_params: typing.Any) -> str:
@@ -68,7 +70,10 @@
             return request.url_for(name, **path_params)
 
         loader = jinja2.FileSystemLoader(directory)
-        env = jinja2.Environment(loader=loader, autoescape=True)
+        env_options.setdefault("loader", loader)
+        env_options.setdefault("autoescape", True)
+
+        env = jinja2.Environment(**env_options)
         env.globals["url_for"] = url_for
         return env

{"golden_diff": "diff --git a/starlette/templating.py b/starlette/templating.py\n--- a/starlette/templating.py\n+++ b/starlette/templating.py\n@@ -55,12 +55,14 @@\n     return templates.TemplateResponse(\"index.html\", {\"request\": request})\n     \"\"\"\n \n-    def __init__(self, directory: typing.Union[str, PathLike]) -> None:\n+    def __init__(\n+        self, directory: typing.Union[str, PathLike], **env_options: typing.Any\n+    ) -> None:\n         assert jinja2 is not None, \"jinja2 must be installed to use Jinja2Templates\"\n-        self.env = self._create_env(directory)\n+        self.env = self._create_env(directory, **env_options)\n \n     def _create_env(\n-        self, directory: typing.Union[str, PathLike]\n+        self, directory: typing.Union[str, PathLike], **env_options: typing.Any\n     ) -> \"jinja2.Environment\":\n         @pass_context\n         def url_for(context: dict, name: str, **path_params: typing.Any) -> str:\n@@ -68,7 +70,10 @@\n             return request.url_for(name, **path_params)\n \n         loader = jinja2.FileSystemLoader(directory)\n-        env = jinja2.Environment(loader=loader, autoescape=True)\n+        env_options.setdefault(\"loader\", loader)\n+        env_options.setdefault(\"autoescape\", True)\n+\n+        env = jinja2.Environment(**env_options)\n         env.globals[\"url_for\"] = url_for\n         return env\n", "issue": "templateing: jinja2: pass kwargs for environment\nI think it would be good to pass something like `env_kwargs` via https://github.com/blueyed/starlette/blob/24c135de71ac56a73f7f797258115941579155bf/starlette/templating.py#L51-L53.\r\n\r\nWhile you can change the env afterwards, it would allow Jinja2 to validate e.g. `enable_async`, and call `load_extensions` etc.\n", "before_files": [{"content": "import typing\nfrom os import PathLike\n\nfrom starlette.background import BackgroundTask\nfrom starlette.responses import Response\nfrom starlette.types import Receive, Scope, Send\n\ntry:\n    import jinja2\n\n    # @contextfunction renamed to @pass_context in Jinja 3.0, to be removed in 3.1\n    if hasattr(jinja2, \"pass_context\"):\n        pass_context = jinja2.pass_context\n    else:  # pragma: nocover\n        pass_context = jinja2.contextfunction\nexcept ImportError:  # pragma: nocover\n    jinja2 = None  # type: ignore\n\n\nclass _TemplateResponse(Response):\n    media_type = \"text/html\"\n\n    def __init__(\n        self,\n        template: typing.Any,\n        context: dict,\n        status_code: int = 200,\n        headers: dict = None,\n        media_type: str = None,\n        background: BackgroundTask = None,\n    ):\n        self.template = template\n        self.context = context\n        content = template.render(context)\n        super().__init__(content, status_code, headers, media_type, background)\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        request = self.context.get(\"request\", {})\n        extensions = request.get(\"extensions\", {})\n        if \"http.response.template\" in extensions:\n            await send(\n                {\n                    \"type\": \"http.response.template\",\n                    \"template\": self.template,\n                    \"context\": self.context,\n                }\n            )\n        await super().__call__(scope, receive, send)\n\n\nclass Jinja2Templates:\n    \"\"\"\n    templates = Jinja2Templates(\"templates\")\n\n    return templates.TemplateResponse(\"index.html\", {\"request\": request})\n    \"\"\"\n\n    def __init__(self, directory: typing.Union[str, PathLike]) -> None:\n        assert jinja2 is not None, \"jinja2 must be installed to use Jinja2Templates\"\n        self.env = self._create_env(directory)\n\n    def _create_env(\n        self, directory: typing.Union[str, PathLike]\n    ) -> \"jinja2.Environment\":\n        @pass_context\n        def url_for(context: dict, name: str, **path_params: typing.Any) -> str:\n            request = context[\"request\"]\n            return request.url_for(name, **path_params)\n\n        loader = jinja2.FileSystemLoader(directory)\n        env = jinja2.Environment(loader=loader, autoescape=True)\n        env.globals[\"url_for\"] = url_for\n        return env\n\n    def get_template(self, name: str) -> \"jinja2.Template\":\n        return self.env.get_template(name)\n\n    def TemplateResponse(\n        self,\n        name: str,\n        context: dict,\n        status_code: int = 200,\n        headers: dict = None,\n        media_type: str = None,\n        background: BackgroundTask = None,\n    ) -> _TemplateResponse:\n        if \"request\" not in context:\n            raise ValueError('context must include a \"request\" key')\n        template = self.get_template(name)\n        return _TemplateResponse(\n            template,\n            context,\n            status_code=status_code,\n            headers=headers,\n            media_type=media_type,\n            background=background,\n        )\n", "path": "starlette/templating.py"}], "after_files": [{"content": "import typing\nfrom os import PathLike\n\nfrom starlette.background import BackgroundTask\nfrom starlette.responses import Response\nfrom starlette.types import Receive, Scope, Send\n\ntry:\n    import jinja2\n\n    # @contextfunction renamed to @pass_context in Jinja 3.0, to be removed in 3.1\n    if hasattr(jinja2, \"pass_context\"):\n        pass_context = jinja2.pass_context\n    else:  # pragma: nocover\n        pass_context = jinja2.contextfunction\nexcept ImportError:  # pragma: nocover\n    jinja2 = None  # type: ignore\n\n\nclass _TemplateResponse(Response):\n    media_type = \"text/html\"\n\n    def __init__(\n        self,\n        template: typing.Any,\n        context: dict,\n        status_code: int = 200,\n        headers: dict = None,\n        media_type: str = None,\n        background: BackgroundTask = None,\n    ):\n        self.template = template\n        self.context = context\n        content = template.render(context)\n        super().__init__(content, status_code, headers, media_type, background)\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        request = self.context.get(\"request\", {})\n        extensions = request.get(\"extensions\", {})\n        if \"http.response.template\" in extensions:\n            await send(\n                {\n                    \"type\": \"http.response.template\",\n                    \"template\": self.template,\n                    \"context\": self.context,\n                }\n            )\n        await super().__call__(scope, receive, send)\n\n\nclass Jinja2Templates:\n    \"\"\"\n    templates = Jinja2Templates(\"templates\")\n\n    return templates.TemplateResponse(\"index.html\", {\"request\": request})\n    \"\"\"\n\n    def __init__(\n        self, directory: typing.Union[str, PathLike], **env_options: typing.Any\n    ) -> None:\n        assert jinja2 is not None, \"jinja2 must be installed to use Jinja2Templates\"\n        self.env = self._create_env(directory, **env_options)\n\n    def _create_env(\n        self, directory: typing.Union[str, PathLike], **env_options: typing.Any\n    ) -> \"jinja2.Environment\":\n        @pass_context\n        def url_for(context: dict, name: str, **path_params: typing.Any) -> str:\n            request = context[\"request\"]\n            return request.url_for(name, **path_params)\n\n        loader = jinja2.FileSystemLoader(directory)\n        env_options.setdefault(\"loader\", loader)\n        env_options.setdefault(\"autoescape\", True)\n\n        env = jinja2.Environment(**env_options)\n        env.globals[\"url_for\"] = url_for\n        return env\n\n    def get_template(self, name: str) -> \"jinja2.Template\":\n        return self.env.get_template(name)\n\n    def TemplateResponse(\n        self,\n        name: str,\n        context: dict,\n        status_code: int = 200,\n        headers: dict = None,\n        media_type: str = None,\n        background: BackgroundTask = None,\n    ) -> _TemplateResponse:\n        if \"request\" not in context:\n            raise ValueError('context must include a \"request\" key')\n        template = self.get_template(name)\n        return _TemplateResponse(\n            template,\n            context,\n            status_code=status_code,\n            headers=headers,\n            media_type=media_type,\n            background=background,\n        )\n", "path": "starlette/templating.py"}]}