Twig error runtime error

I have inherited a rather complicated Symfony 3 project (I'm using Laravel mostly nowadays - it's been years since I used Symfony) so this is a bit out of my wheelhouse. I did a composer update an...

I have inherited a rather complicated Symfony 3 project (I’m using Laravel mostly nowadays — it’s been years since I used Symfony) so this is a bit out of my wheelhouse.

I did a composer update and it built ok.

composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Updating twig/twig 1.x-dev (e8555dc => 1445246):  Checking out 1445246d8e
Writing lock file
Generating autoload files
> IncenteevParameterHandlerScriptHandler::buildParameters
Updating the "app/config/parameters.yml" file
> SensioBundleDistributionBundleComposerScriptHandler::buildBootstrap
> SensioBundleDistributionBundleComposerScriptHandler::clearCache

 // Clearing the cache for the dev environment with debug
 // true


 [OK] Cache for the "dev" environment (debug=true) was successfully cleared.


> SensioBundleDistributionBundleComposerScriptHandler::installAssets

 Trying to install assets as relative symbolic links.

 -- -------- ----------------
     Bundle   Method / Error
 -- -------- ----------------


 [OK] All assets were successfully installed.


> SensioBundleDistributionBundleComposerScriptHandler::installRequirementsFile
> SensioBundleDistributionBundleComposerScriptHandler::prepareDeploymentTarget

I cleared the cache

php bin/console cache:clear --no-warmup --env local

When I browse to my local development URL, I get:

Whoops, looks like something went wrong.

(4/4) Twig_Error_Runtime
An exception has been thrown during the rendering of a template ("Notice: Undefined offset: 0").

in exception_full.html.twig (line 1)
at Twig_Template->displayWithErrorHandling(array('status_code' => 500, 'status_text' => 'Internal Server Error', 'exception' => object(FlattenException), 'logger' => object(Logger), 'currentContent' => '', 'app' => object(AppVariable)), array('head' => array(object(__TwigTemplate_ed2c7b0206a4a8ba0c01ceb7e7a7f0ba342d3cbf55c912fe1f34e6abd35411c0), 'block_head'), 'title' => array(object(__TwigTemplate_ed2c7b0206a4a8ba0c01ceb7e7a7f0ba342d3cbf55c912fe1f34e6abd35411c0), 'block_title'), 'body' => array(object(__TwigTemplate_ed2c7b0206a4a8ba0c01ceb7e7a7f0ba342d3cbf55c912fe1f34e6abd35411c0), 'block_body')))
in Template.php (line 403)

<snip/>

(3/4) ContextErrorException
Notice: Undefined offset: 0

in Profiler.php (line 23)
at Twig_Extension_Profiler->enter(object(Twig_Profiler_Profile))
in ProfilerExtension.php (line 40)

<snip/>

(2/4) Twig_Error_Runtime
An exception has been thrown during the rendering of a template ("Notice: Undefined offset: 0").

in base.html.twig (line 11)
at Twig_Template->displayBlock('javascripts', array('env' => 'local', 'app' => object(AppVariable)), array('title' => array(object(__TwigTemplate_e199b3b21ccad34239564ea288dce2bfa2f11212622c2c75863848c603e82b70), 'block_title'), 'stylesheets' => array(object(__TwigTemplate_e199b3b21ccad34239564ea288dce2bfa2f11212622c2c75863848c603e82b70), 'block_stylesheets'), 'body' => array(object(__TwigTemplate_888836406c51f4232014f646f747310c541800b61ef418c11fbfcee42a1afe9b), 'block_body'), 'javascripts' => array(object(__TwigTemplate_e199b3b21ccad34239564ea288dce2bfa2f11212622c2c75863848c603e82b70), 'block_javascripts')))
in Environment.php(467) : eval()'d code (line 51)

<snip/>

(1/4) ContextErrorException
Notice: Undefined offset: 0

in Profiler.php (line 23)
at Twig_Extension_Profiler->enter(object(Twig_Profiler_Profile))
in ProfilerExtension.php (line 40)

Since this appears to be an issue with vendor files, I’m not sure where to go from here.

The last error in the logs is

