简体   繁体   English

Uncaught ReferenceError:未定义图表,或如何在Twig中包含javascript

[英]Uncaught ReferenceError: Chart is not defined OR how to include javascript in Twig

In my Symfony project I try to make use of Chartjs.org's javascript. 在我的Symfony项目中,我尝试使用Chartjs.org的javascript。

I put the chart.js file right there where all other javascript files are located and in javascript.html I include the file so that it is available across the project. 我将chart.js文件放在所有其他javascript文件所在的位置,并在javascript.html中包含了该文件,以便在整个项目中都可以使用它。

<script src="assets/js/chart.js"></script>

In my twig template I try to instantiate Chart like this: 在我的树枝模板中,我尝试实例化Chart,如下所示:

<canvas id="myChart" width="400" height="400"></canvas>

<script>
    var ctx = document.getElementById("myChart").getContext("2d");
    var myNewChart = new Chart(ctx);
</script>

This throws an error: Uncaught ReferenceError: Chart is not defined 这将引发错误:未捕获的ReferenceError:图表未定义

What am I missing? 我想念什么?

The answer: 答案:

{% javascripts '@AcmeFooBundle/Resources/public/js/*' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

More details: http://symfony.com/doc/2.1/cookbook/assetic/asset_management.html 更多详细信息: http : //symfony.com/doc/2.1/cookbook/assetic/asset_management.html

As to the question where to put your scripts, maybe this will work: 至于将脚本放在哪里的问题,也许可以解决:

<script src="{{ asset('js/propuestas_public.js') }}" type="text/javascript"></script>

http://symfony.com/doc/2.0/book/templating.html#linking-to-assets http://symfony.com/doc/2.0/book/templating.html#linking-to-assets

The asset function's main purpose is to make your application more portable. 资产功能的主要目的是使您的应用程序更具可移植性。 If your application lives at the root of your host (eg http://example.com ), then the rendered paths should be /images/logo.png. 如果您的应用程序位于主机的根目录下(例如http://example.com ),则呈现的路径应为/images/logo.png。 But if your application lives in a subdirectory (eg http://example.com/my_app ), each asset path should render with the subdirectory (eg /my_app/images/logo.png). 但是,如果您的应用程序位于子目录(例如, http : //example.com/my_app )中,则每个资产路径都应使用子目录(例如,/ my_app / images / logo.png)呈现。 The asset function takes care of this by determining how your application is being used and generating the correct paths accordingly. 资产功能通过确定如何使用您的应用程序并相应地生成正确的路径来解决此问题。

Additionally, if you use the asset function, Symfony can automatically append a query string to your asset, in order to guarantee that updated static assets won't be cached when deployed. 另外,如果使用资产功能,Symfony可以自动将查询字符串追加到资产,以确保部署时不会缓存更新的静态资产。 For example, /images/logo.png might look like /images/logo.png?v2. 例如,/ images / logo.png可能看起来像/images/logo.png?v2。 For more information, see the assets_version configuration option. 有关更多信息,请参阅assets_version配置选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM