当前位置: 代码迷 >> 综合 >> 【Dash】如何在Dash Project中使用html, css 或 Java Script
  详细解决方案

【Dash】如何在Dash Project中使用html, css 或 Java Script

热度:100   发布时间:2023-11-14 11:51:07.0

官方教程:https://dash.plot.ly/external-resources

一、CSS+JS

1.1 包含内部css或JS文件

保证css,js文件在该目录下即可自动加载;img和ico文件相同:src='/assets/image.png';

从CDN上托管的文件夹加载资源

import dash
import dash_html_components as htmlapp = dash.Dash(__name__,assets_external_path='http://your-external-assets-folder-url/'
)
app.scripts.config.serve_locally = False

1.2 加载外部css和js

app.scripts.append_script({"external_url": my_js_url
}) 

或者

import dash
import dash_html_components as html# external JavaScript files
external_scripts = ['https://www.google-analytics.com/analytics.js',{'src': 'https://cdn.polyfill.io/v2/polyfill.min.js'},{'src': 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.js','integrity': 'sha256-Qqd/EfdABZUcAxjOkMi8eGEivtdTkh3b65xCZL4qAQA=','crossorigin': 'anonymous'}
]# external CSS stylesheets
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css',{'href': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css','rel': 'stylesheet','integrity': 'sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO','crossorigin': 'anonymous'}
]app = dash.Dash(__name__,external_scripts=external_scripts,external_stylesheets=external_stylesheets)app.layout = html.Div()if __name__ == '__main__':app.run_server(debug=True)

二、HTML

2.1 自定义Dash的HTML索引模板

选择1:

import dash
import dash_html_components as htmlexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']app = dash.Dash(__name__, external_stylesheets=external_stylesheets)app.index_string = '''
<!DOCTYPE html>
<html><head>{%metas%}<title>{%title%}</title>{%favicon%}{%css%}</head><body><div>My Custom header</div>{%app_entry%}<footer>{%config%}{%scripts%}{%renderer%}</footer><div>My Custom footer</div></body>
</html>
'''app.layout = html.Div('Simple Dash App')if __name__ == '__main__':app.run_server(debug=True)

选择2:

import dash
import dash_html_components as htmlclass CustomDash(dash.Dash):def interpolate_index(self, **kwargs):# Inspect the arguments by printing themprint(kwargs)return '''<!DOCTYPE html><html><head><title>My App</title></head><body><div id="custom-header">My custom header</div>{app_entry}{config}{scripts}{renderer}<div id="custom-footer">My custom footer</div></body></html>'''.format(app_entry=kwargs['app_entry'],config=kwargs['config'],scripts=kwargs['scripts'],renderer=kwargs['renderer'])app = CustomDash()app.layout = html.Div('Simple Dash App')if __name__ == '__main__':app.run_server(debug=True)

 

 

  相关解决方案