How to make line feed code valid - symfony

I have entity like
/**
* #ORM\Column(type="text",nullable=true)
*
*/
private $freeText;
then I fetch this column in php and put this in twig.
{{ freeText }}
But it ignores the line feed code.
I think I have to change line feed code to 'br' tag though,where and how should I do this?
Is there any special function on twig?

I'm guessing you mean that even if you put newlines in your text, the browser ignores it and displays text in the same line. Yes, you'll need to replace \n characters with <br /> tags, there's a filter for that:
{{ "I like Twig.\nYou will like it too."|nl2br }}
{# outputs
I like Twig.<br />
You will like it too.
#}

I guess the string is being (auto)escaped ... try:
{{ var|raw }} {# var won't be escaped #}
... or ...
{% autoescape false %}
{{ var }}
{% endautoescape %}

Related

compare a input field value to a string or text symfony2

I was trying to learn about framework and Ill be starting under "Symfony", then i got this problem, I create a
{{ form_widget(form.type) }}
equivalent to
<input type="text" class="type" id="type"/>
this element "input" have a value that given by a tab or menu if i click on it, example jumping.how do i compare it to a text using "Symfony" if statement like the logic below.
{% if jumping == "text" %}
//it will do something
{% endif %}
as explained nicely in the symfony docs here you need to use the form.vars.value to get the input field's value
so for someting like {{ form_widget(form.name) }} you would access the values by doing {{ form.vars.value.name }}
in your case it would be
{% if form.vars.value.name == "text" %}
//do something
{% endif %}

How to passe an array to jquery in twig

I have the following code :
{% set aSessionKeys = app.session.get('aBasket')|keys %}
onkeyup="calculatePrice({{ product['product_price'] }},{{ product['product_id'] }},{{ aSessionKeys }})
And I have an error :
Notice: Array to string conversion
Can you help me please? Thx in advance. So exist a solution to passe this array?
I do like this :
{% set aKeys = aSessionKeys|join(',') %}
{{ dump(aKeys) }}
It shows good, but if I passe to jquery :
calculatePrice({{ product['product_price'] }},{{ product['product_id'] }},{{ aKeys }})
When I do in js methode calculatePrice() :
function calculatePrice(price, product_id, aKeys) {
console.log(aKeys);
var x = document.getElementById("product_quantity_"+product_id);
var total_price = price * x.value;
$("#total_price_"+product_id).html(total_price+" <small> MDL</small>");
sum = 0;
$("#total_price_basket").html();
}
It shows only the first value of aKeys
You have very popular error. You are trying to display array. But how do you imagine that? You can use {{ dump(aSessionKeys) }} for that purpose or use first element: {{ aSessionKeys.0 }} (if it is not an array or object).
But if you want to print all values from this array you can run foreach loop:
{% for element in aSessionKeys %}
{# something here #}
{{ element }}
{# something here #}
{% endfor %}
Obviously (as you are using the |keys filter) aSessionKeys contains an array, and by using {{ aSessionKeys }} in the template Twig will try to output the array as a string, which doesn’t work (or at least is not what you want).
To convert the array to a string, you should use Twig’s join() filter, which will concatenate the array values using a given delimiter string. So, if – for instance – you want to join the values using a comma, this would be the code:
{{ aSessionKeys|join(',) }}

Show image name in Twig, relation one to one

I have a one to one relation between Player and Image. I have also this line in my controller:
var_dump($players[0]->getLinkedImage1()->getName());
It shows the name of an image correctly.
And I have also this line in the template:
{% for players in player %}
{{ player.age }}
{{ player.linkedImage1.name }}
{% endfor %}
but I get this error:
Impossible to access an attribute ("name") on a NULL variable ("")
I expected the last line shown the same name as in the controller.
EDIT: finally I found out that the property was public, that was the reason. Anway I still understand it..
My bad !
Look your for loop..
Try
{% for player in players %}
How did you write the property ? linkedImage1?
If you wrote something like linked_image_1 or linkedImage_1 you should call
{{ player.linked_image_1 }}
or
{{ player.linkedImage_1 }}
then twig will call the related getter according to : http://api.symfony.com/2.4/Symfony/Component/DependencyInjection/Container.html#method_camelize
If its a virtual getter you can directly access with :
{{ player.getLinkedImage1().name }}
or {{ player.getLinkedImage1().getName() }} `
You should try
{{ player.getLinkedImage1().getName() }}

Make Twig syntax from string be parsed

I stored a format of shopping order in database, it's like #{{ number }} (it's just a string), how can use this {{ number }} as a execution of Twig.
For example, in my Controller, when I render the view, I also pass a $number variable:
return $this->render('MyBundle:View:index.html.twig', array('number' => 123));
and in my index.html.twig file, it's something like
{% set orderFormat = some_function_to_get_order_format() %}
// orderFormat will be #{{ number }}
// What can I do to print orderFormat to #123
Try template_from_string function.
{{ include(template_from_string("Hello {{ name }}") }}

symfony 2 twig limit the length of the text and put three dots

How can I limit the length of the text, e.g., 50, and put three dots in the display?
{% if myentity.text|length > 50 %}
{% block td_text %} {{ myentity.text}}{% endblock %}
{%endif%}
{{ myentity.text|length > 50 ? myentity.text|slice(0, 50) ~ '...' : myentity.text }}
You need Twig 1.6
why not use twig's truncate or wordwrap filter? It belongs to twig extensions and lib is part of Symfony2.0 as i see.
{{ text|truncate(50) }}
Another one is:
{{ myentity.text[:50] ~ '...' }}
I know this is a very old question, but from twig 1.6 you can use the slice filter;
{{ myentity.text|slice(0, 50) ~ '...' }}
The second part from the tilde is optional for if you want to add something for example the ellipsis.
Edit: My bad, I see the most up-voted answer do make use of the slice filter.
#olegkhuss solution with named UTF-8 Elipsis:
{{ (my.text|length > 50 ? my.text|slice(0, 50) ~ '…' : my.text) }}
#mshobnr / #olegkhuss solution made into a simple macro:
{% macro trunc(txt, len) -%}
{{ txt|length > len ? txt|slice(0, len) ~ '…' : txt }}
{%- endmacro %}
Usage example:
{{ tools.trunc('This is the text to truncate. ', 50) }}
N.b. I import a Twig template containing macros and import it as 'tools' like this (Symfony):
{% import "#AppBundle/tools.html.twig" as tools -%}
Also, I replaced the html character code with the actual character, this should be no problem when using UTF-8 as the file encoding. This way you don't have to use |raw (as it could cause a security issue).
Update for Twig 2 and Twig 3.
truncate filter is not available, instead of it you may use u-filter
here is an example:
{{ 'Lorem ipsum'|u.truncate(8) }}
Lorem ip
{{ 'Lorem ipsum'|u.truncate(8, '...') }}
Lorem...
Note: this filter is part of StringExtension that can be required by
twig/string-extra
An even more elegant solution is to limit the text by the number of words (and not by number of characters). This prevents ugly tear throughs (e.g. 'Stackov...').
Here's an example where I shorten only text blocks longer than 10 words:
{% set text = myentity.text |split(' ') %}
{% if text|length > 10 %}
{% for t in text|slice(0, 10) %}
{{ t }}
{% endfor %}
...
{% else %}
{{ text|join(' ') }}
{% endif %}
Use the truncate filter to cut off a string after limit is reached
{{ "Hello World!"|truncate(5) }} // default separator is ...
Hello...
You can also tell truncate to preserve whole words by setting the second parameter to true. If the last Word is on the the separator, truncate will print out the whole Word.
{{ "Hello World!"|truncate(7, true) }} // preserve words
Here Hello World!
If you want to change the separator, just set the third parameter to your desired separator.
{{ "Hello World!"|truncate(7, false, "??") }}
Hello W??
You can limit in following way. First is starting index and second is number of characters.
**{{ results['text'][4:2] }}**
if anyone needs this from the modern world, since this question is so old, I would do it this way: I would definitely not want to have an incomplete word at the end, therefor I prefer to do it with the following steps:
limiting the wanted length of characters, exploid my text into a bunch of arrays of sentences separated with a comma or a dot depends on your text, remove the last array which represent the incomplete word then joining or imploiding those arrays together and of course do not forget to join them with that dot we removed when exploiding the string of characters, and outside of the twig {{}} add your three dots, with that been said it will look something like this:
{{myentity.text|slice(0,50)|split('.')|slice(0,-1)|join('.')}}...
readeMore
I wrote this simple marco for the same purpose, hope it helps:
{%- macro stringMaxLength(str, maxLength) -%}
{%- if str | length < maxLength -%}
{{ str }}
{%- else -%}
{{ str|slice(0, maxLength) }}...
{%- endif -%}
{%- endmacro -%}
Usage Example #1 (Output: "my long string here ..."):
{{ _self.stringMaxLength("my long string here bla bla bla la", 20) }}
Usage Example #2 (Output: "shorter string!"):
{{ _self.stringMaxLength("shorter string!", 20) }}
Bugginess* in the new Drupal 8 capabilities here inspired us to write our own:
{% if title|length > 32 %}{% set title_array = title|split(' ') %}{% set title_word_count = 0 %}{% for ta in title_array %}{% set word_count = ta|length %}{% if title_word_count < 32 %}{% set title_word_count = title_word_count + word_count %}{{ ta }} {% endif %}{% endfor %}...{% else %}{{ title }}{% endif %}
This takes into consideration both words and characters (*the "word boundary" setting in D8 was displaying nothing).
In addition to Nemo64's comment under olegkhuss's response, I'd like to add that if you need to make the partial text to finishes on a word not a character, u can do this:
entity.text|split(' ', 11)|length > 10 ? entty.text|split(' ', 11)|slice(0, 10)|join(' ') ~ '…' : entity.text
In this example, all text with more than 10 words will be cuted after the 10th word.
It is better to use an HTML character
{{ entity.text[:50] }}…

Resources