[2018-03-02 15:56:53] request.CRITICAL: Exception thrown when handling an exception (Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("Notice: Undefined offset: 0"). at /Projects/myproject/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Resources/views/Exception/exception_full.html.twig line 1) {"exception":"[object] (Twig_Error_Runtime(code: 0): An exception has been thrown during the rendering of a template ("Notice: Undefined offset: 0"). at /Projects/myproject/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Resources/views/Exception/exception_full.html.twig:1, Symfony\Component\Debug\Exception\ContextErrorException(code: 0): Notice: Undefined offset: 0 at /Projects/myproject/vendor/twig/twig/lib/Twig/Extension/Profiler.php:23)"} []

Содержание

  1. Twig for Developers
  2. Basics
  3. Rendering Templates
  4. Environment Options
  5. Loaders
  6. Compilation Cache
  7. Built-in Loaders
  8. TwigLoaderFilesystemLoader
  9. TwigLoaderArrayLoader
  10. TwigLoaderChainLoader
  11. Create your own Loader
  12. Using Extensions
  13. Built-in Extensions
  14. Core Extension
  15. Escaper Extension
  16. Sandbox Extension
  17. Profiler Extension
  18. Optimizer Extension
  19. Exceptions
  20. Twig for Developers
  21. Basics
  22. Rendering Templates
  23. Environment Options
  24. Loaders
  25. Compilation Cache
  26. Built-in Loaders
  27. TwigLoaderFilesystemLoader
  28. TwigLoaderArrayLoader
  29. TwigLoaderChainLoader
  30. Create your own Loader
  31. Using Extensions
  32. Built-in Extensions
  33. Core Extension
  34. Escaper Extension
  35. Sandbox Extension
  36. Profiler Extension
  37. Optimizer Extension
  38. Exceptions

Twig for Developers

This chapter describes the API to Twig and not the template language. It will be most useful as reference to those implementing the template interface to the application and not those who are creating Twig templates.

Basics

Twig uses a central object called the environment (of class TwigEnvironment ). Instances of this class are used to store the configuration and extensions, and are used to load templates.

Most applications create one TwigEnvironment object on application initialization and use that to load templates. In some cases, it might be useful to have multiple environments side by side, with different configurations.

The typical way to configure Twig to load templates for an application looks roughly like this:

This creates a template environment with a default configuration and a loader that looks up templates in the /path/to/templates/ directory. Different loaders are available and you can also write your own if you want to load templates from a database or other resources.

Notice that the second argument of the environment is an array of options. The cache option is a compilation cache directory, where Twig caches the compiled templates to avoid the parsing phase for sub-sequent requests. It is very different from the cache you might want to add for the evaluated templates. For such a need, you can use any available PHP cache library.

Rendering Templates

To load a template from a Twig environment, call the load() method which returns a TwigTemplateWrapper instance:

To render the template with some variables, call the render() method:

The display() method is a shortcut to output the rendered template.

You can also load and render the template in one fell swoop:

If a template defines blocks, they can be rendered individually via the renderBlock() call:

Environment Options

When creating a new TwigEnvironment instance, you can pass an array of options as the constructor second argument:

The following options are available:

When set to true , the generated templates have a __toString() method that you can use to display the generated nodes (default to false ).

charset string (defaults to utf-8 )

The charset used by the templates.

base_template_class string (defaults to TwigTemplate )

The base template class to use for generated templates.

cache string or false

An absolute path where to store the compiled templates, or false to disable caching (which is the default).

When developing with Twig, it’s useful to recompile the template whenever the source code changes. If you don’t provide a value for the auto_reload option, it will be determined automatically based on the debug value.

If set to false , Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true , Twig throws an exception instead (default to false ).

Sets the default auto-escaping strategy ( name , html , js , css , url , html_attr , or a PHP callback that takes the template «filename» and returns the escaping strategy to use — the callback cannot be a function name to avoid collision with built-in escaping strategies); set it to false to disable auto-escaping. The name escaping strategy determines the escaping strategy to use for a template based on the template filename extension (this strategy does not incur any overhead at runtime as auto-escaping is done at compilation time.)

A flag that indicates which optimizations to apply (default to -1 — all optimizations are enabled; set it to 0 to disable).

Loaders

Loaders are responsible for loading templates from a resource such as the file system.

Compilation Cache

All template loaders can cache the compiled templates on the filesystem for future reuse. It speeds up Twig a lot as templates are only compiled once.

Built-in Loaders

Here is a list of the built-in loaders:

TwigLoaderFilesystemLoader

