0

I've tried this in vain

<img id="previewHolder" width="100%" height="100%" src="{{ asset('bundles/hearwegohearwego/uploads/articleimg/'~form.img.vars.value)}}"/>

img is an attribute of reusable form type form, path of the image stored in database

necroface
  • 2,545
  • 5
  • 34
  • 55
  • 1
    What does viewing your page source reveal about the value of the `src` attribute at the browser? – unrivaledcreations Jul 29 '15 at 00:35
  • Only `bundles/hearwegohearwego/uploads/articleimg/` – necroface Jul 29 '15 at 03:13
  • Then `form.img.vars.value` is actually NULL. It looks like you're trying to combine JavaScript with Twig; and JavaScript values can't be used as part of an argument in a Twig function call, because the `Twig::render(...)` function calls long before the client-side interprets any of the JavaScript code. See my answer below. – unrivaledcreations Jul 29 '15 at 18:23

1 Answers1

1

Short Answer

If you want to use the Twig::asset(...) function to render an image, (1) the image must already exist on the server and (2) you must pass asset(...) a relative pathname leading to that image's location.

In your controller:

$templateValues['imageFile'] = $name_of_uploaded_file;
$template = $twig->loadTemplate('index.html');
echo $template->render( $templateValues );

Your Twig implementation may differ; for example, with Symfony2, Silex, etc. The important thing is to use your controller or PHP code to determine the image's file name, and provide that string to Twig as part of the normal associative array passed to the Twig::render(...) function.

In Twig:

{% set imagePath = 'bundles/hearwegohearwego/uploads/articleimg/' ~ imageFile %}
<img id="previewHolder" width="100%" height="100%" src="{{ asset( imagePath ) }}"/>

Explanation

Your image has the id="previewHolder" attribute, which indicates that you are using this image as a temporary placeholder in a dynamic way, whereupon an image chosen by a user is uploaded, and then shown in that image - probably before POST-ing the form (including that image) to your website. Twig cannot resolve that image for you on the server-side, so JavaScript must be used to render that image.

In Twig, any variables you wish to use must be passed to Twig by your controller; for example:

echo $template->render(array('the' => 'variables', 'go' => 'here'));

In your question, there is a constant concatenated with a variable. That variable is called form.img.vars.value which is not recognized by Twig as one of the values passed to the Twig::render(...) function. It appears to be JavaScript, which will not run (on the client-side) until the Twig actions have already been taken (on the server-side).

If my speculation is correct and you want to preview an image during the upload process, see the question: Preview an image before it is uploaded.

Community
  • 1
  • 1