Search code examples
wysihtml5

Attributes are removed in HTML code


I use wysihtml5. When you insert an image

<img alt src="src" media_img_id="123" data-title="title" data-author="author" />

The result is

<img alt src="src" />

Rules for img

"img": {
    "remove": 0,
        "check_attributes": {
            "width": "numbers",
            "alt": "alt",
            "src": "url", // if you compiled master manually then change this from 'url' to 'src'
            "height": "numbers",
    "media_img_id": "numbers"
        },
        "add_class": {
            "align": "align_img"
        }
    },

How to make the attributes generally not removed?


Solution

  • I have the same task today to extend abilities of this editor. You should add your attributes in special object: I'm using additionaly bootstrap3-wysihtml5 - https://github.com/schnawel007/bootstrap3-wysihtml5 . The object that should be added with new attributes for element:

    var defaultOptions = $.fn.wysihtml5.defaultOptions = { 
      /../
    
      "img": {
        "check_attributes": 
              {
          "width": "numbers",
          "alt": "alt",
          "data-encid": "alt", <<-here is my custom attribute
          "src": "url",
          "height": "numbers"
          }
        },
    
     /../
    }
    

    and in wysihtml5.js you should add condition in which your src attribute is differs from classical source (that this plugin expected) "http://example.png".

    line 4922:

    if (checkAttributes) {
          for (attributeName in checkAttributes) {
            method = attributeCheckMethods[checkAttributes[attributeName]];
            if (!method) {
              continue;
            }
            newAttributeValue = method(_getAttribute(oldNode, attributeName));
            if (typeof(newAttributeValue) === "string") {
              attributes[attributeName] = newAttributeValue;
            }
          }
        }
    

    replace with:

    if (checkAttributes) {
          for (attributeName in checkAttributes) {
            method = attributeCheckMethods[checkAttributes[attributeName]];
            if (!method) {
              continue;
            }
            newAttributeValue = (attributeName == "src" && checkAttributes["data-encid"])
                ? oldNode.src
                : method(_getAttribute(oldNode, attributeName));
            if (typeof(newAttributeValue) === "string") {
              attributes[attributeName] = newAttributeValue;
            }
          }
        }
    

    Here I just copy the src attribute value without checking through wysihtml5.js core.

    Hope this helps!