TwigLoaderFilesystemLoader loads templates from the file system. This loader can find templates in folders on the file system and is the preferred way to load them:

It can also look for templates in an array of directories:

With such a configuration, Twig will first look for templates in $templateDir1 and if they do not exist, it will fallback to look for them in the $templateDir2 .

You can add or prepend paths via the addPath() and prependPath() methods:

The filesystem loader also supports namespaced templates. This allows to group your templates under different namespaces which have their own template paths.

When using the setPaths() , addPath() , and prependPath() methods, specify the namespace as the second argument (when not specified, these methods act on the «main» namespace):

Namespaced templates can be accessed via the special @namespace_name/template_path notation:

TwigLoaderFilesystemLoader supports absolute and relative paths. Using relative paths is preferred as it makes the cache keys independent of the project root directory (for instance, it allows warming the cache from a build server where the directory might be different from the one used on production servers):

When not passing the root path as a second argument, Twig uses getcwd() for relative paths.

TwigLoaderArrayLoader

TwigLoaderArrayLoader loads a template from a PHP array. It is passed an array of strings bound to template names:

This loader is very useful for unit testing. It can also be used for small projects where storing all templates in a single PHP file might make sense.

When using the Array loader with a cache mechanism, you should know that a new cache key is generated each time a template content «changes» (the cache key being the source code of the template). If you don’t want to see your cache grows out of control, you need to take care of clearing the old cache file by yourself.

TwigLoaderChainLoader

TwigLoaderChainLoader delegates the loading of templates to other loaders:

When looking for a template, Twig tries each loader in turn and returns as soon as the template is found. When rendering the index.html template from the above example, Twig will load it with $loader2 but the base.html template will be loaded from $loader1 .

You can also add loaders via the addLoader() method.

Create your own Loader

All loaders implement the TwigLoaderLoaderInterface :

The isFresh() method must return true if the current cached template is still fresh, given the last modification time, or false otherwise.

The getSourceContext() method must return an instance of TwigSource .

Using Extensions

Twig extensions are packages that add new features to Twig. Register an extension via the addExtension() method:

Twig comes bundled with the following extensions:

  • TwigExtensionCoreExtension: Defines all the core features of Twig.
  • TwigExtensionDebugExtension: Defines the dump function to help debug template variables.
  • TwigExtensionEscaperExtension: Adds automatic output-escaping and the possibility to escape/unescape blocks of code.
  • TwigExtensionSandboxExtension: Adds a sandbox mode to the default Twig environment, making it safe to evaluate untrusted code.
  • TwigExtensionProfilerExtension: Enables the built-in Twig profiler.
  • TwigExtensionOptimizerExtension: Optimizes the node tree before compilation.
  • TwigExtensionStringLoaderExtension: Defines the template_from_string function to allow loading templates from string in a template.

The Core, Escaper, and Optimizer extensions are registered by default.

Built-in Extensions

This section describes the features added by the built-in extensions.

Read the chapter about extending Twig to learn how to create your own extensions.

Core Extension

The core extension defines all the core features of Twig:

Escaper Extension

The escaper extension adds automatic output escaping to Twig. It defines a tag, autoescape , and a filter, raw .

When creating the escaper extension, you can switch on or off the global output escaping strategy:

If set to html , all variables in templates are escaped (using the html escaping strategy), except those using the raw filter:

You can also change the escaping mode locally by using the autoescape tag:

The autoescape tag has no effect on included files.

The escaping rules are implemented as follows:

Literals (integers, booleans, arrays, . ) used in the template directly as variables or filter arguments are never automatically escaped:

Expressions which the result is a literal or a variable marked safe are never automatically escaped:

Objects with a __toString method are converted to strings and escaped. You can mark some classes and/or interfaces as being safe for some strategies via EscaperExtension::addSafeClass() :

Escaping is applied before printing, after any other filter is applied:

The `raw` filter should only be used at the end of the filter chain:

Automatic escaping is not applied if the last filter in the chain is marked safe for the current context (e.g. html or js ). escape and escape(‘html’) are marked safe for HTML, escape(‘js’) is marked safe for JavaScript, raw is marked safe for everything.

Note that autoescaping has some limitations as escaping is applied on expressions after evaluation. For instance, when working with concatenation, << foo|raw

bar >> won’t give the expected result as escaping is applied on the result of the concatenation, not on the individual variables (so, the raw filter won’t have any effect here).

