I am using Symfony2, Twig and Twitter Bootstrap. I haven't found there any solution for the following problem.
In certain parts of my web application, I am using tabled displayed relatively (using percentages).
For those values of fields that are too long to fit in the "reserved" space for them, I am using Twig or Javascript functions that truncate the strings so they can fit properly. The question is:
Is there any way to make the length of that truncation be dynamically set according to the displayed width? Note that, since the table is dynamically displayed and reset on window resizing, those widths will change on the go.
Any way to truncate the strings dynamically?
Some pieces of code I am using:
TWIG:
<td>{{ p.name|truncate(50) }}</td>
JAVASCRIPT:
// Truncates a string and adds "..."
function truncate_string(str, len){
if (str.length > len)
return str.substring(0, len) + "...";
else
return str;
}
The solution would be to set dynamically that len
parameter according to the width of the TD and to the resulting width of the string to be displayed.
Do we know through jQuery, CSS or whatever, the exact width of a string according to the font size and type? Or, in other words, how can we know the maximum number of a string will be able to have having a certain width in pixels?