In the Yew framework, due to security reasons, it is not directly supported to insert HTML strings into components. However, sometimes we do need to fetch HTML content from the server and display it on the client side. To insert HTML strings in Yew applications, we can leverage the web_sys and gloo libraries to manipulate the DOM, or use the dangerously_set_inner_html method to set it.
Method One: Using web_sys and gloo for DOM Manipulation
For example, if we need to add an HTML string to an element, we can do the following:
rustuse web_sys::Element; use yew::prelude::*; use wasm_bindgen::JsCast; #[function_component(App)] pub fn app() -> Html { use_effect_with_deps(|html_str| { let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let container = document.get_element_by_id("container").unwrap(); let container: Element = container.dyn_into().unwrap(); container.set_inner_html(html_str); || () }, "这里是需要插入的HTML内容".to_string()); html! { <div id="container"></div> } }
Here, we use use_effect_with_deps to listen for changes in the HTML content and set it safely to the specified container element.
Method Two: Using the dangerously_set_inner_html Attribute
Although it is not recommended to directly use HTML strings due to potential XSS attack risks, it can be used with the dangerously_set_inner_html attribute when data security is ensured.
This method is simpler, but it must be used with great care to ensure the input HTML is safe and avoid XSS attacks.
Conclusion
When inserting HTML strings in Yew, it should be handled with care to ensure HTML security. It can be achieved by directly manipulating the DOM or using the dangerously_set_inner_html attribute, but both require ensuring the HTML content is safe and free from potential security risks. Whenever possible, avoid directly inserting HTML and instead use safer content binding methods.