Sandbox Extension

The sandbox extension can be used to evaluate untrusted code. Access to unsafe attributes and methods is prohibited. The sandbox security is managed by a policy instance. By default, Twig comes with one policy class: TwigSandboxSecurityPolicy . This class allows you to white-list some tags, filters, properties, and methods:

With the previous configuration, the security policy will only allow usage of the if tag, and the upper filter. Moreover, the templates will only be able to call the getTitle() and getBody() methods on Article objects, and the title and body public properties. Everything else won’t be allowed and will generate a TwigSandboxSecurityError exception.

The policy object is the first argument of the sandbox constructor:

By default, the sandbox mode is disabled and should be enabled when including untrusted template code by using the sandbox tag:

You can sandbox all templates by passing true as the second argument of the extension constructor:

Profiler Extension

The profiler extension enables a profiler for Twig templates; it should only be used on your development machines as it adds some overhead:

A profile contains information about time and memory consumption for template, block, and macro executions.

You can also dump the data in a Blackfire.io compatible format:

Upload the profile to visualize it (create a free account first):

Optimizer Extension

The optimizer extension optimizes the node tree before compilation:

By default, all optimizations are turned on. You can select the ones you want to enable by passing them to the constructor:

Twig supports the following optimizations:

  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_ALL , enables all optimizations (this is the default value).
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_NONE , disables all optimizations. This reduces the compilation time, but it can increase the execution time and the consumed memory.
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_FOR , optimizes the for tag by removing the loop variable creation whenever possible.
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_RAW_FILTER , removes the raw filter whenever possible.
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS , simplifies the creation and access of variables in the compiled templates whenever possible.

Exceptions

Twig can throw exceptions:

  • TwigErrorError : The base exception for all errors.
  • TwigErrorSyntaxError : Thrown to tell the user that there is a problem with the template syntax.
  • TwigErrorRuntimeError : Thrown when an error occurs at runtime (when a filter does not exist for instance).
  • TwigErrorLoaderError : Thrown when an error occurs during template loading.
  • TwigSandboxSecurityError : Thrown when an unallowed tag, filter, or method is called in a sandboxed template.

Источник

Twig for Developers

This chapter describes the API to Twig and not the template language. It will be most useful as reference to those implementing the template interface to the application and not those who are creating Twig templates.

Basics

Twig uses a central object called the environment (of class TwigEnvironment ). Instances of this class are used to store the configuration and extensions, and are used to load templates.

Most applications create one TwigEnvironment object on application initialization and use that to load templates. In some cases, it might be useful to have multiple environments side by side, with different configurations.

The typical way to configure Twig to load templates for an application looks roughly like this:

This creates a template environment with a default configuration and a loader that looks up templates in the /path/to/templates/ directory. Different loaders are available and you can also write your own if you want to load templates from a database or other resources.

Notice that the second argument of the environment is an array of options. The cache option is a compilation cache directory, where Twig caches the compiled templates to avoid the parsing phase for sub-sequent requests. It is very different from the cache you might want to add for the evaluated templates. For such a need, you can use any available PHP cache library.

Rendering Templates

To load a template from a Twig environment, call the load() method which returns a TwigTemplateWrapper instance:

To render the template with some variables, call the render() method:

The display() method is a shortcut to output the rendered template.

You can also load and render the template in one fell swoop:

If a template defines blocks, they can be rendered individually via the renderBlock() call:

Environment Options

When creating a new TwigEnvironment instance, you can pass an array of options as the constructor second argument:

The following options are available:

When set to true , the generated templates have a __toString() method that you can use to display the generated nodes (default to false ).

charset string (defaults to utf-8 )

The charset used by the templates.

cache string or false

An absolute path where to store the compiled templates, or false to disable caching (which is the default).

When developing with Twig, it’s useful to recompile the template whenever the source code changes. If you don’t provide a value for the auto_reload option, it will be determined automatically based on the debug value.

If set to false , Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true , Twig throws an exception instead (default to false ).

Sets the default auto-escaping strategy ( name , html , js , css , url , html_attr , or a PHP callback that takes the template «filename» and returns the escaping strategy to use — the callback cannot be a function name to avoid collision with built-in escaping strategies); set it to false to disable auto-escaping. The name escaping strategy determines the escaping strategy to use for a template based on the template filename extension (this strategy does not incur any overhead at runtime as auto-escaping is done at compilation time.)

