I have a function in twig which selects some values from db and displays a selectbox. I am trying to change the content of the div. The problem is that with innerHTML {{ creates a new line without quote and this is shown like error. It doesnt get the select box because it doesn't have quotes.
$(document).ready(function() {
$type = $("select[name='dtl[USER_TYPE]']");
$type.change(function() {
if ($(this).val() == "AUTOR") {
var content = '{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') }}';
document.getElementById("kodi").innerHTML = '"'+ content + '"';
}
});
});
macros.twig
<select data-placeholder="{{ translate('ZGJIDH_NJE') }}" name="{{ name }}" class="form-control input-sm chosen-select">
<option {% if not options.allowNull %}disabled{% endif %} selected value>{{ translate('ZGJIDH_NJE') }}</option>
{% for f in dataset %}
<option value="{{ f[kodField] }}" {% if f[kodField] | trim == selectedVal %}selected{% endif %}>
{% if f[labelField] %}
{{ f[labelField] }} {% if f[kodField] %}— ({{ f[kodField] }}){% endif %}
{% else %}
{{ f[kodField] }}
{% endif %}
</option>
{% endfor %}
</select>
EDIT this is shown in console. {{ creates a new line without quotes:
var content = "
<select data-placeholder="Zgjidh nje..." name="dtl[USER_TYPE_OBJECT_KOD]" class="form-control input-sm chosen-select">
<option disabled selected value>Zgjidh nje...</option>
</select>
The problem is that your twig syntax is breaking the javascript syntax. See below, just change the '
to "
if ($(this).val() == "AUTOR") {
var content = '{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') }}';
document.getElementById("kodi").innerHTML = '"'+ content + '"';
}
Correct code :
if ($(this).val() == "AUTOR") {
var content = "{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') }}";
document.getElementById("kodi").innerHTML = '"'+ content + '"';
}
Due to the contents of your output JS is breaking as well. U can solve this by extending twig :
$filter = new Twig_SimpleFilter('escape_for_js', function ($string) {
$needles= array(
"\n",
"\r",
'"',
);
$replaces = array(
'',
'',
'\"',
);
return str_replace($needles, $replaces, $string);
});
Add this filter into twig :
$twig = new Twig_Environment($loader);
$twig->addFilter($filter
Using this filter :
var content = "{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') | escape_for_js }}";
More about extending twig here
No need to extend Twig yourself. Just use json_encode
:
var content = {{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') | json_encode }};
Notice the lack of quotes. json_encode will add them for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.