Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[Asset] added the component#13234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
fabpot merged 4 commits intosymfony:2.7fromfabpot:asset-component
Feb 10, 2015
Merged

Conversation

@fabpot
Copy link
Member

QA
Bug fix?yes
New feature?yes
BC breaks?no
Deprecations?yes
Tests pass?yes
Fixed tickets#10973,#11748,#11876,#4883,#12474
LicenseMIT
Doc PRnot yet

TODO:

  • submit documentation PR

The current Asset sub-namespace in Templating has several (major) problems:

To decouple this feature and make it reusable in Silex for instance, and to fix the design issues and make it more extensible, I've decided to extract and rework the features provided into a new Asset component.

Basically, this component allows the developer to easily manage asset URLs: versioning, paths, and hosts.

Both the new and the old asset management features are kept in this PR to avoid breaking BC; the old system is of course deprecated and automatically converted to the new one.

Even if the features are quite similar, and besides the flexilibity of the new system, here are some differences:

  • PathPackage always prepend the path (even if the given path starts with/).
  • Usage is stricter (for instance,PathPackage requires a basePath to be passed andUrlPackage requires that at least on URL is passed).
  • In the configuration, named packages inherits from the version and version format of the default package by default.
  • It is not possible to override the version when asking for a URL (instead, you can define your own version strategy implementation -- the use cases explained in[Templating] Added ability to set a specific version of the asset #6092 are easily implemented this way).
  • It's not possible to generate absolute URLs (seeURL manipulations as a Twig extension #13264 for a better alternative using composition; so usingabsolute_url(asset_path('me.png')) should work).
    [assets] bundle package #10973 was about adding shortcuts for bundles, which is a good idea; but given that you rarely reference built-in or third-party bundle assets and because we now have a one-bundle default approach named AppBundle, the same can be achieved with just a simple piece of configuration with the new assets feature:
framework:assets:packages:app:base_path:/bundles/app/img:base_path:/bundles/app/images/

Then:

{{ asset('images/me.png', 'app') }}# /bundles/app/images/me.png{{ asset('me.png', 'img') }}# /bundles/app/images/me.png

#12474 discussed the possibility to add a version for absolute URL. It's not possible to do that in a generic way as the version strategy involves both the version and the path, which obviously cannot work when the path is an absolute URL already. Instead, one should use theasset_version Twig function to add the version manually.

@fabpotfabpotforce-pushed theasset-component branch 8 times, most recently frome716f76 toc9e9565CompareJanuary 4, 2015 18:30
This was referencedJan 4, 2015
@fabpotfabpotforce-pushed theasset-component branch 2 times, most recently from10c720c to95f7b7fCompareJanuary 5, 2015 07:18
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

wouldn't it be betterdefaultNull?

@acasademont
Copy link
Contributor

I like the overall simplification, no more weird behaviour depending on wether your packages contain ssl/non-ssl urls.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

👍 thanks for this "totaly" standalone component !

@fabpotfabpotforce-pushed theasset-component branch 8 times, most recently from6439559 tob0bc46fCompareJanuary 5, 2015 13:14

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

"Generating an absolute URL [...]" or "Generating absolute URLs [...]"?

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

fixed

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

this cannot benull anymore

@fabpotfabpot merged commit0750d02 intosymfony:2.7Feb 10, 2015
fabpot added a commit that referenced this pull requestFeb 10, 2015
This PR was merged into the 2.7 branch.Discussion----------[Asset] added the component| Q             | A| ------------- | ---| Bug fix?      | yes| New feature?  | yes| BC breaks?    | no| Deprecations? | yes| Tests pass?   | yes| Fixed tickets |#10973,#11748,#11876,#4883,#12474| License       | MIT| Doc PR        | not yetTODO: - [ ] submit documentation PRThe current Asset sub-namespace in Templating has several (major) problems: * It does not cover all use cases (see#10973 and#4883 for some example) * It has some design issues (relies on the Request instance and so requires the request scope, very coupled with the PHP templating sub-system, see#11748 and#11876)To decouple this feature and make it reusable in Silex for instance, and to fix the design issues and make it more extensible, I've decided to extract and rework the features provided into a new Asset component.Basically, this component allows the developer to easily manage asset URLs: versioning, paths, and hosts.Both the new and the old asset management features are kept in this PR to avoid breaking BC; the old system is of course deprecated and automatically converted to the new one.Even if the features are quite similar, and besides the flexilibity of the new system, here are some differences: * `PathPackage` always prepend the path (even if the given path starts with `/`). * Usage is stricter (for instance, `PathPackage` requires a basePath to be passed and `UrlPackage` requires that at least on URL is passed). * In the configuration, named packages inherits from the version and version format of the default package by default. * It is not possible to override the version when asking for a URL (instead, you can define your own version strategy implementation -- the use cases explained in#6092 are easily implemented this way). * It's not possible to generate absolute URLs (see#13264 for a better alternative using composition; so using `absolute_url(asset_path('me.png')) should work)`.#10973 was about adding shortcuts for bundles, which is a good idea; but given that you rarely reference built-in or third-party bundle assets and because we now have a one-bundle default approach named AppBundle, the same can be achieved with just a simple piece of configuration with the new assets feature:```ymlframework:    assets:        packages:            app:                base_path: /bundles/app/            img:                base_path: /bundles/app/images/```Then:```jinja{{ asset('images/me.png', 'app') }}# /bundles/app/images/me.png{{ asset('me.png', 'img') }}# /bundles/app/images/me.png```#12474 discussed the possibility to add a version for absolute URL. It's not possible to do that in a generic way as the version strategy involves both the version and the path, which obviously cannot work when the path is an absolute URL already. Instead, one should use the `asset_version` Twig function to add the version manually.Commits-------0750d02 removed usage of the deprecated forms of asset() in the core frameworkf74a1f2 renamed asset_path() to asset() and added a BC layer4d0adea [Asset] added a NullContext classd33c41d [Asset] added the component
@fabpotfabpot deleted the asset-component branchFebruary 12, 2015 09:32
@svassaux
Copy link

The following does not work anymore:

img src="{{ asset('images/user.png', 'images') | imagine_filter('default') }}" alt="Image de profil"

seehttp://stackoverflow.com/questions/33200339/symfony-2-7-asset-component-not-working-with-imagine-filter

@jakzal
Copy link
Contributor

@svassaux if you think there's a bug, please create a new issue.

@12th
Copy link

If use absolute_url() for image from the CLI the url is without host, because masterRequest is empty.
Please tell me how get absolute url for image, for example in email?

@acasademont
Copy link
Contributor

@12th
Copy link

@acasademont
Yes, I saw this example, but absolute route work only for twig url() for tag , and when try use absolute for asset(), this not work.

/**     * Send email to player     *     * @param Letter $letter     * @return int     */    public function sendLetter(Letter $letter)    {        $context = [];        $toEmail = '';        $fromEmail = '';        $result = null;        $email = $letter->getEmail();        switch ($email->getType()) {            case Email::TYPE_INVITE:                $mailer = $this->parameters['mailers'][$letter->getEmail()->getGateway()->getSlug()];                $invite = $this->_inviteHelper->findOneBy(['id' => $letter->getEntityId()]);                $context['token'] = $letter->getToken();                $context['entity'] = $this->_emailHelper->getEntity($letter);                $toEmail = $invite->getEmail();                $fromEmail = [$mailer['send_from'] => $mailer['sender_name']];                break;            default:                $mailer = $this->parameters['mailers']['default'];        }        // For CLI mailing, because request does not has http request        $requestContext = $this->router->getContext();        $requestContext            ->setHost($mailer['site_http_host'])            ->setScheme($mailer['site_http_schema'])        ;        // Change default settings for sending special        $transport = \Swift_SmtpTransport::newInstance($mailer['host'], $mailer['port'], true)            ->setUsername($mailer['username'])            ->setPassword($mailer['password'])            ->setEncryption($mailer['encryption'])        ;        $this->mailer = \Swift_Mailer::newInstance($transport);        $this->twig->setLoader(new \Twig_Loader_Array(['letter' => $email->getBodyHtml()]));        $context  = $this->twig->mergeGlobals($context);        $htmlBody = $this->twig->render('letter', $context);        // Catch incorrect email        try {            $message = \Swift_Message::newInstance()                ->setSubject($email->getSubject())                ->setFrom($fromEmail)                ->setTo($toEmail);            if ( ! empty($htmlBody)) {                $message                    ->setBody($htmlBody, 'text/html')                    ->addPart($email->getBodyText(), 'text/plain')                ;            } else {                $message->setBody($email->getBodyText());            }            $result = $this->mailer->send($message);        } catch (\Exception $ex) {            $letter->setStatus(Letter::STATUS_ERROR_SEND);            $this->_emailHelper->updateLetter($letter);            VarDumper::dump($ex->getMessage());            return false;        }        $letter->setStatus(Letter::STATUS_SENT);        if ( ! (bool)$result) {            $letter->setStatus(Letter::STATUS_ERROR_SEND);        }        $this->_emailHelper->updateLetter($letter);        return $result;    }

Services

app_main.mailer:      class: App\MainBundle\Model\Mailer      arguments:          - @mailer          - @router          - @twig          - @swiftmailer.transport.real

Config:

swiftmailer:    transport:  "%mailer_transport%"    host:       "%mailer_host%"    username:   "%mailer_user%"    password:   "%mailer_password%"    port:       "%mailer_port%"    encryption: "%mailer_encryption%"    auth_mode:  login    spool:     { type: memory }

When try use flush the queue after send, catch error User Error: Call to undefined method getSpool

...$result = $this->mailer->send($message);// now manually flush the queue$spool = $this->mailer->getTransport()->getSpool();$spool->flushQueue($this->_esmtpTransport);

If dump getMasterRequest() in generateAbsoluteUrl(), the request is null, and I get path without host

/**     * Returns the absolute URL for the given absolute or relative path.     *     * This method returns the path unchanged if no request is available.     *     * @param string $path The path     *     * @return string The absolute URL     *     * @see Request::getUriForPath()     */    public function generateAbsoluteUrl($path)    {        if (false !== strpos($path, '://') || '//' === substr($path, 0, 2)) {            return $path;        }       VarDumper::dump($this->requestStack->getMasterRequest());die;        if (!$request = $this->requestStack->getMasterRequest()) {            return $path;        }        if (!$path || '/' !== $path[0]) {            $prefix = $request->getPathInfo();            $last = strlen($prefix) - 1;            if ($last !== $pos = strrpos($prefix, '/')) {                $prefix = substr($prefix, 0, $pos).'/';            }            return $request->getUriForPath($prefix.$path);        }        return $request->getSchemeAndHttpHost().$path;    }

@acasademont
Copy link
Contributor

@12th
Copy link

And whether it is possible to dynamically change depending on the sender's e-mail settings?

@acasademont
Copy link
Contributor

mmm you would need to create a "package" for each of them and have different url's in there

http://symfony.com/doc/current/reference/configuration/framework.html#packages

@12th
Copy link

Alternatively I try, but it's not the best option because the sender to the individual letters is different and is selected from the panel

@12th
Copy link

If set host in package base_path

framework:    assets:        version_format: %%s?%%s        packages:            img_email:                version: 15.09.22                base_path: http://site.com/email/

template lokk like:

<body>

the html look like

<body style=3D"margin:0; padding: 0; background:#2e2b2a url(/http://site.com/email/main/bg.png) top center repeat;">

with slash at the beginning of the address

@12th
Copy link

as a solution to use

 // fix absolute url to image, because absolute_url() not work from CLI  $htmlBody = str_replace('%site_http_host%', 'http://'.$mailer['site_http_host'], $htmlBody);

@12th
Copy link

Solution there#15448

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

No reviews

Assignees

No one assigned

Labels

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

11 participants

@fabpot@acasademont@wouterj@stof@svassaux@jakzal@12th@lsmith77@mickaelandrieu@albertplaya@xabbuh

[8]ページ先頭

©2009-2025 Movatter.jp