A flag that indicates which optimizations to apply (default to -1 — all optimizations are enabled; set it to 0 to disable).

Loaders

Loaders are responsible for loading templates from a resource such as the file system.

Compilation Cache

All template loaders can cache the compiled templates on the filesystem for future reuse. It speeds up Twig a lot as templates are only compiled once.

Built-in Loaders

Here is a list of the built-in loaders:

TwigLoaderFilesystemLoader

TwigLoaderFilesystemLoader loads templates from the file system. This loader can find templates in folders on the file system and is the preferred way to load them:

It can also look for templates in an array of directories:

With such a configuration, Twig will first look for templates in $templateDir1 and if they do not exist, it will fallback to look for them in the $templateDir2 .

You can add or prepend paths via the addPath() and prependPath() methods:

The filesystem loader also supports namespaced templates. This allows to group your templates under different namespaces which have their own template paths.

When using the setPaths() , addPath() , and prependPath() methods, specify the namespace as the second argument (when not specified, these methods act on the «main» namespace):

Namespaced templates can be accessed via the special @namespace_name/template_path notation:

TwigLoaderFilesystemLoader supports absolute and relative paths. Using relative paths is preferred as it makes the cache keys independent of the project root directory (for instance, it allows warming the cache from a build server where the directory might be different from the one used on production servers):

When not passing the root path as a second argument, Twig uses getcwd() for relative paths.

TwigLoaderArrayLoader

TwigLoaderArrayLoader loads a template from a PHP array. It is passed an array of strings bound to template names:

This loader is very useful for unit testing. It can also be used for small projects where storing all templates in a single PHP file might make sense.

When using the Array loader with a cache mechanism, you should know that a new cache key is generated each time a template content «changes» (the cache key being the source code of the template). If you don’t want to see your cache grows out of control, you need to take care of clearing the old cache file by yourself.

TwigLoaderChainLoader

TwigLoaderChainLoader delegates the loading of templates to other loaders:

When looking for a template, Twig tries each loader in turn and returns as soon as the template is found. When rendering the index.html template from the above example, Twig will load it with $loader2 but the base.html template will be loaded from $loader1 .

You can also add loaders via the addLoader() method.

Create your own Loader

All loaders implement the TwigLoaderLoaderInterface :

The isFresh() method must return true if the current cached template is still fresh, given the last modification time, or false otherwise.

The getSourceContext() method must return an instance of TwigSource .

Using Extensions

Twig extensions are packages that add new features to Twig. Register an extension via the addExtension() method:

Twig comes bundled with the following extensions:

  • TwigExtensionCoreExtension: Defines all the core features of Twig.
  • TwigExtensionDebugExtension: Defines the dump function to help debug template variables.
  • TwigExtensionEscaperExtension: Adds automatic output-escaping and the possibility to escape/unescape blocks of code.
  • TwigExtensionSandboxExtension: Adds a sandbox mode to the default Twig environment, making it safe to evaluate untrusted code.
  • TwigExtensionProfilerExtension: Enables the built-in Twig profiler.
  • TwigExtensionOptimizerExtension: Optimizes the node tree before compilation.
  • TwigExtensionStringLoaderExtension: Defines the template_from_string function to allow loading templates from string in a template.

The Core, Escaper, and Optimizer extensions are registered by default.

Built-in Extensions

This section describes the features added by the built-in extensions.

Read the chapter about extending Twig to learn how to create your own extensions.

Core Extension

The core extension defines all the core features of Twig:

Escaper Extension

The escaper extension adds automatic output escaping to Twig. It defines a tag, autoescape , and a filter, raw .

When creating the escaper extension, you can switch on or off the global output escaping strategy:

If set to html , all variables in templates are escaped (using the html escaping strategy), except those using the raw filter:

You can also change the escaping mode locally by using the autoescape tag:

The autoescape tag has no effect on included files.

The escaping rules are implemented as follows:

Literals (integers, booleans, arrays, . ) used in the template directly as variables or filter arguments are never automatically escaped:

Expressions which the result is a literal or a variable marked safe are never automatically escaped:

Objects with a __toString method are converted to strings and escaped. You can mark some classes and/or interfaces as being safe for some strategies via EscaperExtension::addSafeClass() :

Escaping is applied before printing, after any other filter is applied:

