Apply tinyMCE settings to dynamicly created textar

2019-09-05 17:55发布

问题:

I create lots of tinymce with django:

<script type="text/javascript" src="{{ STATIC_PREFIX }}js/tiny_mce/tiny_mce.js"
</script>
<script type="text/javascript" src="{{ STATIC_PREFIX }}js/tiny_mce/tiny_init.js"
</script>

<script type="text/javascript">
tinyMCE.settings = configArray[1];
tinyMCE.execCommand('mceAddControl', true, "tobs");
</script>
        {% for obs in obss %}
        <div id="obs">
          DateTime:<samp>{{ obs.date }}</samp><br>
          Description: <br>
           <textarea id="tobs" class="ro">{{ obs.description }}</textarea><br>
           {% for f in obs.content %}
              File:
              <a href=Observations/{{f}} title="download file">
               <script>
                 get_name("{{f}}")
               </script>
              </a><br>
           {% endfor %}
           Author:<samp>{{ obs.user }}</samp><br>
           Type:<samp>{{ obs.category }}</samp><br><br>
        </div>
        {% empty %}
            <br>Sorry, no observations in DataBase.
        {% endfor %}

But problem is thet only first textarea is getting my settings from configArray[1] and looks like tinymce, second and third are just simple textarea with no tinymce settings.

How can I change whis?

回答1:

Change the id for each textarea. ids are supposed to be unique in HTML, but your for loop is creating multiple textareas with the same id. TinyMCE is trying to render the textarea with id="tobs" and gets confused when it finds more than one. You could try:

{% for obs in obss %}
    ...
    {% with "tobs"|add:forloop.counter as area_id %}
        <textarea id={{ area_id }} class="ro">{{ obs.description }}</textarea<br>
    {% endwith %}
    ...
{% endfor %}

That should make your textareas with ids: tobs1, tobs2, tobs3,..., which should fix the problem.

Read more here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

And here: TinyMCE not working when loading two textareas

But there should be a more elegant solution to this problem. So far I've been able to find this example, which uses class to distinguish between textareas and doesn't use ids at all, which contradicts the solution from the last link: http://www.tinymce.com/tryit/3_x/multiple_configs.php