Reputation: 4324
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?
Upvotes: 1
Views: 1571
Reputation: 85
You can extend twig filter to create your own filter or edit your CSS styles / HTML like this
CSS :
table td{
position:relative;
overflow:hidden;
}
table td > span{
display: inline-block;
position:relative;
height: 18px;
min-width: 200px;
}
HTML :
<table>
<tr>
<td><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc imperdiet ante magna, non pretium sem. </span></td>
<td><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc imperdiet ante magna, non pretium sem. </span></td>
</tr>
<tr>
<td><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc imperdiet ante magna, non pretium sem. </span></td>
<td><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc imperdiet ante magna, non pretium sem. </span></td>
</tr>
So your TD content automatically resize and no need to truncate the text.
Upvotes: 2
Reputation: 2733
There is a jQuery plugin to do what you're asking. This won't be achievable with anything other than javascript. Perhaps a CSS wizard might be able to construct a solution by using overflow
and after
attributes. By my judgement that would only work if you had a fixed string appended to every string in the element (the full string would never be shown).
Also check out this older SO answer which is related.
Upvotes: 1