The `raw` filter should only be used at the end of the filter chain:

Automatic escaping is not applied if the last filter in the chain is marked safe for the current context (e.g. html or js ). escape and escape(‘html’) are marked safe for HTML, escape(‘js’) is marked safe for JavaScript, raw is marked safe for everything.

Note that autoescaping has some limitations as escaping is applied on expressions after evaluation. For instance, when working with concatenation, << foo|raw

bar >> won’t give the expected result as escaping is applied on the result of the concatenation, not on the individual variables (so, the raw filter won’t have any effect here).

Sandbox Extension

The sandbox extension can be used to evaluate untrusted code. Access to unsafe attributes and methods is prohibited. The sandbox security is managed by a policy instance. By default, Twig comes with one policy class: TwigSandboxSecurityPolicy . This class allows you to white-list some tags, filters, properties, and methods:

With the previous configuration, the security policy will only allow usage of the if tag, and the upper filter. Moreover, the templates will only be able to call the getTitle() and getBody() methods on Article objects, and the title and body public properties. Everything else won’t be allowed and will generate a TwigSandboxSecurityError exception.

The policy object is the first argument of the sandbox constructor:

By default, the sandbox mode is disabled and should be enabled when including untrusted template code by using the sandbox tag:

You can sandbox all templates by passing true as the second argument of the extension constructor:

Profiler Extension

The profiler extension enables a profiler for Twig templates; it should only be used on your development machines as it adds some overhead:

A profile contains information about time and memory consumption for template, block, and macro executions.

You can also dump the data in a Blackfire.io compatible format:

Upload the profile to visualize it (create a free account first):

Optimizer Extension

The optimizer extension optimizes the node tree before compilation:

By default, all optimizations are turned on. You can select the ones you want to enable by passing them to the constructor:

Twig supports the following optimizations:

  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_ALL , enables all optimizations (this is the default value).
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_NONE , disables all optimizations. This reduces the compilation time, but it can increase the execution time and the consumed memory.
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_FOR , optimizes the for tag by removing the loop variable creation whenever possible.
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_RAW_FILTER , removes the raw filter whenever possible.
  • TwigNodeVisitorOptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS , simplifies the creation and access of variables in the compiled templates whenever possible.

Exceptions

Twig can throw exceptions:

  • TwigErrorError : The base exception for all errors.
  • TwigErrorSyntaxError : Thrown to tell the user that there is a problem with the template syntax.
  • TwigErrorRuntimeError : Thrown when an error occurs at runtime (when a filter does not exist for instance).
  • TwigErrorLoaderError : Thrown when an error occurs during template loading.
  • TwigSandboxSecurityError : Thrown when an unallowed tag, filter, or method is called in a sandboxed template.

Источник

Trying to set-up a Craft site on a local environment. The site is currently live and functions well on prod. On the local environment, the site seems to work fine, except that every time I try to access an admin page, I get the following error:

Twig_Error_Runtime

Variable "entry" does not exist in "layouts/main/_layout" at line 29 (C:wampwwwstagecraftappvendortwigtwiglibTwigTemplate.php:332)

#0 C:wampwwwstagecraftstorageruntimecompiled_templatesb354e5036bda0f90c30db509f858e96127617afb2773e83d81aa61dc5b4e29b.php(47): Twig_Template->getContext(Array, 'entry')
#1 C:wampwwwstagecraftappvendortwigtwiglibTwigTemplate.php(279): __TwigTemplate_b3540e5036bda0f90c30db509f858e96127617afb2773e83d81aa61dc5b4e29b->doDisplay(Array, Array)
#2 C:wampwwwstagecraftappvendortwigtwiglibTwigTemplate.php(253): Twig_Template->displayWithErrorHandling(Array, Array)
#3 C:wampwwwstagecraftstorageruntimecompiled_templates95c945c04614017a210d5882c1a2a1f87467f3a26a51d13ab2f7ee1ff3b62ffe.php(26): Twig_Template->display(Array, Array)
#4 C:wampwwwstagecraftappvendortwigtwiglibTwigTemplate.php(279): __TwigTemplate_95c945c04614017a210d5882c1a2a1f87467f3a26a51d13ab2f7ee1ff3b62ffe->doDisplay(Array, Array)
#5 C:wampwwwstagecraftappvendortwigtwiglibTwigTemplate.php(253): Twig_Template->displayWithErrorHandling(Array, Array)
#6 C:wampwwwstagecraftappvendortwigtwiglibTwigTemplate.php(264): Twig_Template->display(Array)
#7 C:wampwwwstagecraftappvendortwigtwiglibTwigEnvironment.php(292): Twig_Template->render(Array)
#8 C:wampwwwstagecraftappservicesTemplatesService.php(220): Twig_Environment->render('404', Array)
#9 C:wampwwwstagecraftappcontrollersBaseController.php(74): CraftTemplatesService->render('404', Array)
#10 C:wampwwwstagecraftappcontrollersTemplatesController.php(203): CraftBaseController->renderTemplate('404', Array)
#11 C:wampwwwstagecraftappframeworkwebactionsCInlineAction.php(49): CraftTemplatesController->actionRenderError()
#12 C:wampwwwstagecraftappframeworkwebCController.php(308): CInlineAction->runWithParams(Array)
#13 C:wampwwwstagecraftappframeworkwebCController.php(286): CController->runAction(Object(CInlineAction))
#14 C:wampwwwstagecraftappframeworkwebCController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#15 C:wampwwwstagecraftappframeworkwebCWebApplication.php(282): CController->run('renderError')
#16 C:wampwwwstagecraftappframeworkbaseCErrorHandler.php(331): CWebApplication->runController('templates/rende...')
#17 C:wampwwwstagecraftappframeworkbaseCErrorHandler.php(204): CErrorHandler->render('error', Array)
#18 C:wampwwwstagecraftappetcerrorsErrorHandler.php(128): CErrorHandler->handleException(Object(CraftHttpException))
#19 C:wampwwwstagecraftappframeworkbaseCErrorHandler.php(129): CraftErrorHandler->handleException(Object(CraftHttpException))
#20 C:wampwwwstagecraftappframeworkbaseCApplication.php(732): CErrorHandler->handle(Object(CExceptionEvent))
#21 [internal function]: CApplication->handleException(Object(CraftHttpException))
#22 {main}

And here is the layouts/main/_layouts code:

