简体   繁体   English

Symfony2 ::加载自定义表单类型时添加资产

[英]Symfony2 :: Add assets when a custom formtype is loaded

I've created a service for loading a custom form-type. 我已经创建了用于加载自定义表单类型的服务。 But is it possible whenever I call this service, that automatically some javascript is autmaticlly loaded in mine block 'footer_javascripts' ? 但是,每当我调用此服务时,是否有可能自动将一些JavaScript自动加载到我的代码块“ footer_javascripts”中? Because I don't want to load every time all the javascript. 因为我不想每次都加载所有JavaScript。

At the moment, I'm doing it like this: 目前,我正在这样做:

{% block wysiwyg_widget %}
    {% block footer_javascripts %}
       <script src="{{ asset('bundles/acme/js/demo/demo1.js') }}"></script>
       <script src="{{ asset('bundles/acme/js/demo/demo2.js') }}"></script>
   {% endblock %}
{% endblock %}

But now the code is in the content, and I would like it in the block 'footer_javascript' and calling {{ parent() }} doesn't work. 但是现在代码在内容中了,我想在代码块“ footer_javascript”中调用{{parent()}}不起作用。

Thanks in advance 提前致谢

You can combine your Javascript files (and also CSS files) to reduce the number of HTTP requests. 您可以合并Javascript文件 (以及CSS文件)以减少HTTP请求的数量。

You can use a variable to decide if the Javascript need to be loaded. 您可以使用变量来确定是否需要加载Javascript。

First, define it on your controller: 首先,在您的控制器上定义它:

public function homepageAction($no_locale = false)
{
    [...]

    $customFormType = null;

    if (/* test if you used the custom form-type */)
    {
            $customFormType = true;
    }

    return $this->render('SCACWebsiteBundle:Default:homepage.html.twig',
        array(
            'form' => $form,
            'customFormType ' => $customFormType
        )
    );
}

Then you can test the variable in Twig: 然后,您可以在Twig中测试变量:

{% if ((customFormType is defined) and (customFormType)) %}
    {% javascripts
        'bundles/acme/js/demo/demo1.js'
        'bundles/acme/js/demo/demo2.js' %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endif %}

By using (customFormType is defined) , you don't need to declare the variable in all of your controller. 通过使用(customFormType is defined) ,您无需在所有控制器中声明变量。 This test ensures that there will be no error if the variable is not defined. 此测试确保如果未定义变量,则不会有错误。 The condition (customFormType) will be true only if the custom form-type will be loaded, even if it's the same controller, with or without the custom form-type. 条件(customFormType)仅在加载有或没有自定义表单类型的情况下加载自定义表单类型(即使它是同一控制器(customFormType)也将为true。 If the custom form-type is not loaded, customFormType will have the null value and the result of the condition will be false. 如果未加载自定义表单类型,则customFormType将具有null值,并且条件的结果将为false。

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

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