{#
 # Layout template
 # ---------------
 #
 # This template defines your site�s global layout. It can be
 # �extended� by other templates to fill in the gaps.
 #
 # See Twig�s Template Inheritance documentation for more details:
 # http://twig.sensiolabs.org/doc/templates.html#template-inheritance
 #}

<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8" />
  <!--[if IE]>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <![endif]-->

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta property="og:locale" content="en_US" />
  <meta property="og:type" content="website" />

  {% block meta %}{% endblock %}

  <head profile="http://www.w3.org/2005/10/profile">
  <link rel="icon" type="image/png" href="{{ seo.favicon[0].getUrl() }}">

  {% if entry.canonicalUrl %}
    <link rel="canonical" href="{{ entry.canonicalUrl }}" />
  {% endif %}

  <title>{% if entry.pageTitle %}{{ entry.pageTitle | raw }}{% else %}{{ entry.title | raw }}{% endif %}</title>
  <meta name="description" content="{% if entry.seoDescription is defined %}{{ entry.seoDescription }}{% else %}{{ seo.seoDescription }}{% endif %}" />
  <meta name="keywords" content="{% if entry.seoKeywords is defined %}{{ entry.seoKeywords }}{% else %}{{ seo.seoKeywords }}{% endif %}" />

  <link rel="home" href="{{ siteUrl }}" />


    <link rel="stylesheet" href="{{ craft.bust.er('/lib/css/dev/base.css') }}">





    <link href="{{ craft.bust.er('/lib/css/parallax.css') }}" type="text/css" rel="stylesheet" data-skrollr-stylesheet />




  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
    <script src="{{ craft.bust.er('/lib/js/ie8.min.js') }}"></script>
  <![endif]-->

  <!-- SHARING -->
  {% if entry is defined %}

    {% if entry.sharingText %}
      {% set description = entry.sharingText %}
    {% elseif entry.seoDescription %}
      {% set description = entry.seoDescription %}
    {% else %}
      {% if entry.section == 'blogPosts' %}
        {% set description = entry.entryContent | trimit(600) %}
      {% elseif socialMedia.sharingText %}
        {% set description = socialMedia.sharingText %}
      {% elseif seo.seoDescription %}
        {% set description = seo.seoDescription %}
      {% else %}
        {% set description = '' %}
      {% endif %}
    {% endif %}

    {%if entry.pageTitle %}
      {% set title = entry.pageTitle %}
    {% else %}
      {% set title = entry.title %}
    {% endif %}

    <meta property="og:title" content="{{ title }}" />
    <meta property="og:description" content="{{ description }}" />
    {# SHARING IMAGE // defaults to global.  Otherwise set the block in your template #}
    {% include "layouts/main/partials/_sharingImage" %}
  {% endif %}
    <meta property="og:url" content="{{ entry.Url }}" />

<!-- Start Visual Website Optimizer Asynchronous Code -->
<script type='text/javascript'>
var _vwo_code=(function(){
var account_id=126816,
settings_tolerance=2000,
library_tolerance=2500,
use_existing_jquery=false,
// DO NOT EDIT BELOW THIS LINE
f=false,d=document;return{use_existing_jquery:function(){return use_existing_jquery;},library_tolerance:function(){return library_tolerance;},finish:function(){if(!f){f=true;var a=d.getElementById('_vis_opt_path_hides');if(a)a.parentNode.removeChild(a);}},finished:function(){return f;},load:function(a){var b=d.createElement('script');b.src=a;b.type='text/javascript';b.innerText;b.onerror=function(){_vwo_code.finish();};d.getElementsByTagName('head')[0].appendChild(b);},init:function(){settings_timer=setTimeout('_vwo_code.finish()',settings_tolerance);this.load('//dev.visualwebsiteoptimizer.com/j.php?a='+account_id+'&u='+encodeURIComponent(d.URL)+'&r='+Math.random());var a=d.createElement('style'),b='body{opacity:0 !important;filter:alpha(opacity=0) !important;background:none !important;}',h=d.getElementsByTagName('head')[0];a.setAttribute('id','_vis_opt_path_hides');a.setAttribute('type','text/css');if(a.styleSheet)a.styleSheet.cssText=b;else a.appendChild(d.createTextNode(b));h.appendChild(a);return settings_timer;}};}());_vwo_settings_timer=_vwo_code.init();
</script>
<!-- End Visual Website Optimizer Asynchronous Code -->

</head>

<body class="craft page-{{ craft.request.lastSegment() }} section-{{ craft.request.firstSegment() }}">

<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-5N2WB8"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-5N2WB8');</script>
<!-- End Google Tag Manager -->

<div>

  {# COOKIE NOTIFICATION FOR EU USERS - Hidden by default.  Ajax call to /api/showCookieNotification.html may cause this to appear if user is visiting site for first time in EU (uses session cookie) #}
  <div id="cookieNotice" class="alert alert-success alert-dismissible">
    <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          {{ default.cookieNotice }}
        </div>
      </div>
    </div>
  </div>

  {% include "layouts/main/partials/_mainNav.html" %}

  <div id="skrollr-body">

      {% set _layout = block('layout') %}
      {% if _layout is not empty %}
          {{ _layout|raw }}
       {% else %}

          {% block content %}
            <p>If you see me, you haven�t set your <code>{% verbatim %}{% block content %}�{% endblock %}{% endverbatim %}</code> yet.</p>
            <p>See Twig�s <a href="http://twig.sensiolabs.org/doc/templates.html#template-inheritance">Template Inheritance</a> documentation for an explanation.</p>
          {% endblock %}


      {% endif %}

      {% include "layouts/main/partials/_mobileNav.html" %}

      {% include "layouts/main/partials/_footerNav.html" %}

  </div><!-- END #skrollr-body -->


    <script type="text/javascript" src="{{ craft.bust.er('/lib/js/dev/vendor.js') }}"></script>




  <script type="text/javascript" defer="defer" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53a9b2ec75518a77"></script>


  <!-- TYPEKIT -->
  <script src="//use.typekit.net/nfj8gcg.js"></script>
  <script>try{Typekit.load();}catch(e){}</script>

  {{ getFootHtml() }}


    <script type="text/javascript" src="{{ craft.bust.er('/lib/js/dev/main.js') }}"></script>







</div>

</body>
</html>

Any idea what’s going on here and possible fixes?

Thanks!

Понравилась статья? Поделить с друзьями:
  • Twain reportlasterror an error occurred что делать
  • Twain invalid source name ошибка 1с
  • Twain driver is already running kyocera ошибка
  • Twain acquire error 1c
  • Tw007 ошибка сканера